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 case "accept":
243 receiveAccept(from, message);
244 break;
245 default:
246 break;
247 }
248 }
249
250 private void receiveAccept(Jid from, Element message) {
251 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
252 if (originatedFromMyself) {
253 if (transition(State.ACCEPTED)) {
254 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
255 this.jingleConnectionManager.finishConnection(this);
256 } else {
257 Log.d(Config.LOGTAG,id.account.getJid().asBareJid()+": unable to transition to accept because already in state="+this.state);
258 }
259 } else {
260 Log.d(Config.LOGTAG,id.account.getJid().asBareJid()+": ignoring 'accept' from "+from);
261 }
262 }
263
264 private void receiveReject(Jid from, Element message) {
265 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
266 //reject from another one of my clients
267 if (originatedFromMyself) {
268 if (transition(State.REJECTED)) {
269 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
270 this.jingleConnectionManager.finishConnection(this);
271 } else {
272 Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
273 }
274 } else {
275 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
276 }
277 }
278
279 private void receivePropose(final Jid from, final Element propose) {
280 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
281 //TODO we can use initiator logic here
282 if (originatedFromMyself) {
283 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
284 } else if (transition(State.PROPOSED)) {
285 startRinging();
286 } else {
287 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
288 }
289 }
290
291 private void startRinging() {
292 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
293 xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
294 }
295
296 private void receiveProceed(final Jid from, final Element proceed) {
297 if (from.equals(id.with)) {
298 if (isInitiator()) {
299 if (transition(State.PROCEED)) {
300 this.sendSessionInitiate();
301 } else {
302 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
303 }
304 } else {
305 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
306 }
307 } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
308 if (transition(State.ACCEPTED)) {
309 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
310 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
311 this.jingleConnectionManager.finishConnection(this);
312 }
313 } else {
314 //TODO a carbon copied proceed from another client of mine has the same logic as `accept`
315 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
316 }
317 }
318
319 private void receiveRetract(final Jid from, final Element retract) {
320 if (from.equals(id.with)) {
321 if (transition(State.RETRACTED)) {
322 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
323 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
324 //TODO create missed call notification/message
325 jingleConnectionManager.finishConnection(this);
326 } else {
327 Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
328 }
329 } else {
330 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
331 }
332 }
333
334 private void sendSessionInitiate() {
335 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
336 setupWebRTC();
337 try {
338 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
339 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
340 Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
341 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
342 sendSessionInitiate(rtpContentMap);
343 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
344 } catch (Exception e) {
345 Log.d(Config.LOGTAG, "unable to sendSessionInitiate", e);
346 }
347 }
348
349 private void sendSessionInitiate(RtpContentMap rtpContentMap) {
350 this.initiatorRtpContentMap = rtpContentMap;
351 this.transitionOrThrow(State.SESSION_INITIALIZED);
352 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
353 Log.d(Config.LOGTAG, sessionInitiate.toString());
354 send(sessionInitiate);
355 }
356
357 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
358 final RtpContentMap transportInfo;
359 try {
360 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
361 transportInfo = rtpContentMap.transportInfo(contentName, candidate);
362 } catch (Exception e) {
363 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
364 return;
365 }
366 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
367 Log.d(Config.LOGTAG, jinglePacket.toString());
368 send(jinglePacket);
369 }
370
371 private void send(final JinglePacket jinglePacket) {
372 jinglePacket.setTo(id.with);
373 //TODO track errors
374 xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
375 }
376
377 public RtpEndUserState getEndUserState() {
378 switch (this.state) {
379 case PROPOSED:
380 if (isInitiator()) {
381 return RtpEndUserState.RINGING;
382 } else {
383 return RtpEndUserState.INCOMING_CALL;
384 }
385 case PROCEED:
386 if (isInitiator()) {
387 return RtpEndUserState.CONNECTING;
388 } else {
389 return RtpEndUserState.ACCEPTING_CALL;
390 }
391 case SESSION_INITIALIZED:
392 return RtpEndUserState.CONNECTING;
393 case SESSION_ACCEPTED:
394 final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
395 if (state == PeerConnection.PeerConnectionState.CONNECTED) {
396 return RtpEndUserState.CONNECTED;
397 } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
398 return RtpEndUserState.CONNECTING;
399 } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
400 return RtpEndUserState.ENDING_CALL;
401 } else if (state == PeerConnection.PeerConnectionState.FAILED) {
402 return RtpEndUserState.CONNECTIVITY_ERROR;
403 } else {
404 return RtpEndUserState.ENDING_CALL;
405 }
406 case REJECTED:
407 case TERMINATED_DECLINED_OR_BUSY:
408 if (isInitiator()) {
409 return RtpEndUserState.DECLINED_OR_BUSY;
410 } else {
411 return RtpEndUserState.ENDED;
412 }
413 case TERMINATED_SUCCESS:
414 case ACCEPTED:
415 case RETRACTED:
416 case TERMINATED_CANCEL_OR_TIMEOUT:
417 return RtpEndUserState.ENDED;
418 case TERMINATED_CONNECTIVITY_ERROR:
419 return RtpEndUserState.CONNECTIVITY_ERROR;
420 }
421 throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
422 }
423
424
425 public void acceptCall() {
426 switch (this.state) {
427 case PROPOSED:
428 acceptCallFromProposed();
429 break;
430 case SESSION_INITIALIZED:
431 acceptCallFromSessionInitialized();
432 break;
433 default:
434 throw new IllegalStateException("Can not accept call from " + this.state);
435 }
436 }
437
438 public void rejectCall() {
439 switch (this.state) {
440 case PROPOSED:
441 rejectCallFromProposed();
442 break;
443 default:
444 throw new IllegalStateException("Can not reject call from " + this.state);
445 }
446 }
447
448 public void endCall() {
449
450 //TODO from `propose` we call `retract`
451
452 if (isInState(State.SESSION_INITIALIZED, State.SESSION_ACCEPTED)) {
453 //TODO during session_initialized we might not have a peer connection yet (if the session was initialized directly)
454
455 //TODO from session_initialized we call `cancel`
456
457 //TODO from session_accepted we call `success`
458
459 webRTCWrapper.close();
460 } else {
461 //TODO during earlier stages we want to retract the proposal etc
462 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": called 'endCall' while in state " + this.state);
463 }
464 }
465
466 private void setupWebRTC() {
467 this.webRTCWrapper.setup(this.xmppConnectionService);
468 this.webRTCWrapper.initializePeerConnection();
469 }
470
471 private void acceptCallFromProposed() {
472 transitionOrThrow(State.PROCEED);
473 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
474 this.sendJingleMessage("accept", id.account.getJid().asBareJid());
475 this.sendJingleMessage("proceed");
476 }
477
478 private void rejectCallFromProposed() {
479 transitionOrThrow(State.REJECTED);
480 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
481 this.sendJingleMessage("reject");
482 jingleConnectionManager.finishConnection(this);
483 }
484
485 private void sendJingleMessage(final String action) {
486 sendJingleMessage(action, id.with);
487 }
488
489 private void sendJingleMessage(final String action, final Jid to) {
490 final MessagePacket messagePacket = new MessagePacket();
491 messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
492 messagePacket.setTo(to);
493 messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
494 Log.d(Config.LOGTAG, messagePacket.toString());
495 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
496 }
497
498 private void acceptCallFromSessionInitialized() {
499 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
500 throw new IllegalStateException("accepting from this state has not been implemented yet");
501 }
502
503 private synchronized boolean isInState(State... state) {
504 return Arrays.asList(state).contains(this.state);
505 }
506
507 private synchronized boolean transition(final State target) {
508 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
509 if (validTransitions != null && validTransitions.contains(target)) {
510 this.state = target;
511 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
512 updateEndUserState();
513 return true;
514 } else {
515 return false;
516 }
517 }
518
519 public void transitionOrThrow(final State target) {
520 if (!transition(target)) {
521 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
522 }
523 }
524
525 @Override
526 public void onIceCandidate(final IceCandidate iceCandidate) {
527 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
528 Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
529 sendTransportInfo(iceCandidate.sdpMid, candidate);
530 }
531
532 @Override
533 public void onConnectionChange(PeerConnection.PeerConnectionState newState) {
534 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
535 updateEndUserState();
536 }
537
538 private void updateEndUserState() {
539 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
540 }
541}