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