JingleRtpConnection.java

   1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.util.Log;
   4
   5import androidx.annotation.NonNull;
   6import androidx.annotation.Nullable;
   7
   8import com.google.common.base.Joiner;
   9import com.google.common.base.Optional;
  10import com.google.common.base.Preconditions;
  11import com.google.common.base.Stopwatch;
  12import com.google.common.base.Strings;
  13import com.google.common.base.Throwables;
  14import com.google.common.collect.Collections2;
  15import com.google.common.collect.ImmutableList;
  16import com.google.common.collect.ImmutableMap;
  17import com.google.common.collect.ImmutableSet;
  18import com.google.common.collect.Sets;
  19import com.google.common.primitives.Ints;
  20import com.google.common.util.concurrent.FutureCallback;
  21import com.google.common.util.concurrent.Futures;
  22import com.google.common.util.concurrent.ListenableFuture;
  23import com.google.common.util.concurrent.MoreExecutors;
  24
  25import org.webrtc.EglBase;
  26import org.webrtc.IceCandidate;
  27import org.webrtc.PeerConnection;
  28import org.webrtc.VideoTrack;
  29
  30import java.util.Arrays;
  31import java.util.Collection;
  32import java.util.Collections;
  33import java.util.LinkedList;
  34import java.util.List;
  35import java.util.Map;
  36import java.util.Queue;
  37import java.util.Set;
  38import java.util.concurrent.ExecutionException;
  39import java.util.concurrent.ScheduledFuture;
  40import java.util.concurrent.TimeUnit;
  41
  42import eu.siacs.conversations.BuildConfig;
  43import eu.siacs.conversations.Config;
  44import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  45import eu.siacs.conversations.crypto.axolotl.CryptoFailedException;
  46import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  47import eu.siacs.conversations.entities.Account;
  48import eu.siacs.conversations.entities.Contact;
  49import eu.siacs.conversations.entities.Conversation;
  50import eu.siacs.conversations.entities.Conversational;
  51import eu.siacs.conversations.entities.Message;
  52import eu.siacs.conversations.entities.Presence;
  53import eu.siacs.conversations.entities.RtpSessionStatus;
  54import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  55import eu.siacs.conversations.services.AppRTCAudioManager;
  56import eu.siacs.conversations.utils.IP;
  57import eu.siacs.conversations.xml.Element;
  58import eu.siacs.conversations.xml.Namespace;
  59import eu.siacs.conversations.xmpp.Jid;
  60import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
  61import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
  62import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
  63import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  64import eu.siacs.conversations.xmpp.jingle.stanzas.Proceed;
  65import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  66import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  67import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  68import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  69import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  70
  71public class JingleRtpConnection extends AbstractJingleConnection
  72        implements WebRTCWrapper.EventCallback {
  73
  74    public static final List<State> STATES_SHOWING_ONGOING_CALL =
  75            Arrays.asList(
  76                    State.PROCEED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED);
  77    private static final long BUSY_TIME_OUT = 30;
  78    private static final List<State> TERMINATED =
  79            Arrays.asList(
  80                    State.ACCEPTED,
  81                    State.REJECTED,
  82                    State.REJECTED_RACED,
  83                    State.RETRACTED,
  84                    State.RETRACTED_RACED,
  85                    State.TERMINATED_SUCCESS,
  86                    State.TERMINATED_DECLINED_OR_BUSY,
  87                    State.TERMINATED_CONNECTIVITY_ERROR,
  88                    State.TERMINATED_CANCEL_OR_TIMEOUT,
  89                    State.TERMINATED_APPLICATION_FAILURE,
  90                    State.TERMINATED_SECURITY_ERROR);
  91
  92    private static final Map<State, Collection<State>> VALID_TRANSITIONS;
  93
  94    static {
  95        final ImmutableMap.Builder<State, Collection<State>> transitionBuilder =
  96                new ImmutableMap.Builder<>();
  97        transitionBuilder.put(
  98                State.NULL,
  99                ImmutableList.of(
 100                        State.PROPOSED,
 101                        State.SESSION_INITIALIZED,
 102                        State.TERMINATED_APPLICATION_FAILURE,
 103                        State.TERMINATED_SECURITY_ERROR));
 104        transitionBuilder.put(
 105                State.PROPOSED,
 106                ImmutableList.of(
 107                        State.ACCEPTED,
 108                        State.PROCEED,
 109                        State.REJECTED,
 110                        State.RETRACTED,
 111                        State.TERMINATED_APPLICATION_FAILURE,
 112                        State.TERMINATED_SECURITY_ERROR,
 113                        State.TERMINATED_CONNECTIVITY_ERROR // only used when the xmpp connection
 114                        // rebinds
 115                        ));
 116        transitionBuilder.put(
 117                State.PROCEED,
 118                ImmutableList.of(
 119                        State.REJECTED_RACED,
 120                        State.RETRACTED_RACED,
 121                        State.SESSION_INITIALIZED_PRE_APPROVED,
 122                        State.TERMINATED_SUCCESS,
 123                        State.TERMINATED_APPLICATION_FAILURE,
 124                        State.TERMINATED_SECURITY_ERROR,
 125                        State.TERMINATED_CONNECTIVITY_ERROR // at this state used for error
 126                        // bounces of the proceed message
 127                        ));
 128        transitionBuilder.put(
 129                State.SESSION_INITIALIZED,
 130                ImmutableList.of(
 131                        State.SESSION_ACCEPTED,
 132                        State.TERMINATED_SUCCESS,
 133                        State.TERMINATED_DECLINED_OR_BUSY,
 134                        State.TERMINATED_CONNECTIVITY_ERROR, // at this state used for IQ errors
 135                        // and IQ timeouts
 136                        State.TERMINATED_CANCEL_OR_TIMEOUT,
 137                        State.TERMINATED_APPLICATION_FAILURE,
 138                        State.TERMINATED_SECURITY_ERROR));
 139        transitionBuilder.put(
 140                State.SESSION_INITIALIZED_PRE_APPROVED,
 141                ImmutableList.of(
 142                        State.SESSION_ACCEPTED,
 143                        State.TERMINATED_SUCCESS,
 144                        State.TERMINATED_DECLINED_OR_BUSY,
 145                        State.TERMINATED_CONNECTIVITY_ERROR, // at this state used for IQ errors
 146                        // and IQ timeouts
 147                        State.TERMINATED_CANCEL_OR_TIMEOUT,
 148                        State.TERMINATED_APPLICATION_FAILURE,
 149                        State.TERMINATED_SECURITY_ERROR));
 150        transitionBuilder.put(
 151                State.SESSION_ACCEPTED,
 152                ImmutableList.of(
 153                        State.TERMINATED_SUCCESS,
 154                        State.TERMINATED_DECLINED_OR_BUSY,
 155                        State.TERMINATED_CONNECTIVITY_ERROR,
 156                        State.TERMINATED_CANCEL_OR_TIMEOUT,
 157                        State.TERMINATED_APPLICATION_FAILURE,
 158                        State.TERMINATED_SECURITY_ERROR));
 159        VALID_TRANSITIONS = transitionBuilder.build();
 160    }
 161
 162    private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
 163    private final Queue<Map.Entry<String, RtpContentMap.DescriptionTransport>>
 164            pendingIceCandidates = new LinkedList<>();
 165    private final OmemoVerification omemoVerification = new OmemoVerification();
 166    private final Message message;
 167    private State state = State.NULL;
 168    private Set<Media> proposedMedia;
 169    private RtpContentMap initiatorRtpContentMap;
 170    private RtpContentMap responderRtpContentMap;
 171    private RtpContentMap incomingContentAdd;
 172    private RtpContentMap outgoingContentAdd;
 173    private IceUdpTransportInfo.Setup peerDtlsSetup;
 174    private final Stopwatch sessionDuration = Stopwatch.createUnstarted();
 175    private final Queue<PeerConnection.PeerConnectionState> stateHistory = new LinkedList<>();
 176    private ScheduledFuture<?> ringingTimeoutFuture;
 177
 178    JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
 179        super(jingleConnectionManager, id, initiator);
 180        final Conversation conversation =
 181                jingleConnectionManager
 182                        .getXmppConnectionService()
 183                        .findOrCreateConversation(id.account, id.with.asBareJid(), false, false);
 184        this.message =
 185                new Message(
 186                        conversation,
 187                        isInitiator() ? Message.STATUS_SEND : Message.STATUS_RECEIVED,
 188                        Message.TYPE_RTP_SESSION,
 189                        id.sessionId);
 190    }
 191
 192    private static State reasonToState(Reason reason) {
 193        switch (reason) {
 194            case SUCCESS:
 195                return State.TERMINATED_SUCCESS;
 196            case DECLINE:
 197            case BUSY:
 198                return State.TERMINATED_DECLINED_OR_BUSY;
 199            case CANCEL:
 200            case TIMEOUT:
 201                return State.TERMINATED_CANCEL_OR_TIMEOUT;
 202            case SECURITY_ERROR:
 203                return State.TERMINATED_SECURITY_ERROR;
 204            case FAILED_APPLICATION:
 205            case UNSUPPORTED_TRANSPORTS:
 206            case UNSUPPORTED_APPLICATIONS:
 207                return State.TERMINATED_APPLICATION_FAILURE;
 208            default:
 209                return State.TERMINATED_CONNECTIVITY_ERROR;
 210        }
 211    }
 212
 213    @Override
 214    synchronized void deliverPacket(final JinglePacket jinglePacket) {
 215        switch (jinglePacket.getAction()) {
 216            case SESSION_INITIATE:
 217                receiveSessionInitiate(jinglePacket);
 218                break;
 219            case TRANSPORT_INFO:
 220                receiveTransportInfo(jinglePacket);
 221                break;
 222            case SESSION_ACCEPT:
 223                receiveSessionAccept(jinglePacket);
 224                break;
 225            case SESSION_TERMINATE:
 226                receiveSessionTerminate(jinglePacket);
 227                break;
 228            case CONTENT_ADD:
 229                receiveContentAdd(jinglePacket);
 230                break;
 231            case CONTENT_ACCEPT:
 232                receiveContentAccept(jinglePacket);
 233                break;
 234            case CONTENT_REJECT:
 235                receiveContentReject(jinglePacket);
 236                break;
 237            case CONTENT_REMOVE:
 238                receiveContentRemove(jinglePacket);
 239                break;
 240            default:
 241                respondOk(jinglePacket);
 242                Log.d(
 243                        Config.LOGTAG,
 244                        String.format(
 245                                "%s: received unhandled jingle action %s",
 246                                id.account.getJid().asBareJid(), jinglePacket.getAction()));
 247                break;
 248        }
 249    }
 250
 251    @Override
 252    synchronized void notifyRebound() {
 253        if (isTerminated()) {
 254            return;
 255        }
 256        webRTCWrapper.close();
 257        if (!isInitiator() && isInState(State.PROPOSED, State.SESSION_INITIALIZED)) {
 258            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 259        }
 260        if (isInState(
 261                State.SESSION_INITIALIZED,
 262                State.SESSION_INITIALIZED_PRE_APPROVED,
 263                State.SESSION_ACCEPTED)) {
 264            // we might have already changed resources (full jid) at this point; so this might not
 265            // even reach the other party
 266            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 267        } else {
 268            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 269            finish();
 270        }
 271    }
 272
 273    private void receiveSessionTerminate(final JinglePacket jinglePacket) {
 274        respondOk(jinglePacket);
 275        final JinglePacket.ReasonWrapper wrapper = jinglePacket.getReason();
 276        final State previous = this.state;
 277        Log.d(
 278                Config.LOGTAG,
 279                id.account.getJid().asBareJid()
 280                        + ": received session terminate reason="
 281                        + wrapper.reason
 282                        + "("
 283                        + Strings.nullToEmpty(wrapper.text)
 284                        + ") while in state "
 285                        + previous);
 286        if (TERMINATED.contains(previous)) {
 287            Log.d(
 288                    Config.LOGTAG,
 289                    id.account.getJid().asBareJid()
 290                            + ": ignoring session terminate because already in "
 291                            + previous);
 292            return;
 293        }
 294        webRTCWrapper.close();
 295        final State target = reasonToState(wrapper.reason);
 296        transitionOrThrow(target);
 297        writeLogMessage(target);
 298        if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
 299            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 300        }
 301        finish();
 302    }
 303
 304    private void receiveTransportInfo(final JinglePacket jinglePacket) {
 305        // Due to the asynchronicity of processing session-init we might move from NULL|PROCEED to
 306        // INITIALIZED only after transport-info has been received
 307        if (isInState(
 308                State.NULL,
 309                State.PROCEED,
 310                State.SESSION_INITIALIZED,
 311                State.SESSION_INITIALIZED_PRE_APPROVED,
 312                State.SESSION_ACCEPTED)) {
 313            final RtpContentMap contentMap;
 314            try {
 315                contentMap = RtpContentMap.of(jinglePacket);
 316            } catch (final IllegalArgumentException | NullPointerException e) {
 317                Log.d(
 318                        Config.LOGTAG,
 319                        id.account.getJid().asBareJid()
 320                                + ": improperly formatted contents; ignoring",
 321                        e);
 322                respondOk(jinglePacket);
 323                return;
 324            }
 325            receiveTransportInfo(jinglePacket, contentMap);
 326        } else {
 327            if (isTerminated()) {
 328                respondOk(jinglePacket);
 329                Log.d(
 330                        Config.LOGTAG,
 331                        id.account.getJid().asBareJid()
 332                                + ": ignoring out-of-order transport info; we where already terminated");
 333            } else {
 334                Log.d(
 335                        Config.LOGTAG,
 336                        id.account.getJid().asBareJid()
 337                                + ": received transport info while in state="
 338                                + this.state);
 339                terminateWithOutOfOrder(jinglePacket);
 340            }
 341        }
 342    }
 343
 344    private void receiveTransportInfo(
 345            final JinglePacket jinglePacket, final RtpContentMap contentMap) {
 346        final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> candidates =
 347                contentMap.contents.entrySet();
 348        if (this.state == State.SESSION_ACCEPTED) {
 349            // zero candidates + modified credentials are an ICE restart offer
 350            if (checkForIceRestart(jinglePacket, contentMap)) {
 351                return;
 352            }
 353            respondOk(jinglePacket);
 354            try {
 355                processCandidates(candidates);
 356            } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
 357                Log.w(
 358                        Config.LOGTAG,
 359                        id.account.getJid().asBareJid()
 360                                + ": PeerConnection was not initialized when processing transport info. this usually indicates a race condition that can be ignored");
 361            }
 362        } else {
 363            respondOk(jinglePacket);
 364            pendingIceCandidates.addAll(candidates);
 365        }
 366    }
 367
 368    private void receiveContentAdd(final JinglePacket jinglePacket) {
 369        final RtpContentMap modification;
 370        try {
 371            modification = RtpContentMap.of(jinglePacket);
 372            modification.requireContentDescriptions();
 373        } catch (final RuntimeException e) {
 374            Log.d(
 375                    Config.LOGTAG,
 376                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 377                    Throwables.getRootCause(e));
 378            respondOk(jinglePacket);
 379            webRTCWrapper.close();
 380            sendSessionTerminate(Reason.of(e), e.getMessage());
 381            return;
 382        }
 383        if (isInState(State.SESSION_ACCEPTED)) {
 384            receiveContentAdd(jinglePacket, modification);
 385        } else {
 386            terminateWithOutOfOrder(jinglePacket);
 387        }
 388    }
 389
 390    private void receiveContentAdd(
 391            final JinglePacket jinglePacket, final RtpContentMap modification) {
 392        final RtpContentMap remote = getRemoteContentMap();
 393        if (!Collections.disjoint(modification.getNames(), remote.getNames())) {
 394            respondOk(jinglePacket);
 395            this.webRTCWrapper.close();
 396            sendSessionTerminate(
 397                    Reason.FAILED_APPLICATION,
 398                    String.format(
 399                            "contents with names %s already exists",
 400                            Joiner.on(", ").join(modification.getNames())));
 401            return;
 402        }
 403        final ContentAddition contentAddition =
 404                ContentAddition.of(ContentAddition.Direction.INCOMING, modification);
 405
 406        final RtpContentMap outgoing = this.outgoingContentAdd;
 407        final Set<ContentAddition.Summary> outgoingContentAddSummary =
 408                outgoing == null ? Collections.emptySet() : ContentAddition.summary(outgoing);
 409
 410        if (outgoingContentAddSummary.equals(contentAddition.summary)) {
 411            if (isInitiator()) {
 412                Log.d(
 413                        Config.LOGTAG,
 414                        id.getAccount().getJid().asBareJid()
 415                                + ": respond with tie break to matching content-add offer");
 416                respondWithTieBreak(jinglePacket);
 417            } else {
 418                Log.d(
 419                        Config.LOGTAG,
 420                        id.getAccount().getJid().asBareJid()
 421                                + ": automatically accept matching content-add offer");
 422                acceptContentAdd(contentAddition.summary, modification);
 423            }
 424            return;
 425        }
 426
 427        // once we can display multiple video tracks we can be more loose with this condition
 428        // theoretically it should also be fine to automatically accept audio only contents
 429        if (Media.audioOnly(remote.getMedia()) && Media.videoOnly(contentAddition.media())) {
 430            Log.d(
 431                    Config.LOGTAG,
 432                    id.getAccount().getJid().asBareJid() + ": received " + contentAddition);
 433            this.incomingContentAdd = modification;
 434            respondOk(jinglePacket);
 435            updateEndUserState();
 436        } else {
 437            respondOk(jinglePacket);
 438            // TODO do we want to add a reason?
 439            rejectContentAdd(modification);
 440        }
 441    }
 442
 443    private void receiveContentAccept(final JinglePacket jinglePacket) {
 444        final RtpContentMap receivedContentAccept;
 445        try {
 446            receivedContentAccept = RtpContentMap.of(jinglePacket);
 447            receivedContentAccept.requireContentDescriptions();
 448        } catch (final RuntimeException e) {
 449            Log.d(
 450                    Config.LOGTAG,
 451                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 452                    Throwables.getRootCause(e));
 453            respondOk(jinglePacket);
 454            webRTCWrapper.close();
 455            sendSessionTerminate(Reason.of(e), e.getMessage());
 456            return;
 457        }
 458
 459        final RtpContentMap outgoingContentAdd = this.outgoingContentAdd;
 460        if (outgoingContentAdd == null) {
 461            Log.d(Config.LOGTAG, "received content-accept when we had no outgoing content add");
 462            terminateWithOutOfOrder(jinglePacket);
 463            return;
 464        }
 465        final Set<ContentAddition.Summary> ourSummary = ContentAddition.summary(outgoingContentAdd);
 466        if (ourSummary.equals(ContentAddition.summary(receivedContentAccept))) {
 467            this.outgoingContentAdd = null;
 468            respondOk(jinglePacket);
 469            receiveContentAccept(receivedContentAccept);
 470        } else {
 471            Log.d(Config.LOGTAG, "received content-accept did not match our outgoing content-add");
 472            terminateWithOutOfOrder(jinglePacket);
 473        }
 474    }
 475
 476    private void receiveContentAccept(final RtpContentMap receivedContentAccept) {
 477        final IceUdpTransportInfo.Setup peerDtlsSetup = getPeerDtlsSetup();
 478        final RtpContentMap modifiedContentMap =
 479                getRemoteContentMap().addContent(receivedContentAccept, peerDtlsSetup);
 480
 481        setRemoteContentMap(modifiedContentMap);
 482
 483        final SessionDescription answer = SessionDescription.of(modifiedContentMap, !isInitiator());
 484
 485        final org.webrtc.SessionDescription sdp =
 486                new org.webrtc.SessionDescription(
 487                        org.webrtc.SessionDescription.Type.ANSWER, answer.toString());
 488
 489        try {
 490            this.webRTCWrapper.setRemoteDescription(sdp).get();
 491        } catch (final Exception e) {
 492            final Throwable cause = Throwables.getRootCause(e);
 493            Log.d(
 494                    Config.LOGTAG,
 495                    id.getAccount().getJid().asBareJid()
 496                            + ": unable to set remote description after receiving content-accept",
 497                    cause);
 498            webRTCWrapper.close();
 499            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
 500            return;
 501        }
 502        updateEndUserState();
 503        Log.d(
 504                Config.LOGTAG,
 505                id.getAccount().getJid().asBareJid()
 506                        + ": remote has accepted content-add "
 507                        + ContentAddition.summary(receivedContentAccept));
 508    }
 509
 510    private void receiveContentReject(final JinglePacket jinglePacket) {
 511        final RtpContentMap receivedContentReject;
 512        try {
 513            receivedContentReject = RtpContentMap.of(jinglePacket);
 514        } catch (final RuntimeException e) {
 515            Log.d(
 516                    Config.LOGTAG,
 517                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 518                    Throwables.getRootCause(e));
 519            respondOk(jinglePacket);
 520            this.webRTCWrapper.close();
 521            sendSessionTerminate(Reason.of(e), e.getMessage());
 522            return;
 523        }
 524
 525        final RtpContentMap outgoingContentAdd = this.outgoingContentAdd;
 526        if (outgoingContentAdd == null) {
 527            Log.d(Config.LOGTAG, "received content-reject when we had no outgoing content add");
 528            terminateWithOutOfOrder(jinglePacket);
 529            return;
 530        }
 531        final Set<ContentAddition.Summary> ourSummary = ContentAddition.summary(outgoingContentAdd);
 532        if (ourSummary.equals(ContentAddition.summary(receivedContentReject))) {
 533            this.outgoingContentAdd = null;
 534            respondOk(jinglePacket);
 535            Log.d(Config.LOGTAG,jinglePacket.toString());
 536            receiveContentReject(ourSummary);
 537        } else {
 538            Log.d(Config.LOGTAG, "received content-reject did not match our outgoing content-add");
 539            terminateWithOutOfOrder(jinglePacket);
 540        }
 541    }
 542
 543    private void receiveContentReject(final Set<ContentAddition.Summary> summary) {
 544        try {
 545            this.webRTCWrapper.removeTrack(Media.VIDEO);
 546            final RtpContentMap localContentMap = customRollback();
 547            modifyLocalContentMap(localContentMap);
 548        } catch (final Exception e) {
 549            final Throwable cause = Throwables.getRootCause(e);
 550            Log.d(
 551                    Config.LOGTAG,
 552                    id.getAccount().getJid().asBareJid()
 553                            + ": unable to rollback local description after receiving content-reject",
 554                    cause);
 555            webRTCWrapper.close();
 556            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
 557            return;
 558        }
 559        Log.d(
 560                Config.LOGTAG,
 561                id.getAccount().getJid().asBareJid()
 562                        + ": remote has rejected our content-add "
 563                        + summary);
 564    }
 565
 566    private void receiveContentRemove(final JinglePacket jinglePacket) {
 567        final RtpContentMap receivedContentRemove;
 568        try {
 569            receivedContentRemove = RtpContentMap.of(jinglePacket);
 570            receivedContentRemove.requireContentDescriptions();
 571        } catch (final RuntimeException e) {
 572            Log.d(
 573                    Config.LOGTAG,
 574                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 575                    Throwables.getRootCause(e));
 576            respondOk(jinglePacket);
 577            this.webRTCWrapper.close();
 578            sendSessionTerminate(Reason.of(e), e.getMessage());
 579            return;
 580        }
 581        respondOk(jinglePacket);
 582        receiveContentRemove(receivedContentRemove);
 583    }
 584
 585    private void receiveContentRemove(final RtpContentMap receivedContentRemove) {
 586        final RtpContentMap incomingContentAdd = this.incomingContentAdd;
 587        final Set<ContentAddition.Summary> contentAddSummary =
 588                incomingContentAdd == null
 589                        ? Collections.emptySet()
 590                        : ContentAddition.summary(incomingContentAdd);
 591        final Set<ContentAddition.Summary> removeSummary =
 592                ContentAddition.summary(receivedContentRemove);
 593        if (contentAddSummary.equals(removeSummary)) {
 594            this.incomingContentAdd = null;
 595            updateEndUserState();
 596        } else {
 597            webRTCWrapper.close();
 598            sendSessionTerminate(
 599                    Reason.FAILED_APPLICATION,
 600                    String.format(
 601                            "%s only supports %s as a means to retract a not yet accepted %s",
 602                            BuildConfig.APP_NAME,
 603                            JinglePacket.Action.CONTENT_REMOVE,
 604                            JinglePacket.Action.CONTENT_ACCEPT));
 605        }
 606    }
 607
 608    public synchronized void retractContentAdd() {
 609        final RtpContentMap outgoingContentAdd = this.outgoingContentAdd;
 610        if (outgoingContentAdd == null) {
 611            throw new IllegalStateException("Not outgoing content add");
 612        }
 613        try {
 614            webRTCWrapper.removeTrack(Media.VIDEO);
 615            final RtpContentMap localContentMap = customRollback();
 616            modifyLocalContentMap(localContentMap);
 617        } catch (final Exception e) {
 618            final Throwable cause = Throwables.getRootCause(e);
 619            Log.d(
 620                    Config.LOGTAG,
 621                    id.getAccount().getJid().asBareJid()
 622                            + ": unable to rollback local description after trying to retract content-add",
 623                    cause);
 624            webRTCWrapper.close();
 625            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
 626            return;
 627        }
 628        this.outgoingContentAdd = null;
 629        final JinglePacket retract =
 630                outgoingContentAdd
 631                        .toStub()
 632                        .toJinglePacket(JinglePacket.Action.CONTENT_REMOVE, id.sessionId);
 633        this.send(retract);
 634        Log.d(
 635                Config.LOGTAG,
 636                id.getAccount().getJid()
 637                        + ": retract content-add "
 638                        + ContentAddition.summary(outgoingContentAdd));
 639    }
 640
 641    private RtpContentMap customRollback() throws ExecutionException, InterruptedException {
 642        final SessionDescription sdp = setLocalSessionDescription();
 643        final RtpContentMap localRtpContentMap = RtpContentMap.of(sdp, isInitiator());
 644        final SessionDescription answer = generateFakeResponse(localRtpContentMap);
 645        this.webRTCWrapper
 646                .setRemoteDescription(
 647                        new org.webrtc.SessionDescription(
 648                                org.webrtc.SessionDescription.Type.ANSWER, answer.toString()))
 649                .get();
 650        return localRtpContentMap;
 651    }
 652
 653    private SessionDescription generateFakeResponse(final RtpContentMap localContentMap) {
 654        final RtpContentMap currentRemote = getRemoteContentMap();
 655        final RtpContentMap.Diff diff = currentRemote.diff(localContentMap);
 656        if (diff.isEmpty()) {
 657            throw new IllegalStateException(
 658                    "Unexpected rollback condition. No difference between local and remote");
 659        }
 660        final RtpContentMap patch = localContentMap.toContentModification(diff.added);
 661        if (ImmutableSet.of(Content.Senders.NONE).equals(patch.getSenders())) {
 662            final RtpContentMap nextRemote =
 663                    currentRemote.addContent(
 664                            patch.modifiedSenders(Content.Senders.NONE), getPeerDtlsSetup());
 665            return SessionDescription.of(nextRemote, !isInitiator());
 666        }
 667        throw new IllegalStateException(
 668                "Unexpected rollback condition. Senders were not uniformly none");
 669    }
 670
 671    public synchronized void acceptContentAdd(@NonNull final Set<ContentAddition.Summary> contentAddition) {
 672        final RtpContentMap incomingContentAdd = this.incomingContentAdd;
 673        if (incomingContentAdd == null) {
 674            throw new IllegalStateException("No incoming content add");
 675        }
 676
 677        if (contentAddition.equals(ContentAddition.summary(incomingContentAdd))) {
 678            this.incomingContentAdd = null;
 679            acceptContentAdd(contentAddition, incomingContentAdd);
 680        } else {
 681            throw new IllegalStateException("Accepted content add does not match pending content-add");
 682        }
 683    }
 684
 685    private void acceptContentAdd(@NonNull final Set<ContentAddition.Summary> contentAddition, final RtpContentMap incomingContentAdd) {
 686        final IceUdpTransportInfo.Setup setup = getPeerDtlsSetup();
 687        final RtpContentMap modifiedContentMap = getRemoteContentMap().addContent(incomingContentAdd, setup);
 688        this.setRemoteContentMap(modifiedContentMap);
 689
 690        final SessionDescription offer;
 691        try {
 692            offer = SessionDescription.of(modifiedContentMap, !isInitiator());
 693        } catch (final IllegalArgumentException | NullPointerException e) {
 694            Log.d(Config.LOGTAG, id.getAccount().getJid().asBareJid() + ": unable convert offer from content-add to SDP", e);
 695            webRTCWrapper.close();
 696            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 697            return;
 698        }
 699        this.incomingContentAdd = null;
 700        acceptContentAdd(contentAddition, offer);
 701    }
 702
 703    private void acceptContentAdd(
 704            final Set<ContentAddition.Summary> contentAddition, final SessionDescription offer) {
 705        final org.webrtc.SessionDescription sdp =
 706                new org.webrtc.SessionDescription(
 707                        org.webrtc.SessionDescription.Type.OFFER, offer.toString());
 708        try {
 709            this.webRTCWrapper.setRemoteDescription(sdp).get();
 710
 711            // TODO add tracks for 'media' where contentAddition.senders matches
 712
 713            // TODO if senders.sending(isInitiator())
 714
 715            this.webRTCWrapper.addTrack(Media.VIDEO);
 716
 717            // TODO add additional transceivers for recv only cases
 718
 719            final SessionDescription answer = setLocalSessionDescription();
 720            final RtpContentMap rtpContentMap = RtpContentMap.of(answer, isInitiator());
 721
 722            final RtpContentMap contentAcceptMap =
 723                    rtpContentMap.toContentModification(
 724                            Collections2.transform(contentAddition, ca -> ca.name));
 725            Log.d(
 726                    Config.LOGTAG,
 727                    id.getAccount().getJid().asBareJid()
 728                            + ": sending content-accept "
 729                            + ContentAddition.summary(contentAcceptMap));
 730            modifyLocalContentMap(rtpContentMap);
 731            sendContentAccept(contentAcceptMap);
 732        } catch (final Exception e) {
 733            Log.d(Config.LOGTAG, "unable to accept content add", Throwables.getRootCause(e));
 734            webRTCWrapper.close();
 735            sendSessionTerminate(Reason.FAILED_APPLICATION);
 736        }
 737    }
 738
 739    private void sendContentAccept(final RtpContentMap contentAcceptMap) {
 740        final JinglePacket jinglePacket = contentAcceptMap.toJinglePacket(JinglePacket.Action.CONTENT_ACCEPT, id.sessionId);
 741        send(jinglePacket);
 742    }
 743
 744    public synchronized void rejectContentAdd() {
 745        final RtpContentMap incomingContentAdd = this.incomingContentAdd;
 746        if (incomingContentAdd == null) {
 747            throw new IllegalStateException("No incoming content add");
 748        }
 749        this.incomingContentAdd = null;
 750        updateEndUserState();
 751        rejectContentAdd(incomingContentAdd);
 752    }
 753
 754    private void rejectContentAdd(final RtpContentMap contentMap) {
 755        final JinglePacket jinglePacket =
 756                contentMap
 757                        .toStub()
 758                        .toJinglePacket(JinglePacket.Action.CONTENT_REJECT, id.sessionId);
 759        Log.d(
 760                Config.LOGTAG,
 761                id.getAccount().getJid().asBareJid()
 762                        + ": rejecting content "
 763                        + ContentAddition.summary(contentMap));
 764        send(jinglePacket);
 765    }
 766
 767    private boolean checkForIceRestart(
 768            final JinglePacket jinglePacket, final RtpContentMap rtpContentMap) {
 769        final RtpContentMap existing = getRemoteContentMap();
 770        final Set<IceUdpTransportInfo.Credentials> existingCredentials;
 771        final IceUdpTransportInfo.Credentials newCredentials;
 772        try {
 773            existingCredentials = existing.getCredentials();
 774            newCredentials = rtpContentMap.getDistinctCredentials();
 775        } catch (final IllegalStateException e) {
 776            Log.d(Config.LOGTAG, "unable to gather credentials for comparison", e);
 777            return false;
 778        }
 779        if (existingCredentials.contains(newCredentials)) {
 780            return false;
 781        }
 782        // TODO an alternative approach is to check if we already got an iq result to our
 783        // ICE-restart
 784        // and if that's the case we are seeing an answer.
 785        // This might be more spec compliant but also more error prone potentially
 786        final boolean isOffer = rtpContentMap.emptyCandidates();
 787        final RtpContentMap restartContentMap;
 788        try {
 789            if (isOffer) {
 790                Log.d(Config.LOGTAG, "received offer to restart ICE " + newCredentials);
 791                restartContentMap =
 792                        existing.modifiedCredentials(
 793                                newCredentials, IceUdpTransportInfo.Setup.ACTPASS);
 794            } else {
 795                final IceUdpTransportInfo.Setup setup = getPeerDtlsSetup();
 796                Log.d(
 797                        Config.LOGTAG,
 798                        "received confirmation of ICE restart"
 799                                + newCredentials
 800                                + " peer_setup="
 801                                + setup);
 802                // DTLS setup attribute needs to be rewritten to reflect current peer state
 803                // https://groups.google.com/g/discuss-webrtc/c/DfpIMwvUfeM
 804                restartContentMap = existing.modifiedCredentials(newCredentials, setup);
 805            }
 806            if (applyIceRestart(jinglePacket, restartContentMap, isOffer)) {
 807                return isOffer;
 808            } else {
 809                Log.d(Config.LOGTAG, "ignoring ICE restart. sending tie-break");
 810                respondWithTieBreak(jinglePacket);
 811                return true;
 812            }
 813        } catch (final Exception exception) {
 814            respondOk(jinglePacket);
 815            final Throwable rootCause = Throwables.getRootCause(exception);
 816            if (rootCause instanceof WebRTCWrapper.PeerConnectionNotInitialized) {
 817                // If this happens a termination is already in progress
 818                Log.d(Config.LOGTAG, "ignoring PeerConnectionNotInitialized on ICE restart");
 819                return true;
 820            }
 821            Log.d(Config.LOGTAG, "failure to apply ICE restart", rootCause);
 822            webRTCWrapper.close();
 823            sendSessionTerminate(Reason.ofThrowable(rootCause), rootCause.getMessage());
 824            return true;
 825        }
 826    }
 827
 828    private IceUdpTransportInfo.Setup getPeerDtlsSetup() {
 829        final IceUdpTransportInfo.Setup peerSetup = this.peerDtlsSetup;
 830        if (peerSetup == null || peerSetup == IceUdpTransportInfo.Setup.ACTPASS) {
 831            throw new IllegalStateException("Invalid peer setup");
 832        }
 833        return peerSetup;
 834    }
 835
 836    private void storePeerDtlsSetup(final IceUdpTransportInfo.Setup setup) {
 837        if (setup == null || setup == IceUdpTransportInfo.Setup.ACTPASS) {
 838            throw new IllegalArgumentException("Trying to store invalid peer dtls setup");
 839        }
 840        this.peerDtlsSetup = setup;
 841    }
 842
 843    private boolean applyIceRestart(
 844            final JinglePacket jinglePacket,
 845            final RtpContentMap restartContentMap,
 846            final boolean isOffer)
 847            throws ExecutionException, InterruptedException {
 848        final SessionDescription sessionDescription = SessionDescription.of(restartContentMap, !isInitiator());
 849        final org.webrtc.SessionDescription.Type type =
 850                isOffer
 851                        ? org.webrtc.SessionDescription.Type.OFFER
 852                        : org.webrtc.SessionDescription.Type.ANSWER;
 853        org.webrtc.SessionDescription sdp =
 854                new org.webrtc.SessionDescription(type, sessionDescription.toString());
 855        if (isOffer && webRTCWrapper.getSignalingState() != PeerConnection.SignalingState.STABLE) {
 856            if (isInitiator()) {
 857                // We ignore the offer and respond with tie-break. This will clause the responder
 858                // not to apply the content map
 859                return false;
 860            }
 861        }
 862        webRTCWrapper.setRemoteDescription(sdp).get();
 863        setRemoteContentMap(restartContentMap);
 864        if (isOffer) {
 865            webRTCWrapper.setIsReadyToReceiveIceCandidates(false);
 866            final SessionDescription localSessionDescription = setLocalSessionDescription();
 867            setLocalContentMap(RtpContentMap.of(localSessionDescription, isInitiator()));
 868            // We need to respond OK before sending any candidates
 869            respondOk(jinglePacket);
 870            webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
 871        } else {
 872            storePeerDtlsSetup(restartContentMap.getDtlsSetup());
 873        }
 874        return true;
 875    }
 876
 877    private void processCandidates(
 878            final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> contents) {
 879        for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contents) {
 880            processCandidate(content);
 881        }
 882    }
 883
 884    private void processCandidate(
 885            final Map.Entry<String, RtpContentMap.DescriptionTransport> content) {
 886        final RtpContentMap rtpContentMap = getRemoteContentMap();
 887        final List<String> indices = toIdentificationTags(rtpContentMap);
 888        final String sdpMid = content.getKey(); // aka content name
 889        final IceUdpTransportInfo transport = content.getValue().transport;
 890        final IceUdpTransportInfo.Credentials credentials = transport.getCredentials();
 891
 892        // TODO check that credentials remained the same
 893
 894        for (final IceUdpTransportInfo.Candidate candidate : transport.getCandidates()) {
 895            final String sdp;
 896            try {
 897                sdp = candidate.toSdpAttribute(credentials.ufrag);
 898            } catch (final IllegalArgumentException e) {
 899                Log.d(
 900                        Config.LOGTAG,
 901                        id.account.getJid().asBareJid()
 902                                + ": ignoring invalid ICE candidate "
 903                                + e.getMessage());
 904                continue;
 905            }
 906            final int mLineIndex = indices.indexOf(sdpMid);
 907            if (mLineIndex < 0) {
 908                Log.w(
 909                        Config.LOGTAG,
 910                        "mLineIndex not found for " + sdpMid + ". available indices " + indices);
 911            }
 912            final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
 913            Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
 914            this.webRTCWrapper.addIceCandidate(iceCandidate);
 915        }
 916    }
 917
 918    private RtpContentMap getRemoteContentMap() {
 919        return isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
 920    }
 921
 922    private RtpContentMap getLocalContentMap() {
 923        return isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
 924    }
 925
 926    private List<String> toIdentificationTags(final RtpContentMap rtpContentMap) {
 927        final Group originalGroup = rtpContentMap.group;
 928        final List<String> identificationTags =
 929                originalGroup == null
 930                        ? rtpContentMap.getNames()
 931                        : originalGroup.getIdentificationTags();
 932        if (identificationTags.size() == 0) {
 933            Log.w(
 934                    Config.LOGTAG,
 935                    id.account.getJid().asBareJid()
 936                            + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
 937        }
 938        return identificationTags;
 939    }
 940
 941    private ListenableFuture<RtpContentMap> receiveRtpContentMap(
 942            final JinglePacket jinglePacket, final boolean expectVerification) {
 943        final RtpContentMap receivedContentMap;
 944        try {
 945            receivedContentMap = RtpContentMap.of(jinglePacket);
 946        } catch (final Exception e) {
 947            return Futures.immediateFailedFuture(e);
 948        }
 949        if (receivedContentMap instanceof OmemoVerifiedRtpContentMap) {
 950            final ListenableFuture<AxolotlService.OmemoVerifiedPayload<RtpContentMap>> future =
 951                    id.account
 952                            .getAxolotlService()
 953                            .decrypt((OmemoVerifiedRtpContentMap) receivedContentMap, id.with);
 954            return Futures.transform(
 955                    future,
 956                    omemoVerifiedPayload -> {
 957                        // TODO test if an exception here triggers a correct abort
 958                        omemoVerification.setOrEnsureEqual(omemoVerifiedPayload);
 959                        Log.d(
 960                                Config.LOGTAG,
 961                                id.account.getJid().asBareJid()
 962                                        + ": received verifiable DTLS fingerprint via "
 963                                        + omemoVerification);
 964                        return omemoVerifiedPayload.getPayload();
 965                    },
 966                    MoreExecutors.directExecutor());
 967        } else if (Config.REQUIRE_RTP_VERIFICATION || expectVerification) {
 968            return Futures.immediateFailedFuture(
 969                    new SecurityException("DTLS fingerprint was unexpectedly not verifiable"));
 970        } else {
 971            return Futures.immediateFuture(receivedContentMap);
 972        }
 973    }
 974
 975    private void receiveSessionInitiate(final JinglePacket jinglePacket) {
 976        if (isInitiator()) {
 977            Log.d(
 978                    Config.LOGTAG,
 979                    String.format(
 980                            "%s: received session-initiate even though we were initiating",
 981                            id.account.getJid().asBareJid()));
 982            if (isTerminated()) {
 983                Log.d(
 984                        Config.LOGTAG,
 985                        String.format(
 986                                "%s: got a reason to terminate with out-of-order. but already in state %s",
 987                                id.account.getJid().asBareJid(), getState()));
 988                respondWithOutOfOrder(jinglePacket);
 989            } else {
 990                terminateWithOutOfOrder(jinglePacket);
 991            }
 992            return;
 993        }
 994        final ListenableFuture<RtpContentMap> future = receiveRtpContentMap(jinglePacket, false);
 995        Futures.addCallback(
 996                future,
 997                new FutureCallback<RtpContentMap>() {
 998                    @Override
 999                    public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
1000                        receiveSessionInitiate(jinglePacket, rtpContentMap);
1001                    }
1002
1003                    @Override
1004                    public void onFailure(@NonNull final Throwable throwable) {
1005                        respondOk(jinglePacket);
1006                        sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
1007                    }
1008                },
1009                MoreExecutors.directExecutor());
1010    }
1011
1012    private void receiveSessionInitiate(
1013            final JinglePacket jinglePacket, final RtpContentMap contentMap) {
1014        try {
1015            contentMap.requireContentDescriptions();
1016            contentMap.requireDTLSFingerprint(true);
1017        } catch (final RuntimeException e) {
1018            Log.d(
1019                    Config.LOGTAG,
1020                    id.account.getJid().asBareJid() + ": improperly formatted contents",
1021                    Throwables.getRootCause(e));
1022            respondOk(jinglePacket);
1023            sendSessionTerminate(Reason.of(e), e.getMessage());
1024            return;
1025        }
1026        Log.d(
1027                Config.LOGTAG,
1028                "processing session-init with " + contentMap.contents.size() + " contents");
1029        final State target;
1030        if (this.state == State.PROCEED) {
1031            Preconditions.checkState(
1032                    proposedMedia != null && proposedMedia.size() > 0,
1033                    "proposed media must be set when processing pre-approved session-initiate");
1034            if (!this.proposedMedia.equals(contentMap.getMedia())) {
1035                sendSessionTerminate(
1036                        Reason.SECURITY_ERROR,
1037                        String.format(
1038                                "Your session proposal (Jingle Message Initiation) included media %s but your session-initiate was %s",
1039                                this.proposedMedia, contentMap.getMedia()));
1040                return;
1041            }
1042            target = State.SESSION_INITIALIZED_PRE_APPROVED;
1043        } else {
1044            target = State.SESSION_INITIALIZED;
1045        }
1046        if (transition(target, () -> this.initiatorRtpContentMap = contentMap)) {
1047            respondOk(jinglePacket);
1048            pendingIceCandidates.addAll(contentMap.contents.entrySet());
1049            if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
1050                Log.d(
1051                        Config.LOGTAG,
1052                        id.account.getJid().asBareJid()
1053                                + ": automatically accepting session-initiate");
1054                sendSessionAccept();
1055            } else {
1056                Log.d(
1057                        Config.LOGTAG,
1058                        id.account.getJid().asBareJid()
1059                                + ": received not pre-approved session-initiate. start ringing");
1060                startRinging();
1061            }
1062        } else {
1063            Log.d(
1064                    Config.LOGTAG,
1065                    String.format(
1066                            "%s: received session-initiate while in state %s",
1067                            id.account.getJid().asBareJid(), state));
1068            terminateWithOutOfOrder(jinglePacket);
1069        }
1070    }
1071
1072    private void receiveSessionAccept(final JinglePacket jinglePacket) {
1073        if (!isInitiator()) {
1074            Log.d(
1075                    Config.LOGTAG,
1076                    String.format(
1077                            "%s: received session-accept even though we were responding",
1078                            id.account.getJid().asBareJid()));
1079            terminateWithOutOfOrder(jinglePacket);
1080            return;
1081        }
1082        final ListenableFuture<RtpContentMap> future =
1083                receiveRtpContentMap(jinglePacket, this.omemoVerification.hasFingerprint());
1084        Futures.addCallback(
1085                future,
1086                new FutureCallback<RtpContentMap>() {
1087                    @Override
1088                    public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
1089                        receiveSessionAccept(jinglePacket, rtpContentMap);
1090                    }
1091
1092                    @Override
1093                    public void onFailure(@NonNull final Throwable throwable) {
1094                        respondOk(jinglePacket);
1095                        Log.d(
1096                                Config.LOGTAG,
1097                                id.account.getJid().asBareJid()
1098                                        + ": improperly formatted contents in session-accept",
1099                                throwable);
1100                        webRTCWrapper.close();
1101                        sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
1102                    }
1103                },
1104                MoreExecutors.directExecutor());
1105    }
1106
1107    private void receiveSessionAccept(
1108            final JinglePacket jinglePacket, final RtpContentMap contentMap) {
1109        try {
1110            contentMap.requireContentDescriptions();
1111            contentMap.requireDTLSFingerprint();
1112        } catch (final RuntimeException e) {
1113            respondOk(jinglePacket);
1114            Log.d(
1115                    Config.LOGTAG,
1116                    id.account.getJid().asBareJid()
1117                            + ": improperly formatted contents in session-accept",
1118                    e);
1119            webRTCWrapper.close();
1120            sendSessionTerminate(Reason.of(e), e.getMessage());
1121            return;
1122        }
1123        final Set<Media> initiatorMedia = this.initiatorRtpContentMap.getMedia();
1124        if (!initiatorMedia.equals(contentMap.getMedia())) {
1125            sendSessionTerminate(
1126                    Reason.SECURITY_ERROR,
1127                    String.format(
1128                            "Your session-included included media %s but our session-initiate was %s",
1129                            this.proposedMedia, contentMap.getMedia()));
1130            return;
1131        }
1132        Log.d(
1133                Config.LOGTAG,
1134                "processing session-accept with " + contentMap.contents.size() + " contents");
1135        if (transition(State.SESSION_ACCEPTED)) {
1136            respondOk(jinglePacket);
1137            receiveSessionAccept(contentMap);
1138        } else {
1139            Log.d(
1140                    Config.LOGTAG,
1141                    String.format(
1142                            "%s: received session-accept while in state %s",
1143                            id.account.getJid().asBareJid(), state));
1144            respondOk(jinglePacket);
1145        }
1146    }
1147
1148    private void receiveSessionAccept(final RtpContentMap contentMap) {
1149        this.responderRtpContentMap = contentMap;
1150        this.storePeerDtlsSetup(contentMap.getDtlsSetup());
1151        final SessionDescription sessionDescription;
1152        try {
1153            sessionDescription = SessionDescription.of(contentMap, false);
1154        } catch (final IllegalArgumentException | NullPointerException e) {
1155            Log.d(
1156                    Config.LOGTAG,
1157                    id.account.getJid().asBareJid()
1158                            + ": unable convert offer from session-accept to SDP",
1159                    e);
1160            webRTCWrapper.close();
1161            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
1162            return;
1163        }
1164        final org.webrtc.SessionDescription answer =
1165                new org.webrtc.SessionDescription(
1166                        org.webrtc.SessionDescription.Type.ANSWER, sessionDescription.toString());
1167        try {
1168            this.webRTCWrapper.setRemoteDescription(answer).get();
1169        } catch (final Exception e) {
1170            Log.d(
1171                    Config.LOGTAG,
1172                    id.account.getJid().asBareJid()
1173                            + ": unable to set remote description after receiving session-accept",
1174                    Throwables.getRootCause(e));
1175            webRTCWrapper.close();
1176            sendSessionTerminate(
1177                    Reason.FAILED_APPLICATION, Throwables.getRootCause(e).getMessage());
1178            return;
1179        }
1180        processCandidates(contentMap.contents.entrySet());
1181    }
1182
1183    private void sendSessionAccept() {
1184        final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
1185        if (rtpContentMap == null) {
1186            throw new IllegalStateException("initiator RTP Content Map has not been set");
1187        }
1188        final SessionDescription offer;
1189        try {
1190            offer = SessionDescription.of(rtpContentMap, true);
1191        } catch (final IllegalArgumentException | NullPointerException e) {
1192            Log.d(
1193                    Config.LOGTAG,
1194                    id.account.getJid().asBareJid()
1195                            + ": unable convert offer from session-initiate to SDP",
1196                    e);
1197            webRTCWrapper.close();
1198            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
1199            return;
1200        }
1201        sendSessionAccept(rtpContentMap.getMedia(), offer);
1202    }
1203
1204    private void sendSessionAccept(final Set<Media> media, final SessionDescription offer) {
1205        discoverIceServers(iceServers -> sendSessionAccept(media, offer, iceServers));
1206    }
1207
1208    private synchronized void sendSessionAccept(
1209            final Set<Media> media,
1210            final SessionDescription offer,
1211            final List<PeerConnection.IceServer> iceServers) {
1212        if (isTerminated()) {
1213            Log.w(
1214                    Config.LOGTAG,
1215                    id.account.getJid().asBareJid()
1216                            + ": ICE servers got discovered when session was already terminated. nothing to do.");
1217            return;
1218        }
1219        try {
1220            setupWebRTC(media, iceServers);
1221        } catch (final WebRTCWrapper.InitializationException e) {
1222            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
1223            webRTCWrapper.close();
1224            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
1225            return;
1226        }
1227        final org.webrtc.SessionDescription sdp =
1228                new org.webrtc.SessionDescription(
1229                        org.webrtc.SessionDescription.Type.OFFER, offer.toString());
1230        try {
1231            this.webRTCWrapper.setRemoteDescription(sdp).get();
1232            addIceCandidatesFromBlackLog();
1233            org.webrtc.SessionDescription webRTCSessionDescription =
1234                    this.webRTCWrapper.setLocalDescription().get();
1235            prepareSessionAccept(webRTCSessionDescription);
1236        } catch (final Exception e) {
1237            failureToAcceptSession(e);
1238        }
1239    }
1240
1241    private void failureToAcceptSession(final Throwable throwable) {
1242        if (isTerminated()) {
1243            return;
1244        }
1245        final Throwable rootCause = Throwables.getRootCause(throwable);
1246        Log.d(Config.LOGTAG, "unable to send session accept", rootCause);
1247        webRTCWrapper.close();
1248        sendSessionTerminate(Reason.ofThrowable(rootCause), rootCause.getMessage());
1249    }
1250
1251    private void addIceCandidatesFromBlackLog() {
1252        Map.Entry<String, RtpContentMap.DescriptionTransport> foo;
1253        while ((foo = this.pendingIceCandidates.poll()) != null) {
1254            processCandidate(foo);
1255            Log.d(
1256                    Config.LOGTAG,
1257                    id.account.getJid().asBareJid() + ": added candidate from back log");
1258        }
1259    }
1260
1261    private void prepareSessionAccept(
1262            final org.webrtc.SessionDescription webRTCSessionDescription) {
1263        final SessionDescription sessionDescription =
1264                SessionDescription.parse(webRTCSessionDescription.description);
1265        final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription, false);
1266        this.responderRtpContentMap = respondingRtpContentMap;
1267        storePeerDtlsSetup(respondingRtpContentMap.getDtlsSetup().flip());
1268        final ListenableFuture<RtpContentMap> outgoingContentMapFuture =
1269                prepareOutgoingContentMap(respondingRtpContentMap);
1270        Futures.addCallback(
1271                outgoingContentMapFuture,
1272                new FutureCallback<RtpContentMap>() {
1273                    @Override
1274                    public void onSuccess(final RtpContentMap outgoingContentMap) {
1275                        sendSessionAccept(outgoingContentMap);
1276                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
1277                    }
1278
1279                    @Override
1280                    public void onFailure(@NonNull Throwable throwable) {
1281                        failureToAcceptSession(throwable);
1282                    }
1283                },
1284                MoreExecutors.directExecutor());
1285    }
1286
1287    private void sendSessionAccept(final RtpContentMap rtpContentMap) {
1288        if (isTerminated()) {
1289            Log.w(
1290                    Config.LOGTAG,
1291                    id.account.getJid().asBareJid()
1292                            + ": preparing session accept was too slow. already terminated. nothing to do.");
1293            return;
1294        }
1295        transitionOrThrow(State.SESSION_ACCEPTED);
1296        final JinglePacket sessionAccept =
1297                rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
1298        send(sessionAccept);
1299    }
1300
1301    private ListenableFuture<RtpContentMap> prepareOutgoingContentMap(
1302            final RtpContentMap rtpContentMap) {
1303        if (this.omemoVerification.hasDeviceId()) {
1304            ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>>
1305                    verifiedPayloadFuture =
1306                            id.account
1307                                    .getAxolotlService()
1308                                    .encrypt(
1309                                            rtpContentMap,
1310                                            id.with,
1311                                            omemoVerification.getDeviceId());
1312            return Futures.transform(
1313                    verifiedPayloadFuture,
1314                    verifiedPayload -> {
1315                        omemoVerification.setOrEnsureEqual(verifiedPayload);
1316                        return verifiedPayload.getPayload();
1317                    },
1318                    MoreExecutors.directExecutor());
1319        } else {
1320            return Futures.immediateFuture(rtpContentMap);
1321        }
1322    }
1323
1324    synchronized void deliveryMessage(
1325            final Jid from,
1326            final Element message,
1327            final String serverMessageId,
1328            final long timestamp) {
1329        Log.d(
1330                Config.LOGTAG,
1331                id.account.getJid().asBareJid()
1332                        + ": delivered message to JingleRtpConnection "
1333                        + message);
1334        switch (message.getName()) {
1335            case "propose":
1336                receivePropose(from, Propose.upgrade(message), serverMessageId, timestamp);
1337                break;
1338            case "proceed":
1339                receiveProceed(from, Proceed.upgrade(message), serverMessageId, timestamp);
1340                break;
1341            case "retract":
1342                receiveRetract(from, serverMessageId, timestamp);
1343                break;
1344            case "reject":
1345                receiveReject(from, serverMessageId, timestamp);
1346                break;
1347            case "accept":
1348                receiveAccept(from, serverMessageId, timestamp);
1349                break;
1350            default:
1351                break;
1352        }
1353    }
1354
1355    void deliverFailedProceed(final String message) {
1356        Log.d(
1357                Config.LOGTAG,
1358                id.account.getJid().asBareJid() + ": receive message error for proceed message ("+Strings.nullToEmpty(message)+")");
1359        if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
1360            webRTCWrapper.close();
1361            Log.d(
1362                    Config.LOGTAG,
1363                    id.account.getJid().asBareJid() + ": transitioned into connectivity error");
1364            this.finish();
1365        }
1366    }
1367
1368    private void receiveAccept(final Jid from, final String serverMsgId, final long timestamp) {
1369        final boolean originatedFromMyself =
1370                from.asBareJid().equals(id.account.getJid().asBareJid());
1371        if (originatedFromMyself) {
1372            if (transition(State.ACCEPTED)) {
1373                acceptedOnOtherDevice(serverMsgId, timestamp);
1374            } else {
1375                Log.d(
1376                        Config.LOGTAG,
1377                        id.account.getJid().asBareJid()
1378                                + ": unable to transition to accept because already in state="
1379                                + this.state);
1380            }
1381        } else {
1382            Log.d(
1383                    Config.LOGTAG,
1384                    id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
1385        }
1386    }
1387
1388    private void acceptedOnOtherDevice(final String serverMsgId, final long timestamp) {
1389        if (serverMsgId != null) {
1390            this.message.setServerMsgId(serverMsgId);
1391        }
1392        this.message.setTime(timestamp);
1393        this.message.setCarbon(true); // indicate that call was accepted on other device
1394        this.writeLogMessageSuccess(0);
1395        this.xmppConnectionService
1396                .getNotificationService()
1397                .cancelIncomingCallNotification();
1398        this.finish();
1399    }
1400
1401    private void receiveReject(final Jid from, final String serverMsgId, final long timestamp) {
1402        final boolean originatedFromMyself =
1403                from.asBareJid().equals(id.account.getJid().asBareJid());
1404        // reject from another one of my clients
1405        if (originatedFromMyself) {
1406            receiveRejectFromMyself(serverMsgId, timestamp);
1407        } else if (isInitiator()) {
1408            if (from.equals(id.with)) {
1409                receiveRejectFromResponder();
1410            } else {
1411                Log.d(
1412                        Config.LOGTAG,
1413                        id.account.getJid()
1414                                + ": ignoring reject from "
1415                                + from
1416                                + " for session with "
1417                                + id.with);
1418            }
1419        } else {
1420            Log.d(
1421                    Config.LOGTAG,
1422                    id.account.getJid()
1423                            + ": ignoring reject from "
1424                            + from
1425                            + " for session with "
1426                            + id.with);
1427        }
1428    }
1429
1430    private void receiveRejectFromMyself(String serverMsgId, long timestamp) {
1431        if (transition(State.REJECTED)) {
1432            this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1433            this.finish();
1434            if (serverMsgId != null) {
1435                this.message.setServerMsgId(serverMsgId);
1436            }
1437            this.message.setTime(timestamp);
1438            this.message.setCarbon(true); // indicate that call was rejected on other device
1439            writeLogMessageMissed();
1440        } else {
1441            Log.d(
1442                    Config.LOGTAG,
1443                    "not able to transition into REJECTED because already in " + this.state);
1444        }
1445    }
1446
1447    private void receiveRejectFromResponder() {
1448        if (isInState(State.PROCEED)) {
1449            Log.d(
1450                    Config.LOGTAG,
1451                    id.account.getJid()
1452                            + ": received reject while still in proceed. callee reconsidered");
1453            closeTransitionLogFinish(State.REJECTED_RACED);
1454            return;
1455        }
1456        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED)) {
1457            Log.d(
1458                    Config.LOGTAG,
1459                    id.account.getJid()
1460                            + ": received reject while in SESSION_INITIATED_PRE_APPROVED. callee reconsidered before receiving session-init");
1461            closeTransitionLogFinish(State.TERMINATED_DECLINED_OR_BUSY);
1462            return;
1463        }
1464        Log.d(
1465                Config.LOGTAG,
1466                id.account.getJid()
1467                        + ": ignoring reject from responder because already in state "
1468                        + this.state);
1469    }
1470
1471    private void receivePropose(
1472            final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
1473        final boolean originatedFromMyself =
1474                from.asBareJid().equals(id.account.getJid().asBareJid());
1475        if (originatedFromMyself) {
1476            Log.d(
1477                    Config.LOGTAG,
1478                    id.account.getJid().asBareJid() + ": saw proposal from myself. ignoring");
1479        } else if (transition(
1480                State.PROPOSED,
1481                () -> {
1482                    final Collection<RtpDescription> descriptions =
1483                            Collections2.transform(
1484                                    Collections2.filter(
1485                                            propose.getDescriptions(),
1486                                            d -> d instanceof RtpDescription),
1487                                    input -> (RtpDescription) input);
1488                    final Collection<Media> media =
1489                            Collections2.transform(descriptions, RtpDescription::getMedia);
1490                    Preconditions.checkState(
1491                            !media.contains(Media.UNKNOWN),
1492                            "RTP descriptions contain unknown media");
1493                    Log.d(
1494                            Config.LOGTAG,
1495                            id.account.getJid().asBareJid()
1496                                    + ": received session proposal from "
1497                                    + from
1498                                    + " for "
1499                                    + media);
1500                    this.proposedMedia = Sets.newHashSet(media);
1501                })) {
1502            if (serverMsgId != null) {
1503                this.message.setServerMsgId(serverMsgId);
1504            }
1505            this.message.setTime(timestamp);
1506            startRinging();
1507        } else {
1508            Log.d(
1509                    Config.LOGTAG,
1510                    id.account.getJid()
1511                            + ": ignoring session proposal because already in "
1512                            + state);
1513        }
1514    }
1515
1516    private void startRinging() {
1517        Log.d(
1518                Config.LOGTAG,
1519                id.account.getJid().asBareJid()
1520                        + ": received call from "
1521                        + id.with
1522                        + ". start ringing");
1523        ringingTimeoutFuture =
1524                jingleConnectionManager.schedule(
1525                        this::ringingTimeout, BUSY_TIME_OUT, TimeUnit.SECONDS);
1526        xmppConnectionService.getNotificationService().startRinging(id, getMedia());
1527    }
1528
1529    private synchronized void ringingTimeout() {
1530        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": timeout reached for ringing");
1531        switch (this.state) {
1532            case PROPOSED:
1533                message.markUnread();
1534                rejectCallFromProposed();
1535                break;
1536            case SESSION_INITIALIZED:
1537                message.markUnread();
1538                rejectCallFromSessionInitiate();
1539                break;
1540        }
1541        xmppConnectionService.getNotificationService().pushMissedCallNow(message);
1542    }
1543
1544    private void cancelRingingTimeout() {
1545        final ScheduledFuture<?> future = this.ringingTimeoutFuture;
1546        if (future != null && !future.isCancelled()) {
1547            future.cancel(false);
1548        }
1549    }
1550
1551    private void receiveProceed(
1552            final Jid from, final Proceed proceed, final String serverMsgId, final long timestamp) {
1553        final Set<Media> media =
1554                Preconditions.checkNotNull(
1555                        this.proposedMedia, "Proposed media has to be set before handling proceed");
1556        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
1557        if (from.equals(id.with)) {
1558            if (isInitiator()) {
1559                if (transition(State.PROCEED)) {
1560                    if (serverMsgId != null) {
1561                        this.message.setServerMsgId(serverMsgId);
1562                    }
1563                    this.message.setTime(timestamp);
1564                    final Integer remoteDeviceId = proceed.getDeviceId();
1565                    if (isOmemoEnabled()) {
1566                        this.omemoVerification.setDeviceId(remoteDeviceId);
1567                    } else {
1568                        if (remoteDeviceId != null) {
1569                            Log.d(
1570                                    Config.LOGTAG,
1571                                    id.account.getJid().asBareJid()
1572                                            + ": remote party signaled support for OMEMO verification but we have OMEMO disabled");
1573                        }
1574                        this.omemoVerification.setDeviceId(null);
1575                    }
1576                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
1577                } else {
1578                    Log.d(
1579                            Config.LOGTAG,
1580                            String.format(
1581                                    "%s: ignoring proceed because already in %s",
1582                                    id.account.getJid().asBareJid(), this.state));
1583                }
1584            } else {
1585                Log.d(
1586                        Config.LOGTAG,
1587                        String.format(
1588                                "%s: ignoring proceed because we were not initializing",
1589                                id.account.getJid().asBareJid()));
1590            }
1591        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
1592            if (transition(State.ACCEPTED)) {
1593                Log.d(
1594                        Config.LOGTAG,
1595                        id.account.getJid().asBareJid()
1596                                + ": moved session with "
1597                                + id.with
1598                                + " into state accepted after received carbon copied proceed");
1599                acceptedOnOtherDevice(serverMsgId, timestamp);
1600            }
1601        } else {
1602            Log.d(
1603                    Config.LOGTAG,
1604                    String.format(
1605                            "%s: ignoring proceed from %s. was expected from %s",
1606                            id.account.getJid().asBareJid(), from, id.with));
1607        }
1608    }
1609
1610    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
1611        if (from.equals(id.with)) {
1612            final State target =
1613                    this.state == State.PROCEED ? State.RETRACTED_RACED : State.RETRACTED;
1614            if (transition(target)) {
1615                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1616                xmppConnectionService.getNotificationService().pushMissedCallNow(message);
1617                Log.d(
1618                        Config.LOGTAG,
1619                        id.account.getJid().asBareJid()
1620                                + ": session with "
1621                                + id.with
1622                                + " has been retracted (serverMsgId="
1623                                + serverMsgId
1624                                + ")");
1625                if (serverMsgId != null) {
1626                    this.message.setServerMsgId(serverMsgId);
1627                }
1628                this.message.setTime(timestamp);
1629                if (target == State.RETRACTED) {
1630                    this.message.markUnread();
1631                }
1632                writeLogMessageMissed();
1633                finish();
1634            } else {
1635                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
1636            }
1637        } else {
1638            // TODO parse retract from self
1639            Log.d(
1640                    Config.LOGTAG,
1641                    id.account.getJid().asBareJid()
1642                            + ": received retract from "
1643                            + from
1644                            + ". expected retract from"
1645                            + id.with
1646                            + ". ignoring");
1647        }
1648    }
1649
1650    public void sendSessionInitiate() {
1651        sendSessionInitiate(this.proposedMedia, State.SESSION_INITIALIZED);
1652    }
1653
1654    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
1655        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
1656        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
1657    }
1658
1659    private synchronized void sendSessionInitiate(
1660            final Set<Media> media,
1661            final State targetState,
1662            final List<PeerConnection.IceServer> iceServers) {
1663        if (isTerminated()) {
1664            Log.w(
1665                    Config.LOGTAG,
1666                    id.account.getJid().asBareJid()
1667                            + ": ICE servers got discovered when session was already terminated. nothing to do.");
1668            return;
1669        }
1670        try {
1671            setupWebRTC(media, iceServers);
1672        } catch (final WebRTCWrapper.InitializationException e) {
1673            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
1674            webRTCWrapper.close();
1675            sendRetract(Reason.ofThrowable(e));
1676            return;
1677        }
1678        try {
1679            org.webrtc.SessionDescription webRTCSessionDescription =
1680                    this.webRTCWrapper.setLocalDescription().get();
1681            prepareSessionInitiate(webRTCSessionDescription, targetState);
1682        } catch (final Exception e) {
1683            // TODO sending the error text is worthwhile as well. Especially for FailureToSet
1684            // exceptions
1685            failureToInitiateSession(e, targetState);
1686        }
1687    }
1688
1689    private void failureToInitiateSession(final Throwable throwable, final State targetState) {
1690        if (isTerminated()) {
1691            return;
1692        }
1693        Log.d(
1694                Config.LOGTAG,
1695                id.account.getJid().asBareJid() + ": unable to sendSessionInitiate",
1696                Throwables.getRootCause(throwable));
1697        webRTCWrapper.close();
1698        final Reason reason = Reason.ofThrowable(throwable);
1699        if (isInState(targetState)) {
1700            sendSessionTerminate(reason, throwable.getMessage());
1701        } else {
1702            sendRetract(reason);
1703        }
1704    }
1705
1706    private void sendRetract(final Reason reason) {
1707        // TODO embed reason into retract
1708        sendJingleMessage("retract", id.with.asBareJid());
1709        transitionOrThrow(reasonToState(reason));
1710        this.finish();
1711    }
1712
1713    private void prepareSessionInitiate(
1714            final org.webrtc.SessionDescription webRTCSessionDescription, final State targetState) {
1715        final SessionDescription sessionDescription =
1716                SessionDescription.parse(webRTCSessionDescription.description);
1717        final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription, true);
1718        this.initiatorRtpContentMap = rtpContentMap;
1719        final ListenableFuture<RtpContentMap> outgoingContentMapFuture =
1720                encryptSessionInitiate(rtpContentMap);
1721        Futures.addCallback(
1722                outgoingContentMapFuture,
1723                new FutureCallback<RtpContentMap>() {
1724                    @Override
1725                    public void onSuccess(final RtpContentMap outgoingContentMap) {
1726                        sendSessionInitiate(outgoingContentMap, targetState);
1727                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
1728                    }
1729
1730                    @Override
1731                    public void onFailure(@NonNull final Throwable throwable) {
1732                        failureToInitiateSession(throwable, targetState);
1733                    }
1734                },
1735                MoreExecutors.directExecutor());
1736    }
1737
1738    private void sendSessionInitiate(final RtpContentMap rtpContentMap, final State targetState) {
1739        if (isTerminated()) {
1740            Log.w(
1741                    Config.LOGTAG,
1742                    id.account.getJid().asBareJid()
1743                            + ": preparing session was too slow. already terminated. nothing to do.");
1744            return;
1745        }
1746        this.transitionOrThrow(targetState);
1747        final JinglePacket sessionInitiate =
1748                rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
1749        send(sessionInitiate);
1750    }
1751
1752    private ListenableFuture<RtpContentMap> encryptSessionInitiate(
1753            final RtpContentMap rtpContentMap) {
1754        if (this.omemoVerification.hasDeviceId()) {
1755            final ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>>
1756                    verifiedPayloadFuture =
1757                            id.account
1758                                    .getAxolotlService()
1759                                    .encrypt(
1760                                            rtpContentMap,
1761                                            id.with,
1762                                            omemoVerification.getDeviceId());
1763            final ListenableFuture<RtpContentMap> future =
1764                    Futures.transform(
1765                            verifiedPayloadFuture,
1766                            verifiedPayload -> {
1767                                omemoVerification.setSessionFingerprint(
1768                                        verifiedPayload.getFingerprint());
1769                                return verifiedPayload.getPayload();
1770                            },
1771                            MoreExecutors.directExecutor());
1772            if (Config.REQUIRE_RTP_VERIFICATION) {
1773                return future;
1774            }
1775            return Futures.catching(
1776                    future,
1777                    CryptoFailedException.class,
1778                    e -> {
1779                        Log.w(
1780                                Config.LOGTAG,
1781                                id.account.getJid().asBareJid()
1782                                        + ": unable to use OMEMO DTLS verification on outgoing session initiate. falling back",
1783                                e);
1784                        return rtpContentMap;
1785                    },
1786                    MoreExecutors.directExecutor());
1787        } else {
1788            return Futures.immediateFuture(rtpContentMap);
1789        }
1790    }
1791
1792    private void sendSessionTerminate(final Reason reason) {
1793        sendSessionTerminate(reason, null);
1794    }
1795
1796    private void sendSessionTerminate(final Reason reason, final String text) {
1797        final State previous = this.state;
1798        final State target = reasonToState(reason);
1799        transitionOrThrow(target);
1800        if (previous != State.NULL) {
1801            writeLogMessage(target);
1802        }
1803        final JinglePacket jinglePacket =
1804                new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
1805        jinglePacket.setReason(reason, text);
1806        Log.d(Config.LOGTAG, jinglePacket.toString());
1807        send(jinglePacket);
1808        finish();
1809    }
1810
1811    private void sendTransportInfo(
1812            final String contentName, IceUdpTransportInfo.Candidate candidate) {
1813        final RtpContentMap transportInfo;
1814        try {
1815            final RtpContentMap rtpContentMap =
1816                    isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
1817            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
1818        } catch (final Exception e) {
1819            Log.d(
1820                    Config.LOGTAG,
1821                    id.account.getJid().asBareJid()
1822                            + ": unable to prepare transport-info from candidate for content="
1823                            + contentName);
1824            return;
1825        }
1826        final JinglePacket jinglePacket =
1827                transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
1828        send(jinglePacket);
1829    }
1830
1831    private void send(final JinglePacket jinglePacket) {
1832        jinglePacket.setTo(id.with);
1833        xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
1834    }
1835
1836    private synchronized void handleIqResponse(final Account account, final IqPacket response) {
1837        if (response.getType() == IqPacket.TYPE.ERROR) {
1838            handleIqErrorResponse(response);
1839            return;
1840        }
1841        if (response.getType() == IqPacket.TYPE.TIMEOUT) {
1842            handleIqTimeoutResponse(response);
1843        }
1844    }
1845
1846    private void handleIqErrorResponse(final IqPacket response) {
1847        Preconditions.checkArgument(response.getType() == IqPacket.TYPE.ERROR);
1848        final String errorCondition = response.getErrorCondition();
1849        Log.d(
1850                Config.LOGTAG,
1851                id.account.getJid().asBareJid()
1852                        + ": received IQ-error from "
1853                        + response.getFrom()
1854                        + " in RTP session. "
1855                        + errorCondition);
1856        if (isTerminated()) {
1857            Log.i(
1858                    Config.LOGTAG,
1859                    id.account.getJid().asBareJid()
1860                            + ": ignoring error because session was already terminated");
1861            return;
1862        }
1863        this.webRTCWrapper.close();
1864        final State target;
1865        if (Arrays.asList(
1866                        "service-unavailable",
1867                        "recipient-unavailable",
1868                        "remote-server-not-found",
1869                        "remote-server-timeout")
1870                .contains(errorCondition)) {
1871            target = State.TERMINATED_CONNECTIVITY_ERROR;
1872        } else {
1873            target = State.TERMINATED_APPLICATION_FAILURE;
1874        }
1875        transitionOrThrow(target);
1876        this.finish();
1877    }
1878
1879    private void handleIqTimeoutResponse(final IqPacket response) {
1880        Preconditions.checkArgument(response.getType() == IqPacket.TYPE.TIMEOUT);
1881        Log.d(
1882                Config.LOGTAG,
1883                id.account.getJid().asBareJid()
1884                        + ": received IQ timeout in RTP session with "
1885                        + id.with
1886                        + ". terminating with connectivity error");
1887        if (isTerminated()) {
1888            Log.i(
1889                    Config.LOGTAG,
1890                    id.account.getJid().asBareJid()
1891                            + ": ignoring error because session was already terminated");
1892            return;
1893        }
1894        this.webRTCWrapper.close();
1895        transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
1896        this.finish();
1897    }
1898
1899    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
1900        Log.d(
1901                Config.LOGTAG,
1902                id.account.getJid().asBareJid() + ": terminating session with out-of-order");
1903        this.webRTCWrapper.close();
1904        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
1905        respondWithOutOfOrder(jinglePacket);
1906        this.finish();
1907    }
1908
1909    private void respondWithTieBreak(final JinglePacket jinglePacket) {
1910        respondWithJingleError(jinglePacket, "tie-break", "conflict", "cancel");
1911    }
1912
1913    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
1914        respondWithJingleError(jinglePacket, "out-of-order", "unexpected-request", "wait");
1915    }
1916
1917    void respondWithJingleError(
1918            final IqPacket original,
1919            String jingleCondition,
1920            String condition,
1921            String conditionType) {
1922        jingleConnectionManager.respondWithJingleError(
1923                id.account, original, jingleCondition, condition, conditionType);
1924    }
1925
1926    private void respondOk(final JinglePacket jinglePacket) {
1927        xmppConnectionService.sendIqPacket(
1928                id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
1929    }
1930
1931    public RtpEndUserState getEndUserState() {
1932        switch (this.state) {
1933            case NULL:
1934            case PROPOSED:
1935            case SESSION_INITIALIZED:
1936                if (isInitiator()) {
1937                    return RtpEndUserState.RINGING;
1938                } else {
1939                    return RtpEndUserState.INCOMING_CALL;
1940                }
1941            case PROCEED:
1942                if (isInitiator()) {
1943                    return RtpEndUserState.RINGING;
1944                } else {
1945                    return RtpEndUserState.ACCEPTING_CALL;
1946                }
1947            case SESSION_INITIALIZED_PRE_APPROVED:
1948                if (isInitiator()) {
1949                    return RtpEndUserState.RINGING;
1950                } else {
1951                    return RtpEndUserState.CONNECTING;
1952                }
1953            case SESSION_ACCEPTED:
1954                final ContentAddition ca = getPendingContentAddition();
1955                if (ca != null && ca.direction == ContentAddition.Direction.INCOMING) {
1956                    return RtpEndUserState.INCOMING_CONTENT_ADD;
1957                }
1958                return getPeerConnectionStateAsEndUserState();
1959            case REJECTED:
1960            case REJECTED_RACED:
1961            case TERMINATED_DECLINED_OR_BUSY:
1962                if (isInitiator()) {
1963                    return RtpEndUserState.DECLINED_OR_BUSY;
1964                } else {
1965                    return RtpEndUserState.ENDED;
1966                }
1967            case TERMINATED_SUCCESS:
1968            case ACCEPTED:
1969            case RETRACTED:
1970            case TERMINATED_CANCEL_OR_TIMEOUT:
1971                return RtpEndUserState.ENDED;
1972            case RETRACTED_RACED:
1973                if (isInitiator()) {
1974                    return RtpEndUserState.ENDED;
1975                } else {
1976                    return RtpEndUserState.RETRACTED;
1977                }
1978            case TERMINATED_CONNECTIVITY_ERROR:
1979                return zeroDuration()
1980                        ? RtpEndUserState.CONNECTIVITY_ERROR
1981                        : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
1982            case TERMINATED_APPLICATION_FAILURE:
1983                return RtpEndUserState.APPLICATION_ERROR;
1984            case TERMINATED_SECURITY_ERROR:
1985                return RtpEndUserState.SECURITY_ERROR;
1986        }
1987        throw new IllegalStateException(
1988                String.format("%s has no equivalent EndUserState", this.state));
1989    }
1990
1991    private RtpEndUserState getPeerConnectionStateAsEndUserState() {
1992        final PeerConnection.PeerConnectionState state;
1993        try {
1994            state = webRTCWrapper.getState();
1995        } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
1996            // We usually close the WebRTCWrapper *before* transitioning so we might still
1997            // be in SESSION_ACCEPTED even though the peerConnection has been torn down
1998            return RtpEndUserState.ENDING_CALL;
1999        }
2000        switch (state) {
2001            case CONNECTED:
2002                return RtpEndUserState.CONNECTED;
2003            case NEW:
2004            case CONNECTING:
2005                return RtpEndUserState.CONNECTING;
2006            case CLOSED:
2007                return RtpEndUserState.ENDING_CALL;
2008            default:
2009                return zeroDuration()
2010                        ? RtpEndUserState.CONNECTIVITY_ERROR
2011                        : RtpEndUserState.RECONNECTING;
2012        }
2013    }
2014
2015    public ContentAddition getPendingContentAddition() {
2016        final RtpContentMap in = this.incomingContentAdd;
2017        final RtpContentMap out = this.outgoingContentAdd;
2018        if (out != null) {
2019            return ContentAddition.of(ContentAddition.Direction.OUTGOING, out);
2020        } else if (in != null) {
2021            return ContentAddition.of(ContentAddition.Direction.INCOMING, in);
2022        } else {
2023            return null;
2024        }
2025    }
2026
2027    public Set<Media> getMedia() {
2028        final State current = getState();
2029        if (current == State.NULL) {
2030            if (isInitiator()) {
2031                return Preconditions.checkNotNull(
2032                        this.proposedMedia, "RTP connection has not been initialized properly");
2033            }
2034            throw new IllegalStateException("RTP connection has not been initialized yet");
2035        }
2036        if (Arrays.asList(State.PROPOSED, State.PROCEED).contains(current)) {
2037            return Preconditions.checkNotNull(
2038                    this.proposedMedia, "RTP connection has not been initialized properly");
2039        }
2040        final RtpContentMap localContentMap = getLocalContentMap();
2041        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
2042        if (localContentMap != null) {
2043            return localContentMap.getMedia();
2044        } else if (initiatorContentMap != null) {
2045            return initiatorContentMap.getMedia();
2046        } else if (isTerminated()) {
2047            return Collections.emptySet(); //we might fail before we ever got a chance to set media
2048        } else {
2049            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
2050        }
2051    }
2052
2053    public boolean isVerified() {
2054        final String fingerprint = this.omemoVerification.getFingerprint();
2055        if (fingerprint == null) {
2056            return false;
2057        }
2058        final FingerprintStatus status =
2059                id.account.getAxolotlService().getFingerprintTrust(fingerprint);
2060        return status != null && status.isVerified();
2061    }
2062
2063    public boolean addMedia(final Media media) {
2064        final Set<Media> currentMedia = getMedia();
2065        if (currentMedia.contains(media)) {
2066            throw new IllegalStateException(String.format("%s has already been proposed", media));
2067        }
2068        // TODO add state protection - can only add while ACCEPTED or so
2069        Log.d(Config.LOGTAG,"adding media: "+media);
2070        return webRTCWrapper.addTrack(media);
2071    }
2072
2073    public synchronized void acceptCall() {
2074        switch (this.state) {
2075            case PROPOSED:
2076                cancelRingingTimeout();
2077                acceptCallFromProposed();
2078                break;
2079            case SESSION_INITIALIZED:
2080                cancelRingingTimeout();
2081                acceptCallFromSessionInitialized();
2082                break;
2083            case ACCEPTED:
2084                Log.w(
2085                        Config.LOGTAG,
2086                        id.account.getJid().asBareJid()
2087                                + ": the call has already been accepted  with another client. UI was just lagging behind");
2088                break;
2089            case PROCEED:
2090            case SESSION_ACCEPTED:
2091                Log.w(
2092                        Config.LOGTAG,
2093                        id.account.getJid().asBareJid()
2094                                + ": the call has already been accepted. user probably double tapped the UI");
2095                break;
2096            default:
2097                throw new IllegalStateException("Can not accept call from " + this.state);
2098        }
2099    }
2100
2101    public void notifyPhoneCall() {
2102        Log.d(Config.LOGTAG, "a phone call has just been started. killing jingle rtp connections");
2103        if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(this.state)) {
2104            rejectCall();
2105        } else {
2106            endCall();
2107        }
2108    }
2109
2110    public synchronized void rejectCall() {
2111        if (isTerminated()) {
2112            Log.w(
2113                    Config.LOGTAG,
2114                    id.account.getJid().asBareJid()
2115                            + ": received rejectCall() when session has already been terminated. nothing to do");
2116            return;
2117        }
2118        switch (this.state) {
2119            case PROPOSED:
2120                rejectCallFromProposed();
2121                break;
2122            case SESSION_INITIALIZED:
2123                rejectCallFromSessionInitiate();
2124                break;
2125            default:
2126                throw new IllegalStateException("Can not reject call from " + this.state);
2127        }
2128    }
2129
2130    public synchronized void endCall() {
2131        if (isTerminated()) {
2132            Log.w(
2133                    Config.LOGTAG,
2134                    id.account.getJid().asBareJid()
2135                            + ": received endCall() when session has already been terminated. nothing to do");
2136            return;
2137        }
2138        if (isInState(State.PROPOSED) && !isInitiator()) {
2139            rejectCallFromProposed();
2140            return;
2141        }
2142        if (isInState(State.PROCEED)) {
2143            if (isInitiator()) {
2144                retractFromProceed();
2145            } else {
2146                rejectCallFromProceed();
2147            }
2148            return;
2149        }
2150        if (isInitiator()
2151                && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
2152            this.webRTCWrapper.close();
2153            sendSessionTerminate(Reason.CANCEL);
2154            return;
2155        }
2156        if (isInState(State.SESSION_INITIALIZED)) {
2157            rejectCallFromSessionInitiate();
2158            return;
2159        }
2160        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
2161            this.webRTCWrapper.close();
2162            sendSessionTerminate(Reason.SUCCESS);
2163            return;
2164        }
2165        if (isInState(
2166                State.TERMINATED_APPLICATION_FAILURE,
2167                State.TERMINATED_CONNECTIVITY_ERROR,
2168                State.TERMINATED_DECLINED_OR_BUSY)) {
2169            Log.d(
2170                    Config.LOGTAG,
2171                    "ignoring request to end call because already in state " + this.state);
2172            return;
2173        }
2174        throw new IllegalStateException(
2175                "called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
2176    }
2177
2178    private void retractFromProceed() {
2179        Log.d(Config.LOGTAG, "retract from proceed");
2180        this.sendJingleMessage("retract");
2181        closeTransitionLogFinish(State.RETRACTED_RACED);
2182    }
2183
2184    private void closeTransitionLogFinish(final State state) {
2185        this.webRTCWrapper.close();
2186        transitionOrThrow(state);
2187        writeLogMessage(state);
2188        finish();
2189    }
2190
2191    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
2192        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
2193        this.webRTCWrapper.setup(this.xmppConnectionService, AppRTCAudioManager.SpeakerPhonePreference.of(media));
2194        this.webRTCWrapper.initializePeerConnection(media, iceServers);
2195    }
2196
2197    private void acceptCallFromProposed() {
2198        transitionOrThrow(State.PROCEED);
2199        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2200        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
2201        this.sendJingleMessage("proceed");
2202    }
2203
2204    private void rejectCallFromProposed() {
2205        transitionOrThrow(State.REJECTED);
2206        writeLogMessageMissed();
2207        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2208        this.sendJingleMessage("reject");
2209        finish();
2210    }
2211
2212    private void rejectCallFromProceed() {
2213        this.sendJingleMessage("reject");
2214        closeTransitionLogFinish(State.REJECTED_RACED);
2215    }
2216
2217    private void rejectCallFromSessionInitiate() {
2218        webRTCWrapper.close();
2219        sendSessionTerminate(Reason.DECLINE);
2220        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2221    }
2222
2223    private void sendJingleMessage(final String action) {
2224        sendJingleMessage(action, id.with);
2225    }
2226
2227    private void sendJingleMessage(final String action, final Jid to) {
2228        final MessagePacket messagePacket = new MessagePacket();
2229        messagePacket.setType(MessagePacket.TYPE_CHAT); // we want to carbon copy those
2230        messagePacket.setTo(to);
2231        final Element intent =
2232                messagePacket
2233                        .addChild(action, Namespace.JINGLE_MESSAGE)
2234                        .setAttribute("id", id.sessionId);
2235        if ("proceed".equals(action)) {
2236            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
2237            if (isOmemoEnabled()) {
2238                final int deviceId = id.account.getAxolotlService().getOwnDeviceId();
2239                final Element device =
2240                        intent.addChild("device", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
2241                device.setAttribute("id", deviceId);
2242            }
2243        }
2244        messagePacket.addChild("store", "urn:xmpp:hints");
2245        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
2246    }
2247
2248    private boolean isOmemoEnabled() {
2249        final Conversational conversational = message.getConversation();
2250        if (conversational instanceof Conversation) {
2251            return ((Conversation) conversational).getNextEncryption()
2252                    == Message.ENCRYPTION_AXOLOTL;
2253        }
2254        return false;
2255    }
2256
2257    private void acceptCallFromSessionInitialized() {
2258        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2259        sendSessionAccept();
2260    }
2261
2262    private synchronized boolean isInState(State... state) {
2263        return Arrays.asList(state).contains(this.state);
2264    }
2265
2266    private boolean transition(final State target) {
2267        return transition(target, null);
2268    }
2269
2270    private synchronized boolean transition(final State target, final Runnable runnable) {
2271        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
2272        if (validTransitions != null && validTransitions.contains(target)) {
2273            this.state = target;
2274            if (runnable != null) {
2275                runnable.run();
2276            }
2277            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
2278            updateEndUserState();
2279            updateOngoingCallNotification();
2280            return true;
2281        } else {
2282            return false;
2283        }
2284    }
2285
2286    void transitionOrThrow(final State target) {
2287        if (!transition(target)) {
2288            throw new IllegalStateException(
2289                    String.format("Unable to transition from %s to %s", this.state, target));
2290        }
2291    }
2292
2293    @Override
2294    public void onIceCandidate(final IceCandidate iceCandidate) {
2295        final RtpContentMap rtpContentMap =
2296                isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
2297        final IceUdpTransportInfo.Credentials credentials;
2298        try {
2299            credentials = rtpContentMap.getCredentials(iceCandidate.sdpMid);
2300        } catch (final IllegalArgumentException e) {
2301            Log.d(Config.LOGTAG, "ignoring (not sending) candidate: " + iceCandidate, e);
2302            return;
2303        }
2304        final String uFrag = credentials.ufrag;
2305        final IceUdpTransportInfo.Candidate candidate =
2306                IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp, uFrag);
2307        if (candidate == null) {
2308            Log.d(Config.LOGTAG, "ignoring (not sending) candidate: " + iceCandidate);
2309            return;
2310        }
2311        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate);
2312        sendTransportInfo(iceCandidate.sdpMid, candidate);
2313    }
2314
2315    @Override
2316    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
2317        Log.d(
2318                Config.LOGTAG,
2319                id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
2320        this.stateHistory.add(newState);
2321        if (newState == PeerConnection.PeerConnectionState.CONNECTED) {
2322            this.sessionDuration.start();
2323            updateOngoingCallNotification();
2324        } else if (this.sessionDuration.isRunning()) {
2325            this.sessionDuration.stop();
2326            updateOngoingCallNotification();
2327        }
2328
2329        final boolean neverConnected =
2330                !this.stateHistory.contains(PeerConnection.PeerConnectionState.CONNECTED);
2331
2332        if (newState == PeerConnection.PeerConnectionState.FAILED) {
2333            if (neverConnected) {
2334                if (isTerminated()) {
2335                    Log.d(
2336                            Config.LOGTAG,
2337                            id.account.getJid().asBareJid()
2338                                    + ": not sending session-terminate after connectivity error because session is already in state "
2339                                    + this.state);
2340                    return;
2341                }
2342                webRTCWrapper.execute(this::closeWebRTCSessionAfterFailedConnection);
2343                return;
2344            } else {
2345                this.restartIce();
2346            }
2347        }
2348        updateEndUserState();
2349    }
2350
2351    private void restartIce() {
2352        this.stateHistory.clear();
2353        this.webRTCWrapper.restartIce();
2354    }
2355
2356    @Override
2357    public void onRenegotiationNeeded() {
2358        this.webRTCWrapper.execute(this::renegotiate);
2359    }
2360
2361    private void renegotiate() {
2362        final SessionDescription sessionDescription;
2363        try {
2364            sessionDescription = setLocalSessionDescription();
2365        } catch (final Exception e) {
2366            final Throwable cause = Throwables.getRootCause(e);
2367            Log.d(Config.LOGTAG, "failed to renegotiate", cause);
2368            webRTCWrapper.close();
2369            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
2370            return;
2371        }
2372        final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription, isInitiator());
2373        final RtpContentMap currentContentMap = getLocalContentMap();
2374        final boolean iceRestart = currentContentMap.iceRestart(rtpContentMap);
2375        final RtpContentMap.Diff diff = currentContentMap.diff(rtpContentMap);
2376
2377        Log.d(
2378                Config.LOGTAG,
2379                id.getAccount().getJid().asBareJid()
2380                        + ": renegotiate. iceRestart="
2381                        + iceRestart
2382                        + " content id diff="
2383                        + diff);
2384
2385        if (diff.hasModifications() && iceRestart) {
2386            webRTCWrapper.close();
2387            sendSessionTerminate(
2388                    Reason.FAILED_APPLICATION,
2389                    "WebRTC unexpectedly tried to modify content and transport at once");
2390            return;
2391        }
2392
2393        if (iceRestart) {
2394            initiateIceRestart(rtpContentMap);
2395            return;
2396        } else if (diff.isEmpty()) {
2397            Log.d(
2398                    Config.LOGTAG,
2399                    "renegotiation. nothing to do. SignalingState="
2400                            + this.webRTCWrapper.getSignalingState());
2401        }
2402
2403        if (diff.added.size() > 0) {
2404            modifyLocalContentMap(rtpContentMap);
2405            sendContentAdd(rtpContentMap, diff.added);
2406        }
2407    }
2408
2409    private void initiateIceRestart(final RtpContentMap rtpContentMap) {
2410        final RtpContentMap transportInfo = rtpContentMap.transportInfo();
2411        final JinglePacket jinglePacket =
2412                transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
2413        Log.d(Config.LOGTAG, "initiating ice restart: " + jinglePacket);
2414        jinglePacket.setTo(id.with);
2415        xmppConnectionService.sendIqPacket(
2416                id.account,
2417                jinglePacket,
2418                (account, response) -> {
2419                    if (response.getType() == IqPacket.TYPE.RESULT) {
2420                        Log.d(Config.LOGTAG, "received success to our ice restart");
2421                        setLocalContentMap(rtpContentMap);
2422                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
2423                        return;
2424                    }
2425                    if (response.getType() == IqPacket.TYPE.ERROR) {
2426                        if (isTieBreak(response)) {
2427                            Log.d(Config.LOGTAG, "received tie-break as result of ice restart");
2428                            return;
2429                        }
2430                        handleIqErrorResponse(response);
2431                    }
2432                    if (response.getType() == IqPacket.TYPE.TIMEOUT) {
2433                        handleIqTimeoutResponse(response);
2434                    }
2435                });
2436    }
2437
2438    private boolean isTieBreak(final IqPacket response) {
2439        final Element error = response.findChild("error");
2440        return error != null && error.hasChild("tie-break", Namespace.JINGLE_ERRORS);
2441    }
2442
2443    private void sendContentAdd(final RtpContentMap rtpContentMap, final Collection<String> added) {
2444        final RtpContentMap contentAdd = rtpContentMap.toContentModification(added);
2445        this.outgoingContentAdd = contentAdd;
2446        final JinglePacket jinglePacket =
2447                contentAdd.toJinglePacket(JinglePacket.Action.CONTENT_ADD, id.sessionId);
2448        jinglePacket.setTo(id.with);
2449        xmppConnectionService.sendIqPacket(
2450                id.account,
2451                jinglePacket,
2452                (connection, response) -> {
2453                    if (response.getType() == IqPacket.TYPE.RESULT) {
2454                        Log.d(
2455                                Config.LOGTAG,
2456                                id.getAccount().getJid().asBareJid()
2457                                        + ": received ACK to our content-add");
2458                        return;
2459                    }
2460                    if (response.getType() == IqPacket.TYPE.ERROR) {
2461                        if (isTieBreak(response)) {
2462                            this.outgoingContentAdd = null;
2463                            Log.d(Config.LOGTAG, "received tie-break as result of our content-add");
2464                            return;
2465                        }
2466                        handleIqErrorResponse(response);
2467                    }
2468                    if (response.getType() == IqPacket.TYPE.TIMEOUT) {
2469                        handleIqTimeoutResponse(response);
2470                    }
2471                });
2472    }
2473
2474    private void setLocalContentMap(final RtpContentMap rtpContentMap) {
2475        if (isInitiator()) {
2476            this.initiatorRtpContentMap = rtpContentMap;
2477        } else {
2478            this.responderRtpContentMap = rtpContentMap;
2479        }
2480    }
2481
2482    private void setRemoteContentMap(final RtpContentMap rtpContentMap) {
2483        if (isInitiator()) {
2484            this.responderRtpContentMap = rtpContentMap;
2485        } else {
2486            this.initiatorRtpContentMap = rtpContentMap;
2487        }
2488    }
2489
2490    // this method is to be used for content map modifications that modify media
2491    private void modifyLocalContentMap(final RtpContentMap rtpContentMap) {
2492        final RtpContentMap activeContents = rtpContentMap.activeContents();
2493        setLocalContentMap(activeContents);
2494        this.webRTCWrapper.switchSpeakerPhonePreference(
2495                AppRTCAudioManager.SpeakerPhonePreference.of(activeContents.getMedia()));
2496        updateEndUserState();
2497    }
2498
2499    private SessionDescription setLocalSessionDescription()
2500            throws ExecutionException, InterruptedException {
2501        final org.webrtc.SessionDescription sessionDescription =
2502                this.webRTCWrapper.setLocalDescription().get();
2503        return SessionDescription.parse(sessionDescription.description);
2504    }
2505
2506    private void closeWebRTCSessionAfterFailedConnection() {
2507        this.webRTCWrapper.close();
2508        synchronized (this) {
2509            if (isTerminated()) {
2510                Log.d(
2511                        Config.LOGTAG,
2512                        id.account.getJid().asBareJid()
2513                                + ": no need to send session-terminate after failed connection. Other party already did");
2514                return;
2515            }
2516            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
2517        }
2518    }
2519
2520    public boolean zeroDuration() {
2521        return this.sessionDuration.elapsed(TimeUnit.NANOSECONDS) <= 0;
2522    }
2523
2524    public long getCallDuration() {
2525        return this.sessionDuration.elapsed(TimeUnit.MILLISECONDS);
2526    }
2527
2528    public AppRTCAudioManager getAudioManager() {
2529        return webRTCWrapper.getAudioManager();
2530    }
2531
2532    public boolean isMicrophoneEnabled() {
2533        return webRTCWrapper.isMicrophoneEnabled();
2534    }
2535
2536    public boolean setMicrophoneEnabled(final boolean enabled) {
2537        return webRTCWrapper.setMicrophoneEnabled(enabled);
2538    }
2539
2540    public boolean isVideoEnabled() {
2541        return webRTCWrapper.isVideoEnabled();
2542    }
2543
2544    public void setVideoEnabled(final boolean enabled) {
2545        webRTCWrapper.setVideoEnabled(enabled);
2546    }
2547
2548    public boolean isCameraSwitchable() {
2549        return webRTCWrapper.isCameraSwitchable();
2550    }
2551
2552    public boolean isFrontCamera() {
2553        return webRTCWrapper.isFrontCamera();
2554    }
2555
2556    public ListenableFuture<Boolean> switchCamera() {
2557        return webRTCWrapper.switchCamera();
2558    }
2559
2560    @Override
2561    public void onAudioDeviceChanged(
2562            AppRTCAudioManager.AudioDevice selectedAudioDevice,
2563            Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
2564        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2565                selectedAudioDevice, availableAudioDevices);
2566    }
2567
2568    private void updateEndUserState() {
2569        final RtpEndUserState endUserState = getEndUserState();
2570        jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
2571        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2572                id.account, id.with, id.sessionId, endUserState);
2573    }
2574
2575    private void updateOngoingCallNotification() {
2576        final State state = this.state;
2577        if (STATES_SHOWING_ONGOING_CALL.contains(state)) {
2578            final boolean reconnecting;
2579            if (state == State.SESSION_ACCEPTED) {
2580                reconnecting =
2581                        getPeerConnectionStateAsEndUserState() == RtpEndUserState.RECONNECTING;
2582            } else {
2583                reconnecting = false;
2584            }
2585            xmppConnectionService.setOngoingCall(id, getMedia(), reconnecting);
2586        } else {
2587            xmppConnectionService.removeOngoingCall();
2588        }
2589    }
2590
2591    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
2592        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
2593            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2594            request.setTo(id.account.getDomain());
2595            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
2596            xmppConnectionService.sendIqPacket(
2597                    id.account,
2598                    request,
2599                    (account, response) -> {
2600                        ImmutableList.Builder<PeerConnection.IceServer> listBuilder =
2601                                new ImmutableList.Builder<>();
2602                        if (response.getType() == IqPacket.TYPE.RESULT) {
2603                            final Element services =
2604                                    response.findChild(
2605                                            "services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
2606                            final List<Element> children =
2607                                    services == null
2608                                            ? Collections.emptyList()
2609                                            : services.getChildren();
2610                            for (final Element child : children) {
2611                                if ("service".equals(child.getName())) {
2612                                    final String type = child.getAttribute("type");
2613                                    final String host = child.getAttribute("host");
2614                                    final String sport = child.getAttribute("port");
2615                                    final Integer port =
2616                                            sport == null ? null : Ints.tryParse(sport);
2617                                    final String transport = child.getAttribute("transport");
2618                                    final String username = child.getAttribute("username");
2619                                    final String password = child.getAttribute("password");
2620                                    if (Strings.isNullOrEmpty(host) || port == null) {
2621                                        continue;
2622                                    }
2623                                    if (port < 0 || port > 65535) {
2624                                        continue;
2625                                    }
2626                                    if (Arrays.asList("stun", "stuns", "turn", "turns")
2627                                                    .contains(type)
2628                                            && Arrays.asList("udp", "tcp").contains(transport)) {
2629                                        if (Arrays.asList("stuns", "turns").contains(type)
2630                                                && "udp".equals(transport)) {
2631                                            Log.d(
2632                                                    Config.LOGTAG,
2633                                                    id.account.getJid().asBareJid()
2634                                                            + ": skipping invalid combination of udp/tls in external services");
2635                                            continue;
2636                                        }
2637                                        // TODO Starting on milestone 110, Chromium will perform
2638                                        // stricter validation of TURN and STUN URLs passed to the
2639                                        // constructor of an RTCPeerConnection. More specifically,
2640                                        // STUN URLs will not support a query section, and TURN URLs
2641                                        // will support only a transport parameter in their query
2642                                        // section.
2643                                        final PeerConnection.IceServer.Builder iceServerBuilder =
2644                                                PeerConnection.IceServer.builder(
2645                                                        String.format(
2646                                                                "%s:%s:%s?transport=%s",
2647                                                                type,
2648                                                                IP.wrapIPv6(host),
2649                                                                port,
2650                                                                transport));
2651                                        iceServerBuilder.setTlsCertPolicy(
2652                                                PeerConnection.TlsCertPolicy
2653                                                        .TLS_CERT_POLICY_INSECURE_NO_CHECK);
2654                                        if (username != null && password != null) {
2655                                            iceServerBuilder.setUsername(username);
2656                                            iceServerBuilder.setPassword(password);
2657                                        } else if (Arrays.asList("turn", "turns").contains(type)) {
2658                                            // The WebRTC spec requires throwing an
2659                                            // InvalidAccessError when username (from libwebrtc
2660                                            // source coder)
2661                                            // https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
2662                                            Log.d(
2663                                                    Config.LOGTAG,
2664                                                    id.account.getJid().asBareJid()
2665                                                            + ": skipping "
2666                                                            + type
2667                                                            + "/"
2668                                                            + transport
2669                                                            + " without username and password");
2670                                            continue;
2671                                        }
2672                                        final PeerConnection.IceServer iceServer =
2673                                                iceServerBuilder.createIceServer();
2674                                        Log.d(
2675                                                Config.LOGTAG,
2676                                                id.account.getJid().asBareJid()
2677                                                        + ": discovered ICE Server: "
2678                                                        + iceServer);
2679                                        listBuilder.add(iceServer);
2680                                    }
2681                                }
2682                            }
2683                        }
2684                        final List<PeerConnection.IceServer> iceServers = listBuilder.build();
2685                        if (iceServers.size() == 0) {
2686                            Log.w(
2687                                    Config.LOGTAG,
2688                                    id.account.getJid().asBareJid()
2689                                            + ": no ICE server found "
2690                                            + response);
2691                        }
2692                        onIceServersDiscovered.onIceServersDiscovered(iceServers);
2693                    });
2694        } else {
2695            Log.w(
2696                    Config.LOGTAG,
2697                    id.account.getJid().asBareJid() + ": has no external service discovery");
2698            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
2699        }
2700    }
2701
2702    private void finish() {
2703        if (isTerminated()) {
2704            this.cancelRingingTimeout();
2705            this.webRTCWrapper.verifyClosed();
2706            this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
2707            this.jingleConnectionManager.finishConnectionOrThrow(this);
2708        } else {
2709            throw new IllegalStateException(
2710                    String.format("Unable to call finish from %s", this.state));
2711        }
2712    }
2713
2714    private void writeLogMessage(final State state) {
2715        final long duration = getCallDuration();
2716        if (state == State.TERMINATED_SUCCESS
2717                || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
2718            writeLogMessageSuccess(duration);
2719        } else {
2720            writeLogMessageMissed();
2721        }
2722    }
2723
2724    private void writeLogMessageSuccess(final long duration) {
2725        this.message.setBody(new RtpSessionStatus(true, duration).toString());
2726        this.writeMessage();
2727    }
2728
2729    private void writeLogMessageMissed() {
2730        this.message.setBody(new RtpSessionStatus(false, 0).toString());
2731        this.writeMessage();
2732    }
2733
2734    private void writeMessage() {
2735        final Conversational conversational = message.getConversation();
2736        if (conversational instanceof Conversation) {
2737            ((Conversation) conversational).add(this.message);
2738            xmppConnectionService.createMessageAsync(message);
2739            xmppConnectionService.updateConversationUi();
2740        } else {
2741            throw new IllegalStateException("Somehow the conversation in a message was a stub");
2742        }
2743    }
2744
2745    public State getState() {
2746        return this.state;
2747    }
2748
2749    boolean isTerminated() {
2750        return TERMINATED.contains(this.state);
2751    }
2752
2753    public Optional<VideoTrack> getLocalVideoTrack() {
2754        return webRTCWrapper.getLocalVideoTrack();
2755    }
2756
2757    public Optional<VideoTrack> getRemoteVideoTrack() {
2758        return webRTCWrapper.getRemoteVideoTrack();
2759    }
2760
2761    public EglBase.Context getEglBaseContext() {
2762        return webRTCWrapper.getEglBaseContext();
2763    }
2764
2765    void setProposedMedia(final Set<Media> media) {
2766        this.proposedMedia = media;
2767    }
2768
2769    public void fireStateUpdate() {
2770        final RtpEndUserState endUserState = getEndUserState();
2771        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2772                id.account, id.with, id.sessionId, endUserState);
2773    }
2774
2775    public boolean isSwitchToVideoAvailable() {
2776        final boolean prerequisite =
2777                Media.audioOnly(getMedia())
2778                        && Arrays.asList(RtpEndUserState.CONNECTED, RtpEndUserState.RECONNECTING)
2779                                .contains(getEndUserState());
2780        return prerequisite && remoteHasVideoFeature();
2781    }
2782
2783    private boolean remoteHasVideoFeature() {
2784        final Contact contact = id.getContact();
2785        final Presence presence =
2786                contact.getPresences().get(Strings.nullToEmpty(id.with.getResource()));
2787        final ServiceDiscoveryResult serviceDiscoveryResult =
2788                presence == null ? null : presence.getServiceDiscoveryResult();
2789        final List<String> features =
2790                serviceDiscoveryResult == null ? null : serviceDiscoveryResult.getFeatures();
2791        return features != null && features.contains(Namespace.JINGLE_FEATURE_VIDEO);
2792    }
2793
2794    private interface OnIceServersDiscovered {
2795        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
2796    }
2797}