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