JingleRtpConnection.java

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