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