JingleRtpConnection.java

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