1package eu.siacs.conversations.xmpp.jingle;
2
3import android.os.SystemClock;
4import android.util.Log;
5
6import androidx.annotation.NonNull;
7import androidx.annotation.Nullable;
8
9import com.google.common.base.Optional;
10import com.google.common.base.Preconditions;
11import com.google.common.base.Strings;
12import com.google.common.base.Throwables;
13import com.google.common.collect.Collections2;
14import com.google.common.collect.ImmutableList;
15import com.google.common.collect.ImmutableMap;
16import com.google.common.collect.Sets;
17import com.google.common.primitives.Ints;
18import com.google.common.util.concurrent.FutureCallback;
19import com.google.common.util.concurrent.Futures;
20import com.google.common.util.concurrent.ListenableFuture;
21import com.google.common.util.concurrent.MoreExecutors;
22
23import org.webrtc.EglBase;
24import org.webrtc.IceCandidate;
25import org.webrtc.PeerConnection;
26import org.webrtc.VideoTrack;
27
28import java.util.ArrayDeque;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.Collections;
32import java.util.List;
33import java.util.Map;
34import java.util.Set;
35import java.util.concurrent.ScheduledFuture;
36import java.util.concurrent.TimeUnit;
37
38import eu.siacs.conversations.Config;
39import eu.siacs.conversations.crypto.axolotl.AxolotlService;
40import eu.siacs.conversations.crypto.axolotl.CryptoFailedException;
41import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
42import eu.siacs.conversations.entities.Account;
43import eu.siacs.conversations.entities.Conversation;
44import eu.siacs.conversations.entities.Conversational;
45import eu.siacs.conversations.entities.Message;
46import eu.siacs.conversations.entities.RtpSessionStatus;
47import eu.siacs.conversations.services.AppRTCAudioManager;
48import eu.siacs.conversations.utils.IP;
49import eu.siacs.conversations.xml.Element;
50import eu.siacs.conversations.xml.Namespace;
51import eu.siacs.conversations.xmpp.Jid;
52import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
53import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
54import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
55import eu.siacs.conversations.xmpp.jingle.stanzas.Proceed;
56import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
57import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
58import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
59import eu.siacs.conversations.xmpp.stanzas.IqPacket;
60import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
61
62public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
63
64 public static final List<State> STATES_SHOWING_ONGOING_CALL = Arrays.asList(
65 State.PROCEED,
66 State.SESSION_INITIALIZED_PRE_APPROVED,
67 State.SESSION_ACCEPTED
68 );
69 private static final long BUSY_TIME_OUT = 30;
70 private static final List<State> TERMINATED = Arrays.asList(
71 State.ACCEPTED,
72 State.REJECTED,
73 State.REJECTED_RACED,
74 State.RETRACTED,
75 State.RETRACTED_RACED,
76 State.TERMINATED_SUCCESS,
77 State.TERMINATED_DECLINED_OR_BUSY,
78 State.TERMINATED_CONNECTIVITY_ERROR,
79 State.TERMINATED_CANCEL_OR_TIMEOUT,
80 State.TERMINATED_APPLICATION_FAILURE,
81 State.TERMINATED_SECURITY_ERROR
82 );
83
84 private static final Map<State, Collection<State>> VALID_TRANSITIONS;
85
86 static {
87 final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
88 transitionBuilder.put(State.NULL, ImmutableList.of(
89 State.PROPOSED,
90 State.SESSION_INITIALIZED,
91 State.TERMINATED_APPLICATION_FAILURE,
92 State.TERMINATED_SECURITY_ERROR
93 ));
94 transitionBuilder.put(State.PROPOSED, ImmutableList.of(
95 State.ACCEPTED,
96 State.PROCEED,
97 State.REJECTED,
98 State.RETRACTED,
99 State.TERMINATED_APPLICATION_FAILURE,
100 State.TERMINATED_SECURITY_ERROR,
101 State.TERMINATED_CONNECTIVITY_ERROR //only used when the xmpp connection rebinds
102 ));
103 transitionBuilder.put(State.PROCEED, ImmutableList.of(
104 State.REJECTED_RACED,
105 State.RETRACTED_RACED,
106 State.SESSION_INITIALIZED_PRE_APPROVED,
107 State.TERMINATED_SUCCESS,
108 State.TERMINATED_APPLICATION_FAILURE,
109 State.TERMINATED_SECURITY_ERROR,
110 State.TERMINATED_CONNECTIVITY_ERROR //at this state used for error bounces of the proceed message
111 ));
112 transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(
113 State.SESSION_ACCEPTED,
114 State.TERMINATED_SUCCESS,
115 State.TERMINATED_DECLINED_OR_BUSY,
116 State.TERMINATED_CONNECTIVITY_ERROR, //at this state used for IQ errors and IQ timeouts
117 State.TERMINATED_CANCEL_OR_TIMEOUT,
118 State.TERMINATED_APPLICATION_FAILURE,
119 State.TERMINATED_SECURITY_ERROR
120 ));
121 transitionBuilder.put(State.SESSION_INITIALIZED_PRE_APPROVED, ImmutableList.of(
122 State.SESSION_ACCEPTED,
123 State.TERMINATED_SUCCESS,
124 State.TERMINATED_DECLINED_OR_BUSY,
125 State.TERMINATED_CONNECTIVITY_ERROR, //at this state used for IQ errors and IQ timeouts
126 State.TERMINATED_CANCEL_OR_TIMEOUT,
127 State.TERMINATED_APPLICATION_FAILURE,
128 State.TERMINATED_SECURITY_ERROR
129 ));
130 transitionBuilder.put(State.SESSION_ACCEPTED, ImmutableList.of(
131 State.TERMINATED_SUCCESS,
132 State.TERMINATED_DECLINED_OR_BUSY,
133 State.TERMINATED_CONNECTIVITY_ERROR,
134 State.TERMINATED_CANCEL_OR_TIMEOUT,
135 State.TERMINATED_APPLICATION_FAILURE,
136 State.TERMINATED_SECURITY_ERROR
137 ));
138 VALID_TRANSITIONS = transitionBuilder.build();
139 }
140
141 private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
142 private final ArrayDeque<Set<Map.Entry<String, RtpContentMap.DescriptionTransport>>> pendingIceCandidates = new ArrayDeque<>();
143 private final OmemoVerification omemoVerification = new OmemoVerification();
144 private final Message message;
145 private State state = State.NULL;
146 private StateTransitionException stateTransitionException;
147 private Set<Media> proposedMedia;
148 private RtpContentMap initiatorRtpContentMap;
149 private RtpContentMap responderRtpContentMap;
150 private long rtpConnectionStarted = 0; //time of 'connected'
151 private long rtpConnectionEnded = 0;
152 private ScheduledFuture<?> ringingTimeoutFuture;
153
154 JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
155 super(jingleConnectionManager, id, initiator);
156 final Conversation conversation = jingleConnectionManager.getXmppConnectionService().findOrCreateConversation(
157 id.account,
158 id.with.asBareJid(),
159 false,
160 false
161 );
162 this.message = new Message(
163 conversation,
164 isInitiator() ? Message.STATUS_SEND : Message.STATUS_RECEIVED,
165 Message.TYPE_RTP_SESSION,
166 id.sessionId
167 );
168 }
169
170 private static State reasonToState(Reason reason) {
171 switch (reason) {
172 case SUCCESS:
173 return State.TERMINATED_SUCCESS;
174 case DECLINE:
175 case BUSY:
176 return State.TERMINATED_DECLINED_OR_BUSY;
177 case CANCEL:
178 case TIMEOUT:
179 return State.TERMINATED_CANCEL_OR_TIMEOUT;
180 case SECURITY_ERROR:
181 return State.TERMINATED_SECURITY_ERROR;
182 case FAILED_APPLICATION:
183 case UNSUPPORTED_TRANSPORTS:
184 case UNSUPPORTED_APPLICATIONS:
185 return State.TERMINATED_APPLICATION_FAILURE;
186 default:
187 return State.TERMINATED_CONNECTIVITY_ERROR;
188 }
189 }
190
191 @Override
192 synchronized void deliverPacket(final JinglePacket jinglePacket) {
193 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
194 switch (jinglePacket.getAction()) {
195 case SESSION_INITIATE:
196 receiveSessionInitiate(jinglePacket);
197 break;
198 case TRANSPORT_INFO:
199 receiveTransportInfo(jinglePacket);
200 break;
201 case SESSION_ACCEPT:
202 receiveSessionAccept(jinglePacket);
203 break;
204 case SESSION_TERMINATE:
205 receiveSessionTerminate(jinglePacket);
206 break;
207 default:
208 respondOk(jinglePacket);
209 Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
210 break;
211 }
212 }
213
214 @Override
215 synchronized void notifyRebound() {
216 if (isTerminated()) {
217 return;
218 }
219 webRTCWrapper.close();
220 if (!isInitiator() && isInState(State.PROPOSED, State.SESSION_INITIALIZED)) {
221 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
222 }
223 if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
224 //we might have already changed resources (full jid) at this point; so this might not even reach the other party
225 sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
226 } else {
227 transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
228 finish();
229 }
230 }
231
232 private void receiveSessionTerminate(final JinglePacket jinglePacket) {
233 respondOk(jinglePacket);
234 final JinglePacket.ReasonWrapper wrapper = jinglePacket.getReason();
235 final State previous = this.state;
236 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session terminate reason=" + wrapper.reason + "(" + Strings.nullToEmpty(wrapper.text) + ") while in state " + previous);
237 if (TERMINATED.contains(previous)) {
238 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring session terminate because already in " + previous);
239 return;
240 }
241 webRTCWrapper.close();
242 final State target = reasonToState(wrapper.reason);
243 transitionOrThrow(target);
244 writeLogMessage(target);
245 if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
246 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
247 }
248 finish();
249 }
250
251 private void receiveTransportInfo(final JinglePacket jinglePacket) {
252 //Due to the asynchronicity of processing session-init we might move from NULL|PROCEED to INITIALIZED only after transport-info has been received
253 if (isInState(State.NULL, State.PROCEED, State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
254 respondOk(jinglePacket);
255 final RtpContentMap contentMap;
256 try {
257 contentMap = RtpContentMap.of(jinglePacket);
258 } catch (IllegalArgumentException | NullPointerException e) {
259 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents; ignoring", e);
260 return;
261 }
262 final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> candidates = contentMap.contents.entrySet();
263 if (this.state == State.SESSION_ACCEPTED) {
264 try {
265 processCandidates(candidates);
266 } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
267 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnection was not initialized when processing transport info. this usually indicates a race condition that can be ignored");
268 }
269 } else {
270 pendingIceCandidates.push(candidates);
271 }
272 } else {
273 if (isTerminated()) {
274 respondOk(jinglePacket);
275 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring out-of-order transport info; we where already terminated");
276 } else {
277 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
278 terminateWithOutOfOrder(jinglePacket);
279 }
280 }
281 }
282
283 private void processCandidates(final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> contents) {
284 final RtpContentMap rtpContentMap = isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
285 final Group originalGroup = rtpContentMap.group;
286 final List<String> identificationTags = originalGroup == null ? rtpContentMap.getNames() : originalGroup.getIdentificationTags();
287 if (identificationTags.size() == 0) {
288 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
289 }
290 processCandidates(identificationTags, contents);
291 }
292
293 private void processCandidates(final List<String> indices, final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> contents) {
294 for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contents) {
295 final String ufrag = content.getValue().transport.getAttribute("ufrag");
296 for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
297 final String sdp;
298 try {
299 sdp = candidate.toSdpAttribute(ufrag);
300 } catch (IllegalArgumentException e) {
301 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring invalid ICE candidate " + e.getMessage());
302 continue;
303 }
304 final String sdpMid = content.getKey();
305 final int mLineIndex = indices.indexOf(sdpMid);
306 if (mLineIndex < 0) {
307 Log.w(Config.LOGTAG, "mLineIndex not found for " + sdpMid + ". available indices " + indices);
308 }
309 final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
310 Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
311 this.webRTCWrapper.addIceCandidate(iceCandidate);
312 }
313 }
314 }
315
316 private ListenableFuture<RtpContentMap> receiveRtpContentMap(final JinglePacket jinglePacket, final boolean expectVerification) {
317 final RtpContentMap receivedContentMap = RtpContentMap.of(jinglePacket);
318 if (receivedContentMap instanceof OmemoVerifiedRtpContentMap) {
319 final ListenableFuture<AxolotlService.OmemoVerifiedPayload<RtpContentMap>> future = id.account.getAxolotlService().decrypt((OmemoVerifiedRtpContentMap) receivedContentMap, id.with);
320 return Futures.transform(future, omemoVerifiedPayload -> {
321 //TODO test if an exception here triggers a correct abort
322 omemoVerification.setOrEnsureEqual(omemoVerifiedPayload);
323 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received verifiable DTLS fingerprint via " + omemoVerification);
324 return omemoVerifiedPayload.getPayload();
325 }, MoreExecutors.directExecutor());
326 } else if (Config.REQUIRE_RTP_VERIFICATION || expectVerification) {
327 return Futures.immediateFailedFuture(
328 new SecurityException("DTLS fingerprint was unexpectedly not verifiable")
329 );
330 } else {
331 return Futures.immediateFuture(receivedContentMap);
332 }
333 }
334
335 private void receiveSessionInitiate(final JinglePacket jinglePacket) {
336 if (isInitiator()) {
337 Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
338 if (isTerminated()) {
339 Log.d(Config.LOGTAG, String.format(
340 "%s: got a reason to terminate with out-of-order. but already in state %s",
341 id.account.getJid().asBareJid(),
342 getState()
343 ));
344 respondWithOutOfOrder(jinglePacket);
345 } else {
346 terminateWithOutOfOrder(jinglePacket);
347 }
348 return;
349 }
350 final ListenableFuture<RtpContentMap> future = receiveRtpContentMap(jinglePacket, false);
351 Futures.addCallback(future, new FutureCallback<RtpContentMap>() {
352 @Override
353 public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
354 receiveSessionInitiate(jinglePacket, rtpContentMap);
355 }
356
357 @Override
358 public void onFailure(@NonNull final Throwable throwable) {
359 respondOk(jinglePacket);
360 sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
361 }
362 }, MoreExecutors.directExecutor());
363 }
364
365 private void receiveSessionInitiate(final JinglePacket jinglePacket, final RtpContentMap contentMap) {
366 try {
367 contentMap.requireContentDescriptions();
368 contentMap.requireDTLSFingerprint();
369 } catch (final RuntimeException e) {
370 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", Throwables.getRootCause(e));
371 respondOk(jinglePacket);
372 sendSessionTerminate(Reason.of(e), e.getMessage());
373 return;
374 }
375 Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
376 final State target;
377 if (this.state == State.PROCEED) {
378 Preconditions.checkState(
379 proposedMedia != null && proposedMedia.size() > 0,
380 "proposed media must be set when processing pre-approved session-initiate"
381 );
382 if (!this.proposedMedia.equals(contentMap.getMedia())) {
383 sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
384 "Your session proposal (Jingle Message Initiation) included media %s but your session-initiate was %s",
385 this.proposedMedia,
386 contentMap.getMedia()
387 ));
388 return;
389 }
390 target = State.SESSION_INITIALIZED_PRE_APPROVED;
391 } else {
392 target = State.SESSION_INITIALIZED;
393 }
394 if (transition(target, () -> this.initiatorRtpContentMap = contentMap)) {
395 respondOk(jinglePacket);
396
397 final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> candidates = contentMap.contents.entrySet();
398 if (candidates.size() > 0) {
399 pendingIceCandidates.push(candidates);
400 }
401 if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
402 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": automatically accepting session-initiate");
403 sendSessionAccept();
404 } else {
405 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received not pre-approved session-initiate. start ringing");
406 startRinging();
407 }
408 } else {
409 Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
410 terminateWithOutOfOrder(jinglePacket);
411 }
412 }
413
414 private void receiveSessionAccept(final JinglePacket jinglePacket) {
415 if (!isInitiator()) {
416 Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
417 terminateWithOutOfOrder(jinglePacket);
418 return;
419 }
420 final ListenableFuture<RtpContentMap> future = receiveRtpContentMap(jinglePacket, this.omemoVerification.hasFingerprint());
421 Futures.addCallback(future, new FutureCallback<RtpContentMap>() {
422 @Override
423 public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
424 receiveSessionAccept(jinglePacket, rtpContentMap);
425 }
426
427 @Override
428 public void onFailure(@NonNull final Throwable throwable) {
429 respondOk(jinglePacket);
430 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", throwable);
431 webRTCWrapper.close();
432 sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
433 }
434 }, MoreExecutors.directExecutor());
435 }
436
437 private void receiveSessionAccept(final JinglePacket jinglePacket, final RtpContentMap contentMap) {
438 try {
439 contentMap.requireContentDescriptions();
440 contentMap.requireDTLSFingerprint();
441 } catch (final RuntimeException e) {
442 respondOk(jinglePacket);
443 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", e);
444 webRTCWrapper.close();
445 sendSessionTerminate(Reason.of(e), e.getMessage());
446 return;
447 }
448 final Set<Media> initiatorMedia = this.initiatorRtpContentMap.getMedia();
449 if (!initiatorMedia.equals(contentMap.getMedia())) {
450 sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
451 "Your session-included included media %s but our session-initiate was %s",
452 this.proposedMedia,
453 contentMap.getMedia()
454 ));
455 return;
456 }
457 Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
458 if (transition(State.SESSION_ACCEPTED)) {
459 respondOk(jinglePacket);
460 receiveSessionAccept(contentMap);
461 } else {
462 Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
463 respondOk(jinglePacket);
464 }
465 }
466
467 private void receiveSessionAccept(final RtpContentMap contentMap) {
468 this.responderRtpContentMap = contentMap;
469 final SessionDescription sessionDescription;
470 try {
471 sessionDescription = SessionDescription.of(contentMap);
472 } catch (final IllegalArgumentException | NullPointerException e) {
473 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-accept to SDP", e);
474 webRTCWrapper.close();
475 sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
476 return;
477 }
478 final org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
479 org.webrtc.SessionDescription.Type.ANSWER,
480 sessionDescription.toString()
481 );
482 try {
483 this.webRTCWrapper.setRemoteDescription(answer).get();
484 } catch (final Exception e) {
485 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to set remote description after receiving session-accept", Throwables.getRootCause(e));
486 webRTCWrapper.close();
487 sendSessionTerminate(Reason.FAILED_APPLICATION);
488 return;
489 }
490 final List<String> identificationTags = contentMap.group == null ? contentMap.getNames() : contentMap.group.getIdentificationTags();
491 processCandidates(identificationTags, contentMap.contents.entrySet());
492 }
493
494 private void sendSessionAccept() {
495 final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
496 if (rtpContentMap == null) {
497 throw new IllegalStateException("initiator RTP Content Map has not been set");
498 }
499 final SessionDescription offer;
500 try {
501 offer = SessionDescription.of(rtpContentMap);
502 } catch (final IllegalArgumentException | NullPointerException e) {
503 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-initiate to SDP", e);
504 webRTCWrapper.close();
505 sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
506 return;
507 }
508 sendSessionAccept(rtpContentMap.getMedia(), offer);
509 }
510
511 private void sendSessionAccept(final Set<Media> media, final SessionDescription offer) {
512 discoverIceServers(iceServers -> sendSessionAccept(media, offer, iceServers));
513 }
514
515 private synchronized void sendSessionAccept(final Set<Media> media, final SessionDescription offer, final List<PeerConnection.IceServer> iceServers) {
516 if (isTerminated()) {
517 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
518 return;
519 }
520 try {
521 setupWebRTC(media, iceServers);
522 } catch (final WebRTCWrapper.InitializationException e) {
523 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
524 webRTCWrapper.close();
525 sendSessionTerminate(Reason.FAILED_APPLICATION);
526 return;
527 }
528 final org.webrtc.SessionDescription sdp = new org.webrtc.SessionDescription(
529 org.webrtc.SessionDescription.Type.OFFER,
530 offer.toString()
531 );
532 try {
533 this.webRTCWrapper.setRemoteDescription(sdp).get();
534 addIceCandidatesFromBlackLog();
535 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
536 prepareSessionAccept(webRTCSessionDescription);
537 } catch (final Exception e) {
538 failureToAcceptSession(e);
539 }
540 }
541
542 private void failureToAcceptSession(final Throwable throwable) {
543 Log.d(Config.LOGTAG, "unable to send session accept", Throwables.getRootCause(throwable));
544 webRTCWrapper.close();
545 sendSessionTerminate(Reason.ofThrowable(throwable));
546 }
547
548 private void addIceCandidatesFromBlackLog() {
549 while (!this.pendingIceCandidates.isEmpty()) {
550 processCandidates(this.pendingIceCandidates.poll());
551 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": added candidates from back log");
552 }
553 }
554
555 private void prepareSessionAccept(final org.webrtc.SessionDescription webRTCSessionDescription) {
556 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
557 final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
558 this.responderRtpContentMap = respondingRtpContentMap;
559 final ListenableFuture<RtpContentMap> outgoingContentMapFuture = prepareOutgoingContentMap(respondingRtpContentMap);
560 Futures.addCallback(outgoingContentMapFuture,
561 new FutureCallback<RtpContentMap>() {
562 @Override
563 public void onSuccess(final RtpContentMap outgoingContentMap) {
564 sendSessionAccept(outgoingContentMap, webRTCSessionDescription);
565 }
566
567 @Override
568 public void onFailure(@NonNull Throwable throwable) {
569 failureToAcceptSession(throwable);
570 }
571 },
572 MoreExecutors.directExecutor()
573 );
574 }
575
576 private void sendSessionAccept(final RtpContentMap rtpContentMap, final org.webrtc.SessionDescription webRTCSessionDescription) {
577 transitionOrThrow(State.SESSION_ACCEPTED);
578 final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
579 send(sessionAccept);
580 try {
581 webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
582 } catch (Exception e) {
583 failureToAcceptSession(e);
584 }
585 }
586
587 private ListenableFuture<RtpContentMap> prepareOutgoingContentMap(final RtpContentMap rtpContentMap) {
588 if (this.omemoVerification.hasDeviceId()) {
589 ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>> verifiedPayloadFuture = id.account.getAxolotlService()
590 .encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
591 return Futures.transform(verifiedPayloadFuture, verifiedPayload -> {
592 omemoVerification.setOrEnsureEqual(verifiedPayload);
593 return verifiedPayload.getPayload();
594 }, MoreExecutors.directExecutor());
595 } else {
596 return Futures.immediateFuture(rtpContentMap);
597 }
598 }
599
600 synchronized void deliveryMessage(final Jid from, final Element message, final String serverMessageId, final long timestamp) {
601 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
602 switch (message.getName()) {
603 case "propose":
604 receivePropose(from, Propose.upgrade(message), serverMessageId, timestamp);
605 break;
606 case "proceed":
607 receiveProceed(from, Proceed.upgrade(message), serverMessageId, timestamp);
608 break;
609 case "retract":
610 receiveRetract(from, serverMessageId, timestamp);
611 break;
612 case "reject":
613 receiveReject(from, serverMessageId, timestamp);
614 break;
615 case "accept":
616 receiveAccept(from, serverMessageId, timestamp);
617 break;
618 default:
619 break;
620 }
621 }
622
623 void deliverFailedProceed() {
624 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receive message error for proceed message");
625 if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
626 webRTCWrapper.close();
627 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into connectivity error");
628 this.finish();
629 }
630 }
631
632 private void receiveAccept(final Jid from, final String serverMsgId, final long timestamp) {
633 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
634 if (originatedFromMyself) {
635 if (transition(State.ACCEPTED)) {
636 if (serverMsgId != null) {
637 this.message.setServerMsgId(serverMsgId);
638 }
639 this.message.setTime(timestamp);
640 this.message.setCarbon(true); //indicate that call was accepted on other device
641 this.writeLogMessageSuccess(0);
642 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
643 this.finish();
644 } else {
645 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
646 }
647 } else {
648 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
649 }
650 }
651
652 private void receiveReject(final Jid from, final String serverMsgId, final long timestamp) {
653 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
654 //reject from another one of my clients
655 if (originatedFromMyself) {
656 receiveRejectFromMyself(serverMsgId, timestamp);
657 } else if (isInitiator()) {
658 if (from.equals(id.with)) {
659 receiveRejectFromResponder();
660 } else {
661 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
662 }
663 } else {
664 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
665 }
666 }
667
668 private void receiveRejectFromMyself(String serverMsgId, long timestamp) {
669 if (transition(State.REJECTED)) {
670 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
671 this.finish();
672 if (serverMsgId != null) {
673 this.message.setServerMsgId(serverMsgId);
674 }
675 this.message.setTime(timestamp);
676 this.message.setCarbon(true); //indicate that call was rejected on other device
677 writeLogMessageMissed();
678 } else {
679 Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
680 }
681 }
682
683 private void receiveRejectFromResponder() {
684 if (isInState(State.PROCEED)) {
685 Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while still in proceed. callee reconsidered");
686 closeTransitionLogFinish(State.REJECTED_RACED);
687 return;
688 }
689 if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED)) {
690 Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while in SESSION_INITIATED_PRE_APPROVED. callee reconsidered before receiving session-init");
691 closeTransitionLogFinish(State.TERMINATED_DECLINED_OR_BUSY);
692 return;
693 }
694 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from responder because already in state " + this.state);
695 }
696
697 private void receivePropose(final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
698 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
699 if (originatedFromMyself) {
700 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from myself. ignoring");
701 } else if (transition(State.PROPOSED, () -> {
702 final Collection<RtpDescription> descriptions = Collections2.transform(
703 Collections2.filter(propose.getDescriptions(), d -> d instanceof RtpDescription),
704 input -> (RtpDescription) input
705 );
706 final Collection<Media> media = Collections2.transform(descriptions, RtpDescription::getMedia);
707 Preconditions.checkState(!media.contains(Media.UNKNOWN), "RTP descriptions contain unknown media");
708 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session proposal from " + from + " for " + media);
709 this.proposedMedia = Sets.newHashSet(media);
710 })) {
711 if (serverMsgId != null) {
712 this.message.setServerMsgId(serverMsgId);
713 }
714 this.message.setTime(timestamp);
715 startRinging();
716 } else {
717 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
718 }
719 }
720
721 private void startRinging() {
722 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
723 ringingTimeoutFuture = jingleConnectionManager.schedule(this::ringingTimeout, BUSY_TIME_OUT, TimeUnit.SECONDS);
724 xmppConnectionService.getNotificationService().startRinging(id, getMedia());
725 }
726
727 private synchronized void ringingTimeout() {
728 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": timeout reached for ringing");
729 switch (this.state) {
730 case PROPOSED:
731 message.markUnread();
732 rejectCallFromProposed();
733 break;
734 case SESSION_INITIALIZED:
735 message.markUnread();
736 rejectCallFromSessionInitiate();
737 break;
738 }
739 }
740
741 private void cancelRingingTimeout() {
742 final ScheduledFuture<?> future = this.ringingTimeoutFuture;
743 if (future != null && !future.isCancelled()) {
744 future.cancel(false);
745 }
746 }
747
748 private void receiveProceed(final Jid from, final Proceed proceed, final String serverMsgId, final long timestamp) {
749 final Set<Media> media = Preconditions.checkNotNull(this.proposedMedia, "Proposed media has to be set before handling proceed");
750 Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
751 if (from.equals(id.with)) {
752 if (isInitiator()) {
753 if (transition(State.PROCEED)) {
754 if (serverMsgId != null) {
755 this.message.setServerMsgId(serverMsgId);
756 }
757 this.message.setTime(timestamp);
758 final Integer remoteDeviceId = proceed.getDeviceId();
759 if (isOmemoEnabled()) {
760 this.omemoVerification.setDeviceId(remoteDeviceId);
761 } else {
762 if (remoteDeviceId != null) {
763 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": remote party signaled support for OMEMO verification but we have OMEMO disabled");
764 }
765 this.omemoVerification.setDeviceId(null);
766 }
767 this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
768 } else {
769 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
770 }
771 } else {
772 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
773 }
774 } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
775 if (transition(State.ACCEPTED)) {
776 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
777 this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
778 this.finish();
779 }
780 } else {
781 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
782 }
783 }
784
785 private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
786 if (from.equals(id.with)) {
787 final State target = this.state == State.PROCEED ? State.RETRACTED_RACED : State.RETRACTED;
788 if (transition(target)) {
789 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
790 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted (serverMsgId=" + serverMsgId + ")");
791 if (serverMsgId != null) {
792 this.message.setServerMsgId(serverMsgId);
793 }
794 this.message.setTime(timestamp);
795 if (target == State.RETRACTED) {
796 this.message.markUnread();
797 }
798 writeLogMessageMissed();
799 finish();
800 } else {
801 Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
802 }
803 } else {
804 //TODO parse retract from self
805 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
806 }
807 }
808
809 public void sendSessionInitiate() {
810 sendSessionInitiate(this.proposedMedia, State.SESSION_INITIALIZED);
811 }
812
813 private void sendSessionInitiate(final Set<Media> media, final State targetState) {
814 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
815 discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
816 }
817
818 private synchronized void sendSessionInitiate(final Set<Media> media, final State targetState, final List<PeerConnection.IceServer> iceServers) {
819 if (isTerminated()) {
820 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
821 return;
822 }
823 try {
824 setupWebRTC(media, iceServers);
825 } catch (final WebRTCWrapper.InitializationException e) {
826 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
827 webRTCWrapper.close();
828 sendRetract(Reason.ofThrowable(e));
829 return;
830 }
831 try {
832 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
833 prepareSessionInitiate(webRTCSessionDescription, targetState);
834 } catch (final Exception e) {
835 failureToInitiateSession(e, targetState);
836 }
837 }
838
839 private void failureToInitiateSession(final Throwable throwable, final State targetState) {
840 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", Throwables.getRootCause(throwable));
841 webRTCWrapper.close();
842 final Reason reason = Reason.ofThrowable(throwable);
843 if (isInState(targetState)) {
844 sendSessionTerminate(reason);
845 } else {
846 sendRetract(reason);
847 }
848 }
849
850 private void sendRetract(final Reason reason) {
851 //TODO embed reason into retract
852 sendJingleMessage("retract", id.with.asBareJid());
853 transitionOrThrow(reasonToState(reason));
854 this.finish();
855 }
856
857 private void prepareSessionInitiate(final org.webrtc.SessionDescription webRTCSessionDescription, final State targetState) {
858 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
859 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
860 this.initiatorRtpContentMap = rtpContentMap;
861 final ListenableFuture<RtpContentMap> outgoingContentMapFuture = encryptSessionInitiate(rtpContentMap);
862 Futures.addCallback(outgoingContentMapFuture, new FutureCallback<RtpContentMap>() {
863 @Override
864 public void onSuccess(final RtpContentMap outgoingContentMap) {
865 sendSessionInitiate(outgoingContentMap, webRTCSessionDescription, targetState);
866 }
867
868 @Override
869 public void onFailure(@NonNull final Throwable throwable) {
870 failureToInitiateSession(throwable, targetState);
871 }
872 }, MoreExecutors.directExecutor());
873 }
874
875 private void sendSessionInitiate(final RtpContentMap rtpContentMap, final org.webrtc.SessionDescription webRTCSessionDescription, final State targetState) {
876 this.transitionOrThrow(targetState);
877 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
878 send(sessionInitiate);
879 try {
880 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
881 } catch (Exception e) {
882 failureToInitiateSession(e, targetState);
883 }
884 }
885
886 private ListenableFuture<RtpContentMap> encryptSessionInitiate(final RtpContentMap rtpContentMap) {
887 if (this.omemoVerification.hasDeviceId()) {
888 final ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>> verifiedPayloadFuture = id.account.getAxolotlService()
889 .encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
890 final ListenableFuture<RtpContentMap> future = Futures.transform(verifiedPayloadFuture, verifiedPayload -> {
891 omemoVerification.setSessionFingerprint(verifiedPayload.getFingerprint());
892 return verifiedPayload.getPayload();
893 }, MoreExecutors.directExecutor());
894 if (Config.REQUIRE_RTP_VERIFICATION) {
895 return future;
896 }
897 return Futures.catching(
898 future,
899 CryptoFailedException.class,
900 e -> {
901 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to use OMEMO DTLS verification on outgoing session initiate. falling back", e);
902 return rtpContentMap;
903 },
904 MoreExecutors.directExecutor()
905 );
906 } else {
907 return Futures.immediateFuture(rtpContentMap);
908 }
909 }
910
911 private void sendSessionTerminate(final Reason reason) {
912 sendSessionTerminate(reason, null);
913 }
914
915 private void sendSessionTerminate(final Reason reason, final String text) {
916 final State previous = this.state;
917 final State target = reasonToState(reason);
918 transitionOrThrow(target);
919 if (previous != State.NULL) {
920 writeLogMessage(target);
921 }
922 final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
923 jinglePacket.setReason(reason, text);
924 Log.d(Config.LOGTAG, jinglePacket.toString());
925 send(jinglePacket);
926 finish();
927 }
928
929 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
930 final RtpContentMap transportInfo;
931 try {
932 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
933 transportInfo = rtpContentMap.transportInfo(contentName, candidate);
934 } catch (final Exception e) {
935 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
936 return;
937 }
938 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
939 send(jinglePacket);
940 }
941
942 private void send(final JinglePacket jinglePacket) {
943 jinglePacket.setTo(id.with);
944 xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
945 }
946
947 private synchronized void handleIqResponse(final Account account, final IqPacket response) {
948 if (response.getType() == IqPacket.TYPE.ERROR) {
949 final String errorCondition = response.getErrorCondition();
950 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
951 if (isTerminated()) {
952 Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
953 return;
954 }
955 this.webRTCWrapper.close();
956 final State target;
957 if (Arrays.asList(
958 "service-unavailable",
959 "recipient-unavailable",
960 "remote-server-not-found",
961 "remote-server-timeout"
962 ).contains(errorCondition)) {
963 target = State.TERMINATED_CONNECTIVITY_ERROR;
964 } else {
965 target = State.TERMINATED_APPLICATION_FAILURE;
966 }
967 transitionOrThrow(target);
968 this.finish();
969 } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
970 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
971 if (isTerminated()) {
972 Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
973 return;
974 }
975 this.webRTCWrapper.close();
976 transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
977 this.finish();
978 }
979 }
980
981 private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
982 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
983 this.webRTCWrapper.close();
984 transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
985 respondWithOutOfOrder(jinglePacket);
986 this.finish();
987 }
988
989 private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
990 jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
991 }
992
993 private void respondOk(final JinglePacket jinglePacket) {
994 xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
995 }
996
997 public void throwStateTransitionException() {
998 final StateTransitionException exception = this.stateTransitionException;
999 if (exception != null) {
1000 throw new IllegalStateException(String.format("Transition to %s did not call finish", exception.state), exception);
1001 }
1002 }
1003
1004 public RtpEndUserState getEndUserState() {
1005 switch (this.state) {
1006 case NULL:
1007 case PROPOSED:
1008 case SESSION_INITIALIZED:
1009 if (isInitiator()) {
1010 return RtpEndUserState.RINGING;
1011 } else {
1012 return RtpEndUserState.INCOMING_CALL;
1013 }
1014 case PROCEED:
1015 if (isInitiator()) {
1016 return RtpEndUserState.RINGING;
1017 } else {
1018 return RtpEndUserState.ACCEPTING_CALL;
1019 }
1020 case SESSION_INITIALIZED_PRE_APPROVED:
1021 if (isInitiator()) {
1022 return RtpEndUserState.RINGING;
1023 } else {
1024 return RtpEndUserState.CONNECTING;
1025 }
1026 case SESSION_ACCEPTED:
1027 final PeerConnection.PeerConnectionState state;
1028 try {
1029 state = webRTCWrapper.getState();
1030 } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
1031 //We usually close the WebRTCWrapper *before* transitioning so we might still
1032 //be in SESSION_ACCEPTED even though the peerConnection has been torn down
1033 return RtpEndUserState.ENDING_CALL;
1034 }
1035 if (state == PeerConnection.PeerConnectionState.CONNECTED) {
1036 return RtpEndUserState.CONNECTED;
1037 } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
1038 return RtpEndUserState.CONNECTING;
1039 } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
1040 return RtpEndUserState.ENDING_CALL;
1041 } else {
1042 return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
1043 }
1044 case REJECTED:
1045 case REJECTED_RACED:
1046 case TERMINATED_DECLINED_OR_BUSY:
1047 if (isInitiator()) {
1048 return RtpEndUserState.DECLINED_OR_BUSY;
1049 } else {
1050 return RtpEndUserState.ENDED;
1051 }
1052 case TERMINATED_SUCCESS:
1053 case ACCEPTED:
1054 case RETRACTED:
1055 case TERMINATED_CANCEL_OR_TIMEOUT:
1056 return RtpEndUserState.ENDED;
1057 case RETRACTED_RACED:
1058 if (isInitiator()) {
1059 return RtpEndUserState.ENDED;
1060 } else {
1061 return RtpEndUserState.RETRACTED;
1062 }
1063 case TERMINATED_CONNECTIVITY_ERROR:
1064 return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
1065 case TERMINATED_APPLICATION_FAILURE:
1066 return RtpEndUserState.APPLICATION_ERROR;
1067 case TERMINATED_SECURITY_ERROR:
1068 return RtpEndUserState.SECURITY_ERROR;
1069 }
1070 throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
1071 }
1072
1073 public Set<Media> getMedia() {
1074 final State current = getState();
1075 if (current == State.NULL) {
1076 if (isInitiator()) {
1077 return Preconditions.checkNotNull(
1078 this.proposedMedia,
1079 "RTP connection has not been initialized properly"
1080 );
1081 }
1082 throw new IllegalStateException("RTP connection has not been initialized yet");
1083 }
1084 if (Arrays.asList(State.PROPOSED, State.PROCEED).contains(current)) {
1085 return Preconditions.checkNotNull(
1086 this.proposedMedia,
1087 "RTP connection has not been initialized properly"
1088 );
1089 }
1090 final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
1091 if (initiatorContentMap != null) {
1092 return initiatorContentMap.getMedia();
1093 } else if (isTerminated()) {
1094 return Collections.emptySet(); //we might fail before we ever got a chance to set media
1095 } else {
1096 return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
1097 }
1098 }
1099
1100
1101 public boolean isVerified() {
1102 final String fingerprint = this.omemoVerification.getFingerprint();
1103 if (fingerprint == null) {
1104 return false;
1105 }
1106 final FingerprintStatus status = id.account.getAxolotlService().getFingerprintTrust(fingerprint);
1107 return status != null && status.isVerified();
1108 }
1109
1110 public synchronized void acceptCall() {
1111 switch (this.state) {
1112 case PROPOSED:
1113 cancelRingingTimeout();
1114 acceptCallFromProposed();
1115 break;
1116 case SESSION_INITIALIZED:
1117 cancelRingingTimeout();
1118 acceptCallFromSessionInitialized();
1119 break;
1120 case ACCEPTED:
1121 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted with another client. UI was just lagging behind");
1122 break;
1123 case PROCEED:
1124 case SESSION_ACCEPTED:
1125 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted. user probably double tapped the UI");
1126 break;
1127 default:
1128 throw new IllegalStateException("Can not accept call from " + this.state);
1129 }
1130 }
1131
1132
1133 public void notifyPhoneCall() {
1134 Log.d(Config.LOGTAG, "a phone call has just been started. killing jingle rtp connections");
1135 if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(this.state)) {
1136 rejectCall();
1137 } else {
1138 endCall();
1139 }
1140 }
1141
1142 public synchronized void rejectCall() {
1143 if (isTerminated()) {
1144 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received rejectCall() when session has already been terminated. nothing to do");
1145 return;
1146 }
1147 switch (this.state) {
1148 case PROPOSED:
1149 rejectCallFromProposed();
1150 break;
1151 case SESSION_INITIALIZED:
1152 rejectCallFromSessionInitiate();
1153 break;
1154 default:
1155 throw new IllegalStateException("Can not reject call from " + this.state);
1156 }
1157 }
1158
1159 public synchronized void endCall() {
1160 if (isTerminated()) {
1161 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
1162 return;
1163 }
1164 if (isInState(State.PROPOSED) && !isInitiator()) {
1165 rejectCallFromProposed();
1166 return;
1167 }
1168 if (isInState(State.PROCEED)) {
1169 if (isInitiator()) {
1170 retractFromProceed();
1171 } else {
1172 rejectCallFromProceed();
1173 }
1174 return;
1175 }
1176 if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
1177 this.webRTCWrapper.close();
1178 sendSessionTerminate(Reason.CANCEL);
1179 return;
1180 }
1181 if (isInState(State.SESSION_INITIALIZED)) {
1182 rejectCallFromSessionInitiate();
1183 return;
1184 }
1185 if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
1186 this.webRTCWrapper.close();
1187 sendSessionTerminate(Reason.SUCCESS);
1188 return;
1189 }
1190 if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
1191 Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
1192 return;
1193 }
1194 throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
1195 }
1196
1197 private void retractFromProceed() {
1198 Log.d(Config.LOGTAG, "retract from proceed");
1199 this.sendJingleMessage("retract");
1200 closeTransitionLogFinish(State.RETRACTED_RACED);
1201 }
1202
1203 private void closeTransitionLogFinish(final State state) {
1204 this.webRTCWrapper.close();
1205 transitionOrThrow(state);
1206 writeLogMessage(state);
1207 finish();
1208 }
1209
1210 private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
1211 this.jingleConnectionManager.ensureConnectionIsRegistered(this);
1212 final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
1213 if (media.contains(Media.VIDEO)) {
1214 speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
1215 } else {
1216 speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
1217 }
1218 this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
1219 this.webRTCWrapper.initializePeerConnection(media, iceServers);
1220 }
1221
1222 private void acceptCallFromProposed() {
1223 transitionOrThrow(State.PROCEED);
1224 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1225 this.sendJingleMessage("accept", id.account.getJid().asBareJid());
1226 this.sendJingleMessage("proceed");
1227 }
1228
1229 private void rejectCallFromProposed() {
1230 transitionOrThrow(State.REJECTED);
1231 writeLogMessageMissed();
1232 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1233 this.sendJingleMessage("reject");
1234 finish();
1235 }
1236
1237 private void rejectCallFromProceed() {
1238 this.sendJingleMessage("reject");
1239 closeTransitionLogFinish(State.REJECTED_RACED);
1240 }
1241
1242 private void rejectCallFromSessionInitiate() {
1243 webRTCWrapper.close();
1244 sendSessionTerminate(Reason.DECLINE);
1245 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1246 }
1247
1248 private void sendJingleMessage(final String action) {
1249 sendJingleMessage(action, id.with);
1250 }
1251
1252 private void sendJingleMessage(final String action, final Jid to) {
1253 final MessagePacket messagePacket = new MessagePacket();
1254 messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
1255 messagePacket.setTo(to);
1256 final Element intent = messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
1257 if ("proceed".equals(action)) {
1258 messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
1259 if (isOmemoEnabled()) {
1260 final int deviceId = id.account.getAxolotlService().getOwnDeviceId();
1261 final Element device = intent.addChild("device", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
1262 device.setAttribute("id", deviceId);
1263 }
1264 }
1265 messagePacket.addChild("store", "urn:xmpp:hints");
1266 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
1267 }
1268
1269 private boolean isOmemoEnabled() {
1270 final Conversational conversational = message.getConversation();
1271 if (conversational instanceof Conversation) {
1272 return ((Conversation) conversational).getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
1273 }
1274 return false;
1275 }
1276
1277 private void acceptCallFromSessionInitialized() {
1278 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1279 sendSessionAccept();
1280 }
1281
1282 private synchronized boolean isInState(State... state) {
1283 return Arrays.asList(state).contains(this.state);
1284 }
1285
1286 private boolean transition(final State target) {
1287 return transition(target, null);
1288 }
1289
1290 private synchronized boolean transition(final State target, final Runnable runnable) {
1291 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
1292 if (validTransitions != null && validTransitions.contains(target)) {
1293 this.state = target;
1294 this.stateTransitionException = new StateTransitionException(target);
1295 if (runnable != null) {
1296 runnable.run();
1297 }
1298 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
1299 updateEndUserState();
1300 updateOngoingCallNotification();
1301 return true;
1302 } else {
1303 return false;
1304 }
1305 }
1306
1307 void transitionOrThrow(final State target) {
1308 if (!transition(target)) {
1309 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
1310 }
1311 }
1312
1313 @Override
1314 public void onIceCandidate(final IceCandidate iceCandidate) {
1315 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
1316 Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
1317 sendTransportInfo(iceCandidate.sdpMid, candidate);
1318 }
1319
1320 @Override
1321 public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
1322 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
1323 if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
1324 this.rtpConnectionStarted = SystemClock.elapsedRealtime();
1325 }
1326 if (newState == PeerConnection.PeerConnectionState.CLOSED && this.rtpConnectionEnded == 0) {
1327 this.rtpConnectionEnded = SystemClock.elapsedRealtime();
1328 }
1329 //TODO 'DISCONNECTED' might be an opportunity to renew the offer and send a transport-replace
1330 //TODO exact syntax is yet to be determined but transport-replace sounds like the most reasonable
1331 //as there is no content-replace
1332 if (Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
1333 if (isTerminated()) {
1334 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
1335 return;
1336 }
1337 new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
1338 } else {
1339 updateEndUserState();
1340 }
1341 }
1342
1343 private void closeWebRTCSessionAfterFailedConnection() {
1344 this.webRTCWrapper.close();
1345 synchronized (this) {
1346 if (isTerminated()) {
1347 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
1348 return;
1349 }
1350 sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
1351 }
1352 }
1353
1354 public long getRtpConnectionStarted() {
1355 return this.rtpConnectionStarted;
1356 }
1357
1358 public long getRtpConnectionEnded() {
1359 return this.rtpConnectionEnded;
1360 }
1361
1362 public AppRTCAudioManager getAudioManager() {
1363 return webRTCWrapper.getAudioManager();
1364 }
1365
1366 public boolean isMicrophoneEnabled() {
1367 return webRTCWrapper.isMicrophoneEnabled();
1368 }
1369
1370 public boolean setMicrophoneEnabled(final boolean enabled) {
1371 return webRTCWrapper.setMicrophoneEnabled(enabled);
1372 }
1373
1374 public boolean isVideoEnabled() {
1375 return webRTCWrapper.isVideoEnabled();
1376 }
1377
1378 public void setVideoEnabled(final boolean enabled) {
1379 webRTCWrapper.setVideoEnabled(enabled);
1380 }
1381
1382 public boolean isCameraSwitchable() {
1383 return webRTCWrapper.isCameraSwitchable();
1384 }
1385
1386 public boolean isFrontCamera() {
1387 return webRTCWrapper.isFrontCamera();
1388 }
1389
1390 public ListenableFuture<Boolean> switchCamera() {
1391 return webRTCWrapper.switchCamera();
1392 }
1393
1394 @Override
1395 public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1396 xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1397 }
1398
1399 private void updateEndUserState() {
1400 final RtpEndUserState endUserState = getEndUserState();
1401 jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
1402 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1403 }
1404
1405 private void updateOngoingCallNotification() {
1406 if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1407 xmppConnectionService.setOngoingCall(id, getMedia());
1408 } else {
1409 xmppConnectionService.removeOngoingCall();
1410 }
1411 }
1412
1413 private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1414 if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1415 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1416 request.setTo(id.account.getDomain());
1417 request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1418 xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1419 ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1420 if (response.getType() == IqPacket.TYPE.RESULT) {
1421 final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1422 final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1423 for (final Element child : children) {
1424 if ("service".equals(child.getName())) {
1425 final String type = child.getAttribute("type");
1426 final String host = child.getAttribute("host");
1427 final String sport = child.getAttribute("port");
1428 final Integer port = sport == null ? null : Ints.tryParse(sport);
1429 final String transport = child.getAttribute("transport");
1430 final String username = child.getAttribute("username");
1431 final String password = child.getAttribute("password");
1432 if (Strings.isNullOrEmpty(host) || port == null) {
1433 continue;
1434 }
1435 if (port < 0 || port > 65535) {
1436 continue;
1437 }
1438 if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1439 if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1440 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1441 continue;
1442 }
1443 final PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer
1444 .builder(String.format("%s:%s:%s?transport=%s", type, IP.wrapIPv6(host), port, transport));
1445 iceServerBuilder.setTlsCertPolicy(PeerConnection.TlsCertPolicy.TLS_CERT_POLICY_INSECURE_NO_CHECK);
1446 if (username != null && password != null) {
1447 iceServerBuilder.setUsername(username);
1448 iceServerBuilder.setPassword(password);
1449 } else if (Arrays.asList("turn", "turns").contains(type)) {
1450 //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1451 //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1452 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1453 continue;
1454 }
1455 final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1456 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1457 listBuilder.add(iceServer);
1458 }
1459 }
1460 }
1461 }
1462 final List<PeerConnection.IceServer> iceServers = listBuilder.build();
1463 if (iceServers.size() == 0) {
1464 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1465 }
1466 onIceServersDiscovered.onIceServersDiscovered(iceServers);
1467 });
1468 } else {
1469 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1470 onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1471 }
1472 }
1473
1474 private void finish() {
1475 if (isTerminated()) {
1476 this.cancelRingingTimeout();
1477 this.webRTCWrapper.verifyClosed();
1478 this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
1479 this.jingleConnectionManager.finishConnectionOrThrow(this);
1480 } else {
1481 throw new IllegalStateException(String.format("Unable to call finish from %s", this.state));
1482 }
1483 }
1484
1485 private void writeLogMessage(final State state) {
1486 final long started = this.rtpConnectionStarted;
1487 long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1488 if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1489 writeLogMessageSuccess(duration);
1490 } else {
1491 writeLogMessageMissed();
1492 }
1493 }
1494
1495 private void writeLogMessageSuccess(final long duration) {
1496 this.message.setBody(new RtpSessionStatus(true, duration).toString());
1497 this.writeMessage();
1498 }
1499
1500 private void writeLogMessageMissed() {
1501 this.message.setBody(new RtpSessionStatus(false, 0).toString());
1502 this.writeMessage();
1503 }
1504
1505 private void writeMessage() {
1506 final Conversational conversational = message.getConversation();
1507 if (conversational instanceof Conversation) {
1508 ((Conversation) conversational).add(this.message);
1509 xmppConnectionService.createMessageAsync(message);
1510 xmppConnectionService.updateConversationUi();
1511 } else {
1512 throw new IllegalStateException("Somehow the conversation in a message was a stub");
1513 }
1514 }
1515
1516 public State getState() {
1517 return this.state;
1518 }
1519
1520 boolean isTerminated() {
1521 return TERMINATED.contains(this.state);
1522 }
1523
1524 public Optional<VideoTrack> getLocalVideoTrack() {
1525 return webRTCWrapper.getLocalVideoTrack();
1526 }
1527
1528 public Optional<VideoTrack> getRemoteVideoTrack() {
1529 return webRTCWrapper.getRemoteVideoTrack();
1530 }
1531
1532
1533 public EglBase.Context getEglBaseContext() {
1534 return webRTCWrapper.getEglBaseContext();
1535 }
1536
1537 void setProposedMedia(final Set<Media> media) {
1538 this.proposedMedia = media;
1539 }
1540
1541 public void fireStateUpdate() {
1542 final RtpEndUserState endUserState = getEndUserState();
1543 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1544 }
1545
1546 private interface OnIceServersDiscovered {
1547 void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1548 }
1549
1550 private static class StateTransitionException extends Exception {
1551 private final State state;
1552
1553 private StateTransitionException(final State state) {
1554 this.state = state;
1555 }
1556 }
1557}