1package eu.siacs.conversations.xmpp.jingle;
2
3import android.util.Log;
4
5import com.google.common.collect.ImmutableList;
6import com.google.common.collect.ImmutableMap;
7
8import org.webrtc.IceCandidate;
9import org.webrtc.PeerConnection;
10
11import java.util.ArrayDeque;
12import java.util.Arrays;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.List;
16import java.util.Map;
17
18import eu.siacs.conversations.Config;
19import eu.siacs.conversations.xml.Element;
20import eu.siacs.conversations.xml.Namespace;
21import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
22import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
23import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
24import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
25import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
26import rocks.xmpp.addr.Jid;
27
28public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
29
30 private static final Map<State, Collection<State>> VALID_TRANSITIONS;
31
32 static {
33 final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
34 transitionBuilder.put(State.NULL, ImmutableList.of(State.PROPOSED, State.SESSION_INITIALIZED));
35 transitionBuilder.put(State.PROPOSED, ImmutableList.of(State.ACCEPTED, State.PROCEED, State.REJECTED, State.RETRACTED));
36 transitionBuilder.put(State.PROCEED, ImmutableList.of(State.SESSION_INITIALIZED));
37 transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(State.SESSION_ACCEPTED));
38 VALID_TRANSITIONS = transitionBuilder.build();
39 }
40
41 private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
42 private final ArrayDeque<IceCandidate> pendingIceCandidates = new ArrayDeque<>();
43 private State state = State.NULL;
44 private RtpContentMap initiatorRtpContentMap;
45 private RtpContentMap responderRtpContentMap;
46
47
48 public JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
49 super(jingleConnectionManager, id, initiator);
50 }
51
52 @Override
53 void deliverPacket(final JinglePacket jinglePacket) {
54 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
55 switch (jinglePacket.getAction()) {
56 case SESSION_INITIATE:
57 receiveSessionInitiate(jinglePacket);
58 break;
59 case TRANSPORT_INFO:
60 receiveTransportInfo(jinglePacket);
61 break;
62 case SESSION_ACCEPT:
63 receiveSessionAccept(jinglePacket);
64 break;
65 case SESSION_TERMINATE:
66 receiveSessionTerminate(jinglePacket);
67 break;
68 default:
69 Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
70 break;
71 }
72 }
73
74 private void receiveSessionTerminate(final JinglePacket jinglePacket) {
75 final Reason reason = jinglePacket.getReason();
76 switch (reason) {
77 case SUCCESS:
78 transitionOrThrow(State.TERMINATED_SUCCESS);
79 break;
80 case DECLINE:
81 case BUSY:
82 transitionOrThrow(State.TERMINATED_DECLINED_OR_BUSY);
83 break;
84 case CANCEL:
85 case TIMEOUT:
86 transitionOrThrow(State.TERMINATED_CANCEL_OR_TIMEOUT);
87 break;
88 default:
89 transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
90 break;
91 }
92 jingleConnectionManager.finishConnection(this);
93 }
94
95 private void receiveTransportInfo(final JinglePacket jinglePacket) {
96 if (isInState(State.SESSION_INITIALIZED, State.SESSION_ACCEPTED)) {
97 final RtpContentMap contentMap;
98 try {
99 contentMap = RtpContentMap.of(jinglePacket);
100 } catch (IllegalArgumentException | NullPointerException e) {
101 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
102 return;
103 }
104 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
105 final Group originalGroup = rtpContentMap != null ? rtpContentMap.group : null;
106 final List<String> identificationTags = originalGroup == null ? Collections.emptyList() : originalGroup.getIdentificationTags();
107 if (identificationTags.size() == 0) {
108 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
109 }
110 for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
111 final String ufrag = content.getValue().transport.getAttribute("ufrag");
112 for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
113 final String sdp = candidate.toSdpAttribute(ufrag);
114 final String sdpMid = content.getKey();
115 final int mLineIndex = identificationTags.indexOf(sdpMid);
116 final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
117 Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
118 if (isInState(State.SESSION_ACCEPTED)) {
119 this.webRTCWrapper.addIceCandidate(iceCandidate);
120 } else {
121 this.pendingIceCandidates.push(iceCandidate);
122 }
123 }
124 }
125 } else {
126 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
127 }
128 }
129
130 private void receiveSessionInitiate(final JinglePacket jinglePacket) {
131 if (isInitiator()) {
132 Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
133 //TODO respond with out-of-order
134 return;
135 }
136 final RtpContentMap contentMap;
137 try {
138 contentMap = RtpContentMap.of(jinglePacket);
139 contentMap.requireContentDescriptions();
140 } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
141 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
142 return;
143 }
144 Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
145 final State oldState = this.state;
146 if (transition(State.SESSION_INITIALIZED)) {
147 this.initiatorRtpContentMap = contentMap;
148 if (oldState == State.PROCEED) {
149 Log.d(Config.LOGTAG, "automatically accepting");
150 sendSessionAccept();
151 } else {
152 Log.d(Config.LOGTAG, "start ringing");
153 //TODO start ringing
154 }
155 } else {
156 Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
157 }
158 }
159
160 private void receiveSessionAccept(final JinglePacket jinglePacket) {
161 if (!isInitiator()) {
162 Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
163 //TODO respond with out-of-order
164 return;
165 }
166 final RtpContentMap contentMap;
167 try {
168 contentMap = RtpContentMap.of(jinglePacket);
169 contentMap.requireContentDescriptions();
170 } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
171 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
172 return;
173 }
174 Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
175 if (transition(State.SESSION_ACCEPTED)) {
176 receiveSessionAccept(contentMap);
177 } else {
178 Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
179 //TODO out-of-order
180 }
181 }
182
183 private void receiveSessionAccept(final RtpContentMap contentMap) {
184 this.responderRtpContentMap = contentMap;
185 org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
186 org.webrtc.SessionDescription.Type.ANSWER,
187 SessionDescription.of(contentMap).toString()
188 );
189 try {
190 this.webRTCWrapper.setRemoteDescription(answer).get();
191 } catch (Exception e) {
192 Log.d(Config.LOGTAG, "unable to receive session accept", e);
193 }
194 }
195
196 private void sendSessionAccept() {
197 final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
198 if (rtpContentMap == null) {
199 throw new IllegalStateException("initiator RTP Content Map has not been set");
200 }
201 setupWebRTC();
202 final org.webrtc.SessionDescription offer = new org.webrtc.SessionDescription(
203 org.webrtc.SessionDescription.Type.OFFER,
204 SessionDescription.of(rtpContentMap).toString()
205 );
206 try {
207 this.webRTCWrapper.setRemoteDescription(offer).get();
208 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
209 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
210 final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
211 sendSessionAccept(respondingRtpContentMap);
212 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription);
213 } catch (Exception e) {
214 Log.d(Config.LOGTAG, "unable to send session accept", e);
215
216 }
217 }
218
219 private void sendSessionAccept(final RtpContentMap rtpContentMap) {
220 this.responderRtpContentMap = rtpContentMap;
221 this.transitionOrThrow(State.SESSION_ACCEPTED);
222 final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
223 Log.d(Config.LOGTAG, sessionAccept.toString());
224 send(sessionAccept);
225 }
226
227 void deliveryMessage(final Jid from, final Element message) {
228 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
229 switch (message.getName()) {
230 case "propose":
231 receivePropose(from, message);
232 break;
233 case "proceed":
234 receiveProceed(from, message);
235 break;
236 case "retract":
237 receiveRetract(from, message);
238 break;
239 case "reject":
240 receiveReject(from, message);
241 break;
242 default:
243 break;
244 }
245 }
246
247 private void receiveReject(Jid from, Element message) {
248 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
249 //reject from another one of my clients
250 if (originatedFromMyself) {
251 if (transition(State.REJECTED)) {
252 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
253 this.jingleConnectionManager.finishConnection(this);
254 } else {
255 Log.d(Config.LOGTAG,"not able to transition into REJECTED because already in "+this.state);
256 }
257 } else {
258 Log.d(Config.LOGTAG,id.account.getJid()+": ignoring reject from "+from+" for session with "+id.with);
259 }
260 }
261
262 private void receivePropose(final Jid from, final Element propose) {
263 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
264 //TODO we can use initiator logic here
265 if (originatedFromMyself) {
266 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
267 } else if (transition(State.PROPOSED)) {
268 startRinging();
269 } else {
270 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
271 }
272 }
273
274 private void startRinging() {
275 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
276 xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
277 }
278
279 private void receiveProceed(final Jid from, final Element proceed) {
280 if (from.equals(id.with)) {
281 if (isInitiator()) {
282 if (transition(State.PROCEED)) {
283 this.sendSessionInitiate();
284 } else {
285 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
286 }
287 } else {
288 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
289 }
290 } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
291 if (transition(State.ACCEPTED)) {
292 Log.d(Config.LOGTAG,id.account.getJid().asBareJid()+": moved session with "+id.with+" into state accepted after received carbon copied procced");
293 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
294 this.jingleConnectionManager.finishConnection(this);
295 }
296 } else {
297 //TODO a carbon copied proceed from another client of mine has the same logic as `accept`
298 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
299 }
300 }
301
302 private void receiveRetract(final Jid from, final Element retract) {
303 if (from.equals(id.with)) {
304 if (transition(State.RETRACTED)) {
305 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
306 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
307 //TODO create missed call notification/message
308 jingleConnectionManager.finishConnection(this);
309 } else {
310 Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
311 }
312 } else {
313 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
314 }
315 }
316
317 private void sendSessionInitiate() {
318 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
319 setupWebRTC();
320 try {
321 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
322 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
323 Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
324 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
325 sendSessionInitiate(rtpContentMap);
326 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
327 } catch (Exception e) {
328 Log.d(Config.LOGTAG, "unable to sendSessionInitiate", e);
329 }
330 }
331
332 private void sendSessionInitiate(RtpContentMap rtpContentMap) {
333 this.initiatorRtpContentMap = rtpContentMap;
334 this.transitionOrThrow(State.SESSION_INITIALIZED);
335 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
336 Log.d(Config.LOGTAG, sessionInitiate.toString());
337 send(sessionInitiate);
338 }
339
340 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
341 final RtpContentMap transportInfo;
342 try {
343 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
344 transportInfo = rtpContentMap.transportInfo(contentName, candidate);
345 } catch (Exception e) {
346 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
347 return;
348 }
349 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
350 Log.d(Config.LOGTAG, jinglePacket.toString());
351 send(jinglePacket);
352 }
353
354 private void send(final JinglePacket jinglePacket) {
355 jinglePacket.setTo(id.with);
356 //TODO track errors
357 xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
358 }
359
360 public RtpEndUserState getEndUserState() {
361 switch (this.state) {
362 case PROPOSED:
363 if (isInitiator()) {
364 return RtpEndUserState.RINGING;
365 } else {
366 return RtpEndUserState.INCOMING_CALL;
367 }
368 case PROCEED:
369 if (isInitiator()) {
370 return RtpEndUserState.CONNECTING;
371 } else {
372 return RtpEndUserState.ACCEPTING_CALL;
373 }
374 case SESSION_INITIALIZED:
375 return RtpEndUserState.CONNECTING;
376 case SESSION_ACCEPTED:
377 final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
378 if (state == PeerConnection.PeerConnectionState.CONNECTED) {
379 return RtpEndUserState.CONNECTED;
380 } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
381 return RtpEndUserState.CONNECTING;
382 } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
383 return RtpEndUserState.ENDING_CALL;
384 } else {
385 return RtpEndUserState.ENDING_CALL;
386 }
387 case REJECTED:
388 case TERMINATED_DECLINED_OR_BUSY:
389 if (isInitiator()) {
390 return RtpEndUserState.DECLINED_OR_BUSY;
391 } else {
392 return RtpEndUserState.ENDED;
393 }
394 case TERMINATED_SUCCESS:
395 case ACCEPTED:
396 case RETRACTED:
397 case TERMINATED_CANCEL_OR_TIMEOUT:
398 return RtpEndUserState.ENDED;
399 case TERMINATED_CONNECTIVITY_ERROR:
400 return RtpEndUserState.CONNECTIVITY_ERROR;
401 }
402 throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
403 }
404
405
406 public void acceptCall() {
407 switch (this.state) {
408 case PROPOSED:
409 acceptCallFromProposed();
410 break;
411 case SESSION_INITIALIZED:
412 acceptCallFromSessionInitialized();
413 break;
414 default:
415 throw new IllegalStateException("Can not accept call from " + this.state);
416 }
417 }
418
419 public void rejectCall() {
420 switch (this.state) {
421 case PROPOSED:
422 rejectCallFromProposed();
423 break;
424 default:
425 throw new IllegalStateException("Can not reject call from " + this.state);
426 }
427 }
428
429 public void endCall() {
430
431 //TODO from `propose` we call `retract`
432
433 if (isInState(State.SESSION_INITIALIZED, State.SESSION_ACCEPTED)) {
434 //TODO during session_initialized we might not have a peer connection yet (if the session was initialized directly)
435
436 //TODO from session_initialized we call `cancel`
437
438 //TODO from session_accepted we call `success`
439
440 webRTCWrapper.close();
441 } else {
442 //TODO during earlier stages we want to retract the proposal etc
443 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": called 'endCall' while in state " + this.state);
444 }
445 }
446
447 private void setupWebRTC() {
448 this.webRTCWrapper.setup(this.xmppConnectionService);
449 this.webRTCWrapper.initializePeerConnection();
450 }
451
452 private void acceptCallFromProposed() {
453 transitionOrThrow(State.PROCEED);
454 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
455 //Note that Movim needs 'accept', correct is 'proceed' https://github.com/movim/movim/issues/916
456 this.sendJingleMessage("proceed");
457
458 //TODO send `accept` to self
459 }
460
461 private void rejectCallFromProposed() {
462 transitionOrThrow(State.REJECTED);
463 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
464 this.sendJingleMessage("reject");
465 jingleConnectionManager.finishConnection(this);
466 }
467
468 private void sendJingleMessage(final String action) {
469 final MessagePacket messagePacket = new MessagePacket();
470 messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
471 messagePacket.setTo(id.with);
472 messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
473 Log.d(Config.LOGTAG, messagePacket.toString());
474 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
475 }
476
477 private void acceptCallFromSessionInitialized() {
478 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
479 throw new IllegalStateException("accepting from this state has not been implemented yet");
480 }
481
482 private synchronized boolean isInState(State... state) {
483 return Arrays.asList(state).contains(this.state);
484 }
485
486 private synchronized boolean transition(final State target) {
487 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
488 if (validTransitions != null && validTransitions.contains(target)) {
489 this.state = target;
490 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
491 updateEndUserState();
492 return true;
493 } else {
494 return false;
495 }
496 }
497
498 public void transitionOrThrow(final State target) {
499 if (!transition(target)) {
500 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
501 }
502 }
503
504 @Override
505 public void onIceCandidate(final IceCandidate iceCandidate) {
506 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
507 Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
508 sendTransportInfo(iceCandidate.sdpMid, candidate);
509 }
510
511 @Override
512 public void onConnectionChange(PeerConnection.PeerConnectionState newState) {
513 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
514 updateEndUserState();
515 }
516
517 private void updateEndUserState() {
518 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
519 }
520}