1package eu.siacs.conversations.xmpp.jingle;
2
3import android.util.Log;
4
5import com.google.common.base.Strings;
6import com.google.common.collect.ImmutableList;
7import com.google.common.collect.ImmutableMap;
8import com.google.common.primitives.Ints;
9
10import org.webrtc.IceCandidate;
11import org.webrtc.PeerConnection;
12
13import java.util.ArrayDeque;
14import java.util.Arrays;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.List;
18import java.util.Map;
19
20import eu.siacs.conversations.Config;
21import eu.siacs.conversations.xml.Element;
22import eu.siacs.conversations.xml.Namespace;
23import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
24import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
25import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
26import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
27import eu.siacs.conversations.xmpp.stanzas.IqPacket;
28import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
29import rocks.xmpp.addr.Jid;
30
31public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
32
33 private static final Map<State, Collection<State>> VALID_TRANSITIONS;
34
35 static {
36 final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
37 transitionBuilder.put(State.NULL, ImmutableList.of(
38 State.PROPOSED,
39 State.SESSION_INITIALIZED,
40 State.TERMINATED_APPLICATION_FAILURE
41 ));
42 transitionBuilder.put(State.PROPOSED, ImmutableList.of(
43 State.ACCEPTED,
44 State.PROCEED,
45 State.REJECTED,
46 State.RETRACTED,
47 State.TERMINATED_APPLICATION_FAILURE
48 ));
49 transitionBuilder.put(State.PROCEED, ImmutableList.of(
50 State.SESSION_INITIALIZED_PRE_APPROVED,
51 State.TERMINATED_SUCCESS,
52 State.TERMINATED_APPLICATION_FAILURE,
53 State.TERMINATED_CONNECTIVITY_ERROR //at this state used for error bounces of the proceed message
54 ));
55 transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(
56 State.SESSION_ACCEPTED,
57 State.TERMINATED_CANCEL_OR_TIMEOUT,
58 State.TERMINATED_DECLINED_OR_BUSY,
59 State.TERMINATED_APPLICATION_FAILURE,
60 State.TERMINATED_CONNECTIVITY_ERROR //at this state used for IQ errors and IQ timeouts
61 ));
62 transitionBuilder.put(State.SESSION_INITIALIZED_PRE_APPROVED, ImmutableList.of(
63 State.SESSION_ACCEPTED,
64 State.TERMINATED_CANCEL_OR_TIMEOUT,
65 State.TERMINATED_DECLINED_OR_BUSY,
66 State.TERMINATED_APPLICATION_FAILURE,
67 State.TERMINATED_CONNECTIVITY_ERROR //at this state used for IQ errors and IQ timeouts
68 ));
69 transitionBuilder.put(State.SESSION_ACCEPTED, ImmutableList.of(
70 State.TERMINATED_SUCCESS,
71 State.TERMINATED_CONNECTIVITY_ERROR,
72 State.TERMINATED_APPLICATION_FAILURE
73 ));
74 VALID_TRANSITIONS = transitionBuilder.build();
75 }
76
77 private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
78 private final ArrayDeque<IceCandidate> pendingIceCandidates = new ArrayDeque<>();
79 private State state = State.NULL;
80 private RtpContentMap initiatorRtpContentMap;
81 private RtpContentMap responderRtpContentMap;
82
83
84 public JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
85 super(jingleConnectionManager, id, initiator);
86 }
87
88 private static State reasonToState(Reason reason) {
89 switch (reason) {
90 case SUCCESS:
91 return State.TERMINATED_SUCCESS;
92 case DECLINE:
93 case BUSY:
94 return State.TERMINATED_DECLINED_OR_BUSY;
95 case CANCEL:
96 case TIMEOUT:
97 return State.TERMINATED_CANCEL_OR_TIMEOUT;
98 case FAILED_APPLICATION:
99 return State.TERMINATED_APPLICATION_FAILURE;
100 default:
101 return State.TERMINATED_CONNECTIVITY_ERROR;
102 }
103 }
104
105 @Override
106 void deliverPacket(final JinglePacket jinglePacket) {
107 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
108 switch (jinglePacket.getAction()) {
109 case SESSION_INITIATE:
110 receiveSessionInitiate(jinglePacket);
111 break;
112 case TRANSPORT_INFO:
113 receiveTransportInfo(jinglePacket);
114 break;
115 case SESSION_ACCEPT:
116 receiveSessionAccept(jinglePacket);
117 break;
118 case SESSION_TERMINATE:
119 receiveSessionTerminate(jinglePacket);
120 break;
121 default:
122 respondOk(jinglePacket);
123 Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
124 break;
125 }
126 }
127
128 private void receiveSessionTerminate(final JinglePacket jinglePacket) {
129 respondOk(jinglePacket);
130 final Reason reason = jinglePacket.getReason();
131 final State previous = this.state;
132 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session terminate reason=" + reason + " while in state " + previous);
133 webRTCWrapper.close();
134 transitionOrThrow(reasonToState(reason));
135 if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
136 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
137 }
138 jingleConnectionManager.finishConnection(this);
139 }
140
141 private void receiveTransportInfo(final JinglePacket jinglePacket) {
142 if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
143 respondOk(jinglePacket);
144 final RtpContentMap contentMap;
145 try {
146 contentMap = RtpContentMap.of(jinglePacket);
147 } catch (IllegalArgumentException | NullPointerException e) {
148 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents; ignoring", e);
149 return;
150 }
151 final RtpContentMap rtpContentMap = isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
152 final Group originalGroup = rtpContentMap != null ? rtpContentMap.group : null;
153 final List<String> identificationTags = originalGroup == null ? Collections.emptyList() : originalGroup.getIdentificationTags();
154 if (identificationTags.size() == 0) {
155 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
156 }
157 for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
158 final String ufrag = content.getValue().transport.getAttribute("ufrag");
159 for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
160 final String sdp = candidate.toSdpAttribute(ufrag);
161 final String sdpMid = content.getKey();
162 final int mLineIndex = identificationTags.indexOf(sdpMid);
163 final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
164 if (isInState(State.SESSION_ACCEPTED)) {
165 Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
166 this.webRTCWrapper.addIceCandidate(iceCandidate);
167 } else {
168 this.pendingIceCandidates.offer(iceCandidate);
169 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": put ICE candidate on backlog");
170 }
171 }
172 }
173 } else {
174 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
175 terminateWithOutOfOrder(jinglePacket);
176 }
177 }
178
179 private void receiveSessionInitiate(final JinglePacket jinglePacket) {
180 if (isInitiator()) {
181 Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
182 terminateWithOutOfOrder(jinglePacket);
183 return;
184 }
185 final RtpContentMap contentMap;
186 try {
187 contentMap = RtpContentMap.of(jinglePacket);
188 contentMap.requireContentDescriptions();
189 //TODO requireTransportWithDtls();
190 } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
191 respondOk(jinglePacket);
192 sendSessionTerminate(Reason.FAILED_APPLICATION);
193 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
194 return;
195 }
196 Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
197 final State target;
198 if (this.state == State.PROCEED) {
199 target = State.SESSION_INITIALIZED_PRE_APPROVED;
200 } else {
201 target = State.SESSION_INITIALIZED;
202 }
203 if (transition(target)) {
204 respondOk(jinglePacket);
205 this.initiatorRtpContentMap = contentMap;
206 if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
207 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": automatically accepting session-initiate");
208 sendSessionAccept();
209 } else {
210 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received not pre-approved session-initiate. start ringing");
211 startRinging();
212 }
213 } else {
214 Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
215 terminateWithOutOfOrder(jinglePacket);
216 }
217 }
218
219 private void receiveSessionAccept(final JinglePacket jinglePacket) {
220 if (!isInitiator()) {
221 Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
222 terminateWithOutOfOrder(jinglePacket);
223 return;
224 }
225 final RtpContentMap contentMap;
226 try {
227 contentMap = RtpContentMap.of(jinglePacket);
228 contentMap.requireContentDescriptions();
229 //TODO requireTransportWithDtls();
230 } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
231 respondOk(jinglePacket);
232 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", e);
233 webRTCWrapper.close();
234 sendSessionTerminate(Reason.FAILED_APPLICATION);
235 return;
236 }
237 Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
238 if (transition(State.SESSION_ACCEPTED)) {
239 respondOk(jinglePacket);
240 receiveSessionAccept(contentMap);
241 } else {
242 Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
243 respondOk(jinglePacket);
244 }
245 }
246
247 private void receiveSessionAccept(final RtpContentMap contentMap) {
248 this.responderRtpContentMap = contentMap;
249 final SessionDescription sessionDescription;
250 try {
251 sessionDescription = SessionDescription.of(contentMap);
252 } catch (final IllegalArgumentException e) {
253 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-accept to SDP", e);
254 webRTCWrapper.close();
255 sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
256 return;
257 }
258 org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
259 org.webrtc.SessionDescription.Type.ANSWER,
260 sessionDescription.toString()
261 );
262 try {
263 this.webRTCWrapper.setRemoteDescription(answer).get();
264 } catch (Exception e) {
265 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to set remote description after receiving session-accept", e);
266 webRTCWrapper.close();
267 sendSessionTerminate(Reason.FAILED_APPLICATION);
268 }
269 }
270
271 private void sendSessionAccept() {
272 final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
273 if (rtpContentMap == null) {
274 throw new IllegalStateException("initiator RTP Content Map has not been set");
275 }
276 final SessionDescription offer;
277 try {
278 offer = SessionDescription.of(rtpContentMap);
279 } catch (final IllegalArgumentException e) {
280 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-initiate to SDP", e);
281 webRTCWrapper.close();
282 sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
283 return;
284 }
285 sendSessionAccept(offer);
286 }
287
288 private void sendSessionAccept(SessionDescription offer) {
289 discoverIceServers(iceServers -> {
290 try {
291 setupWebRTC(iceServers);
292 } catch (WebRTCWrapper.InitializationException e) {
293 sendSessionTerminate(Reason.FAILED_APPLICATION);
294 return;
295 }
296 final org.webrtc.SessionDescription sdp = new org.webrtc.SessionDescription(
297 org.webrtc.SessionDescription.Type.OFFER,
298 offer.toString()
299 );
300 try {
301 this.webRTCWrapper.setRemoteDescription(sdp).get();
302 addIceCandidatesFromBlackLog();
303 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
304 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
305 final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
306 sendSessionAccept(respondingRtpContentMap);
307 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription);
308 } catch (Exception e) {
309 Log.d(Config.LOGTAG, "unable to send session accept", e);
310
311 }
312 });
313 }
314
315 private void addIceCandidatesFromBlackLog() {
316 while (!this.pendingIceCandidates.isEmpty()) {
317 final IceCandidate iceCandidate = this.pendingIceCandidates.poll();
318 this.webRTCWrapper.addIceCandidate(iceCandidate);
319 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": added ICE candidate from back log " + iceCandidate);
320 }
321 }
322
323 private void sendSessionAccept(final RtpContentMap rtpContentMap) {
324 this.responderRtpContentMap = rtpContentMap;
325 this.transitionOrThrow(State.SESSION_ACCEPTED);
326 final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
327 Log.d(Config.LOGTAG, sessionAccept.toString());
328 send(sessionAccept);
329 }
330
331 void deliveryMessage(final Jid from, final Element message) {
332 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
333 switch (message.getName()) {
334 case "propose":
335 receivePropose(from, message);
336 break;
337 case "proceed":
338 receiveProceed(from, message);
339 break;
340 case "retract":
341 receiveRetract(from, message);
342 break;
343 case "reject":
344 receiveReject(from, message);
345 break;
346 case "accept":
347 receiveAccept(from, message);
348 break;
349 default:
350 break;
351 }
352 }
353
354 private void receiveAccept(Jid from, Element message) {
355 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
356 if (originatedFromMyself) {
357 if (transition(State.ACCEPTED)) {
358 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
359 this.jingleConnectionManager.finishConnection(this);
360 } else {
361 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
362 }
363 } else {
364 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
365 }
366 }
367
368 private void receiveReject(Jid from, Element message) {
369 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
370 //reject from another one of my clients
371 if (originatedFromMyself) {
372 if (transition(State.REJECTED)) {
373 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
374 this.jingleConnectionManager.finishConnection(this);
375 } else {
376 Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
377 }
378 } else {
379 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
380 }
381 }
382
383 private void receivePropose(final Jid from, final Element propose) {
384 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
385 //TODO we can use initiator logic here
386 if (originatedFromMyself) {
387 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
388 } else if (transition(State.PROPOSED)) {
389 startRinging();
390 } else {
391 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
392 }
393 }
394
395 private void startRinging() {
396 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
397 xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
398 }
399
400 private void receiveProceed(final Jid from, final Element proceed) {
401 if (from.equals(id.with)) {
402 if (isInitiator()) {
403 if (transition(State.PROCEED)) {
404 this.sendSessionInitiate(State.SESSION_INITIALIZED_PRE_APPROVED);
405 } else {
406 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
407 }
408 } else {
409 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
410 }
411 } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
412 if (transition(State.ACCEPTED)) {
413 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
414 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
415 this.jingleConnectionManager.finishConnection(this);
416 }
417 } else {
418 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
419 }
420 }
421
422 private void receiveRetract(final Jid from, final Element retract) {
423 if (from.equals(id.with)) {
424 if (transition(State.RETRACTED)) {
425 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
426 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
427 //TODO create missed call notification/message
428 jingleConnectionManager.finishConnection(this);
429 } else {
430 Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
431 }
432 } else {
433 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
434 }
435 }
436
437 private void sendSessionInitiate(final State targetState) {
438 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
439 discoverIceServers(iceServers -> {
440 try {
441 setupWebRTC(iceServers);
442 } catch (WebRTCWrapper.InitializationException e) {
443 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize webrtc");
444 transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
445 return;
446 }
447 try {
448 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
449 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
450 Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
451 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
452 sendSessionInitiate(rtpContentMap, targetState);
453 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
454 } catch (final Exception e) {
455 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", e);
456 webRTCWrapper.close();
457 if (isInState(targetState)) {
458 sendSessionTerminate(Reason.FAILED_APPLICATION);
459 } else {
460 transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
461 }
462 }
463 });
464 }
465
466 private void sendSessionInitiate(RtpContentMap rtpContentMap, final State targetState) {
467 this.initiatorRtpContentMap = rtpContentMap;
468 this.transitionOrThrow(targetState);
469 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
470 Log.d(Config.LOGTAG, sessionInitiate.toString());
471 send(sessionInitiate);
472 }
473
474 private void sendSessionTerminate(final Reason reason) {
475 sendSessionTerminate(reason, null);
476 }
477
478 private void sendSessionTerminate(final Reason reason, final String text) {
479 final State target = reasonToState(reason);
480 transitionOrThrow(target);
481 final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
482 jinglePacket.setReason(reason, text);
483 send(jinglePacket);
484 Log.d(Config.LOGTAG, jinglePacket.toString());
485 jingleConnectionManager.finishConnection(this);
486 }
487
488 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
489 final RtpContentMap transportInfo;
490 try {
491 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
492 transportInfo = rtpContentMap.transportInfo(contentName, candidate);
493 } catch (Exception e) {
494 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
495 return;
496 }
497 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
498 Log.d(Config.LOGTAG, jinglePacket.toString());
499 send(jinglePacket);
500 }
501
502 private void send(final JinglePacket jinglePacket) {
503 jinglePacket.setTo(id.with);
504 xmppConnectionService.sendIqPacket(id.account, jinglePacket, (account, response) -> {
505 if (response.getType() == IqPacket.TYPE.ERROR) {
506 final String errorCondition = response.getErrorCondition();
507 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
508 this.webRTCWrapper.close();
509 final State target;
510 if (Arrays.asList(
511 "service-unavailable",
512 "recipient-unavailable",
513 "remote-server-not-found",
514 "remote-server-timeout"
515 ).contains(errorCondition)) {
516 target = State.TERMINATED_CONNECTIVITY_ERROR;
517 } else {
518 target = State.TERMINATED_APPLICATION_FAILURE;
519 }
520 if (transition(target)) {
521 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminated session with " + id.with);
522 } else {
523 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not transitioning because already at state=" + this.state);
524 }
525
526 } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
527 this.webRTCWrapper.close();
528 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
529 transition(State.TERMINATED_CONNECTIVITY_ERROR);
530 this.jingleConnectionManager.finishConnection(this);
531 }
532 });
533 }
534
535 private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
536 Log.d(Config.LOGTAG,id.account.getJid().asBareJid()+": terminating session with out-of-order");
537 webRTCWrapper.close();
538 transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
539 respondWithOutOfOrder(jinglePacket);
540 jingleConnectionManager.finishConnection(this);
541 }
542
543 private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
544 jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
545 }
546
547 private void respondOk(final JinglePacket jinglePacket) {
548 xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
549 }
550
551 public RtpEndUserState getEndUserState() {
552 switch (this.state) {
553 case PROPOSED:
554 case SESSION_INITIALIZED:
555 if (isInitiator()) {
556 return RtpEndUserState.RINGING;
557 } else {
558 return RtpEndUserState.INCOMING_CALL;
559 }
560 case PROCEED:
561 if (isInitiator()) {
562 return RtpEndUserState.RINGING;
563 } else {
564 return RtpEndUserState.ACCEPTING_CALL;
565 }
566 case SESSION_INITIALIZED_PRE_APPROVED:
567 if (isInitiator()) {
568 return RtpEndUserState.RINGING;
569 } else {
570 return RtpEndUserState.CONNECTING;
571 }
572 case SESSION_ACCEPTED:
573 final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
574 if (state == PeerConnection.PeerConnectionState.CONNECTED) {
575 return RtpEndUserState.CONNECTED;
576 } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
577 return RtpEndUserState.CONNECTING;
578 } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
579 return RtpEndUserState.ENDING_CALL;
580 } else if (state == PeerConnection.PeerConnectionState.FAILED) {
581 return RtpEndUserState.CONNECTIVITY_ERROR;
582 } else {
583 return RtpEndUserState.ENDING_CALL;
584 }
585 case REJECTED:
586 case TERMINATED_DECLINED_OR_BUSY:
587 if (isInitiator()) {
588 return RtpEndUserState.DECLINED_OR_BUSY;
589 } else {
590 return RtpEndUserState.ENDED;
591 }
592 case TERMINATED_SUCCESS:
593 case ACCEPTED:
594 case RETRACTED:
595 case TERMINATED_CANCEL_OR_TIMEOUT:
596 return RtpEndUserState.ENDED;
597 case TERMINATED_CONNECTIVITY_ERROR:
598 return RtpEndUserState.CONNECTIVITY_ERROR;
599 case TERMINATED_APPLICATION_FAILURE:
600 return RtpEndUserState.APPLICATION_ERROR;
601 }
602 throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
603 }
604
605
606 public void acceptCall() {
607 switch (this.state) {
608 case PROPOSED:
609 acceptCallFromProposed();
610 break;
611 case SESSION_INITIALIZED:
612 acceptCallFromSessionInitialized();
613 break;
614 default:
615 throw new IllegalStateException("Can not accept call from " + this.state);
616 }
617 }
618
619 public void rejectCall() {
620 switch (this.state) {
621 case PROPOSED:
622 rejectCallFromProposed();
623 break;
624 case SESSION_INITIALIZED:
625 rejectCallFromSessionInitiate();
626 break;
627 default:
628 throw new IllegalStateException("Can not reject call from " + this.state);
629 }
630 }
631
632 public void endCall() {
633 if (isInState(State.PROCEED)) {
634 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
635 webRTCWrapper.close();
636 jingleConnectionManager.finishConnection(this);
637 transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
638 return;
639 }
640 if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
641 webRTCWrapper.close();
642 sendSessionTerminate(Reason.CANCEL);
643 return;
644 }
645 if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
646 webRTCWrapper.close();
647 sendSessionTerminate(Reason.SUCCESS);
648 return;
649 }
650 throw new IllegalStateException("called 'endCall' while in state " + this.state);
651 }
652
653 private void setupWebRTC(final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
654 this.webRTCWrapper.setup(this.xmppConnectionService);
655 this.webRTCWrapper.initializePeerConnection(iceServers);
656 }
657
658 private void acceptCallFromProposed() {
659 transitionOrThrow(State.PROCEED);
660 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
661 this.sendJingleMessage("accept", id.account.getJid().asBareJid());
662 this.sendJingleMessage("proceed");
663 }
664
665 private void rejectCallFromProposed() {
666 transitionOrThrow(State.REJECTED);
667 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
668 this.sendJingleMessage("reject");
669 jingleConnectionManager.finishConnection(this);
670 }
671
672 private void rejectCallFromSessionInitiate() {
673 webRTCWrapper.close();
674 sendSessionTerminate(Reason.DECLINE);
675 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
676 }
677
678 private void sendJingleMessage(final String action) {
679 sendJingleMessage(action, id.with);
680 }
681
682 private void sendJingleMessage(final String action, final Jid to) {
683 final MessagePacket messagePacket = new MessagePacket();
684 messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
685 messagePacket.setTo(to);
686 messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
687 Log.d(Config.LOGTAG, messagePacket.toString());
688 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
689 }
690
691 private void acceptCallFromSessionInitialized() {
692 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
693 sendSessionAccept();
694 }
695
696 private synchronized boolean isInState(State... state) {
697 return Arrays.asList(state).contains(this.state);
698 }
699
700 private synchronized boolean transition(final State target) {
701 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
702 if (validTransitions != null && validTransitions.contains(target)) {
703 this.state = target;
704 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
705 updateEndUserState();
706 return true;
707 } else {
708 return false;
709 }
710 }
711
712 public void transitionOrThrow(final State target) {
713 if (!transition(target)) {
714 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
715 }
716 }
717
718 @Override
719 public void onIceCandidate(final IceCandidate iceCandidate) {
720 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
721 Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
722 sendTransportInfo(iceCandidate.sdpMid, candidate);
723 }
724
725 @Override
726 public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
727 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
728 updateEndUserState();
729 if (newState == PeerConnection.PeerConnectionState.FAILED) { //TODO guard this in isState(initiated,initiated_approved,accepted) otherwise it might fire too late
730 sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
731 }
732 }
733
734 private void updateEndUserState() {
735 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
736 }
737
738 private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
739 if (id.account.getXmppConnection().getFeatures().extendedServiceDiscovery()) {
740 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
741 request.setTo(Jid.of(id.account.getJid().getDomain()));
742 request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
743 xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
744 ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
745 if (response.getType() == IqPacket.TYPE.RESULT) {
746 final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
747 final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
748 for (final Element child : children) {
749 if ("service".equals(child.getName())) {
750 final String type = child.getAttribute("type");
751 final String host = child.getAttribute("host");
752 final String sport = child.getAttribute("port");
753 final Integer port = sport == null ? null : Ints.tryParse(sport);
754 final String transport = child.getAttribute("transport");
755 final String username = child.getAttribute("username");
756 final String password = child.getAttribute("password");
757 if (Strings.isNullOrEmpty(host) || port == null) {
758 continue;
759 }
760 if (port < 0 || port > 65535) {
761 continue;
762 }
763 if (Arrays.asList("stun", "turn").contains(type) || Arrays.asList("udp", "tcp").contains(transport)) {
764 //TODO wrap ipv6 addresses
765 PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s?transport=%s", type, host, port, transport));
766 if (username != null && password != null) {
767 iceServerBuilder.setUsername(username);
768 iceServerBuilder.setPassword(password);
769 } else if (Arrays.asList("turn", "turns").contains(type)) {
770 //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
771 //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
772 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
773 continue;
774 }
775 final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
776 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
777 listBuilder.add(iceServer);
778 }
779 }
780 }
781 }
782 List<PeerConnection.IceServer> iceServers = listBuilder.build();
783 if (iceServers.size() == 0) {
784 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
785 }
786 onIceServersDiscovered.onIceServersDiscovered(iceServers);
787 });
788 } else {
789 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
790 onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
791 }
792 }
793
794 private interface OnIceServersDiscovered {
795 void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
796 }
797}