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                Log.d(Config.LOGTAG, id.account.getJid() + ": received accept from " + from);
1381            }
1382        } else {
1383            Log.d(
1384                    Config.LOGTAG,
1385                    id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
1386        }
1387    }
1388
1389    private void acceptedOnOtherDevice(final String serverMsgId, final long timestamp) {
1390        if (serverMsgId != null) {
1391            this.message.setServerMsgId(serverMsgId);
1392        }
1393        this.message.setTime(timestamp);
1394        this.message.setCarbon(true); // indicate that call was accepted on other device
1395        this.writeLogMessageSuccess(0);
1396        this.xmppConnectionService
1397                .getNotificationService()
1398                .cancelIncomingCallNotification();
1399        this.finish();
1400    }
1401
1402    private void receiveReject(final Jid from, final String serverMsgId, final long timestamp) {
1403        final boolean originatedFromMyself =
1404                from.asBareJid().equals(id.account.getJid().asBareJid());
1405        // reject from another one of my clients
1406        if (originatedFromMyself) {
1407            receiveRejectFromMyself(serverMsgId, timestamp);
1408        } else if (isInitiator()) {
1409            if (from.equals(id.with)) {
1410                receiveRejectFromResponder();
1411            } else {
1412                Log.d(
1413                        Config.LOGTAG,
1414                        id.account.getJid()
1415                                + ": ignoring reject from "
1416                                + from
1417                                + " for session with "
1418                                + id.with);
1419            }
1420        } else {
1421            Log.d(
1422                    Config.LOGTAG,
1423                    id.account.getJid()
1424                            + ": ignoring reject from "
1425                            + from
1426                            + " for session with "
1427                            + id.with);
1428        }
1429    }
1430
1431    private void receiveRejectFromMyself(String serverMsgId, long timestamp) {
1432        if (transition(State.REJECTED)) {
1433            this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1434            this.finish();
1435            if (serverMsgId != null) {
1436                this.message.setServerMsgId(serverMsgId);
1437            }
1438            this.message.setTime(timestamp);
1439            this.message.setCarbon(true); // indicate that call was rejected on other device
1440            writeLogMessageMissed();
1441        } else {
1442            Log.d(
1443                    Config.LOGTAG,
1444                    "not able to transition into REJECTED because already in " + this.state);
1445        }
1446    }
1447
1448    private void receiveRejectFromResponder() {
1449        if (isInState(State.PROCEED)) {
1450            Log.d(
1451                    Config.LOGTAG,
1452                    id.account.getJid()
1453                            + ": received reject while still in proceed. callee reconsidered");
1454            closeTransitionLogFinish(State.REJECTED_RACED);
1455            return;
1456        }
1457        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED)) {
1458            Log.d(
1459                    Config.LOGTAG,
1460                    id.account.getJid()
1461                            + ": received reject while in SESSION_INITIATED_PRE_APPROVED. callee reconsidered before receiving session-init");
1462            closeTransitionLogFinish(State.TERMINATED_DECLINED_OR_BUSY);
1463            return;
1464        }
1465        Log.d(
1466                Config.LOGTAG,
1467                id.account.getJid()
1468                        + ": ignoring reject from responder because already in state "
1469                        + this.state);
1470    }
1471
1472    private void receivePropose(
1473            final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
1474        final boolean originatedFromMyself =
1475                from.asBareJid().equals(id.account.getJid().asBareJid());
1476        if (originatedFromMyself) {
1477            Log.d(
1478                    Config.LOGTAG,
1479                    id.account.getJid().asBareJid() + ": saw proposal from myself. ignoring");
1480        } else if (transition(
1481                State.PROPOSED,
1482                () -> {
1483                    final Collection<RtpDescription> descriptions =
1484                            Collections2.transform(
1485                                    Collections2.filter(
1486                                            propose.getDescriptions(),
1487                                            d -> d instanceof RtpDescription),
1488                                    input -> (RtpDescription) input);
1489                    final Collection<Media> media =
1490                            Collections2.transform(descriptions, RtpDescription::getMedia);
1491                    Preconditions.checkState(
1492                            !media.contains(Media.UNKNOWN),
1493                            "RTP descriptions contain unknown media");
1494                    Log.d(
1495                            Config.LOGTAG,
1496                            id.account.getJid().asBareJid()
1497                                    + ": received session proposal from "
1498                                    + from
1499                                    + " for "
1500                                    + media);
1501                    this.proposedMedia = Sets.newHashSet(media);
1502                })) {
1503            if (serverMsgId != null) {
1504                this.message.setServerMsgId(serverMsgId);
1505            }
1506            this.message.setTime(timestamp);
1507            startRinging();
1508            sendJingleMessage("ringing");
1509        } else {
1510            Log.d(
1511                    Config.LOGTAG,
1512                    id.account.getJid()
1513                            + ": ignoring session proposal because already in "
1514                            + state);
1515        }
1516    }
1517
1518    private void startRinging() {
1519        Log.d(
1520                Config.LOGTAG,
1521                id.account.getJid().asBareJid()
1522                        + ": received call from "
1523                        + id.with
1524                        + ". start ringing");
1525        ringingTimeoutFuture =
1526                jingleConnectionManager.schedule(
1527                        this::ringingTimeout, BUSY_TIME_OUT, TimeUnit.SECONDS);
1528        xmppConnectionService.getNotificationService().startRinging(id, getMedia());
1529    }
1530
1531    private synchronized void ringingTimeout() {
1532        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": timeout reached for ringing");
1533        switch (this.state) {
1534            case PROPOSED:
1535                message.markUnread();
1536                rejectCallFromProposed();
1537                break;
1538            case SESSION_INITIALIZED:
1539                message.markUnread();
1540                rejectCallFromSessionInitiate();
1541                break;
1542        }
1543        xmppConnectionService.getNotificationService().pushMissedCallNow(message);
1544    }
1545
1546    private void cancelRingingTimeout() {
1547        final ScheduledFuture<?> future = this.ringingTimeoutFuture;
1548        if (future != null && !future.isCancelled()) {
1549            future.cancel(false);
1550        }
1551    }
1552
1553    private void receiveProceed(
1554            final Jid from, final Proceed proceed, final String serverMsgId, final long timestamp) {
1555        final Set<Media> media =
1556                Preconditions.checkNotNull(
1557                        this.proposedMedia, "Proposed media has to be set before handling proceed");
1558        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
1559        if (from.equals(id.with)) {
1560            if (isInitiator()) {
1561                if (transition(State.PROCEED)) {
1562                    if (serverMsgId != null) {
1563                        this.message.setServerMsgId(serverMsgId);
1564                    }
1565                    this.message.setTime(timestamp);
1566                    final Integer remoteDeviceId = proceed.getDeviceId();
1567                    if (isOmemoEnabled()) {
1568                        this.omemoVerification.setDeviceId(remoteDeviceId);
1569                    } else {
1570                        if (remoteDeviceId != null) {
1571                            Log.d(
1572                                    Config.LOGTAG,
1573                                    id.account.getJid().asBareJid()
1574                                            + ": remote party signaled support for OMEMO verification but we have OMEMO disabled");
1575                        }
1576                        this.omemoVerification.setDeviceId(null);
1577                    }
1578                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
1579                } else {
1580                    Log.d(
1581                            Config.LOGTAG,
1582                            String.format(
1583                                    "%s: ignoring proceed because already in %s",
1584                                    id.account.getJid().asBareJid(), this.state));
1585                }
1586            } else {
1587                Log.d(
1588                        Config.LOGTAG,
1589                        String.format(
1590                                "%s: ignoring proceed because we were not initializing",
1591                                id.account.getJid().asBareJid()));
1592            }
1593        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
1594            if (transition(State.ACCEPTED)) {
1595                Log.d(
1596                        Config.LOGTAG,
1597                        id.account.getJid().asBareJid()
1598                                + ": moved session with "
1599                                + id.with
1600                                + " into state accepted after received carbon copied proceed");
1601                acceptedOnOtherDevice(serverMsgId, timestamp);
1602            }
1603        } else {
1604            Log.d(
1605                    Config.LOGTAG,
1606                    String.format(
1607                            "%s: ignoring proceed from %s. was expected from %s",
1608                            id.account.getJid().asBareJid(), from, id.with));
1609        }
1610    }
1611
1612    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
1613        if (from.equals(id.with)) {
1614            final State target =
1615                    this.state == State.PROCEED ? State.RETRACTED_RACED : State.RETRACTED;
1616            if (transition(target)) {
1617                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1618                xmppConnectionService.getNotificationService().pushMissedCallNow(message);
1619                Log.d(
1620                        Config.LOGTAG,
1621                        id.account.getJid().asBareJid()
1622                                + ": session with "
1623                                + id.with
1624                                + " has been retracted (serverMsgId="
1625                                + serverMsgId
1626                                + ")");
1627                if (serverMsgId != null) {
1628                    this.message.setServerMsgId(serverMsgId);
1629                }
1630                this.message.setTime(timestamp);
1631                if (target == State.RETRACTED) {
1632                    this.message.markUnread();
1633                }
1634                writeLogMessageMissed();
1635                finish();
1636            } else {
1637                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
1638            }
1639        } else {
1640            // TODO parse retract from self
1641            Log.d(
1642                    Config.LOGTAG,
1643                    id.account.getJid().asBareJid()
1644                            + ": received retract from "
1645                            + from
1646                            + ". expected retract from"
1647                            + id.with
1648                            + ". ignoring");
1649        }
1650    }
1651
1652    public void sendSessionInitiate() {
1653        sendSessionInitiate(this.proposedMedia, State.SESSION_INITIALIZED);
1654    }
1655
1656    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
1657        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
1658        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
1659    }
1660
1661    private synchronized void sendSessionInitiate(
1662            final Set<Media> media,
1663            final State targetState,
1664            final List<PeerConnection.IceServer> iceServers) {
1665        if (isTerminated()) {
1666            Log.w(
1667                    Config.LOGTAG,
1668                    id.account.getJid().asBareJid()
1669                            + ": ICE servers got discovered when session was already terminated. nothing to do.");
1670            return;
1671        }
1672        try {
1673            setupWebRTC(media, iceServers);
1674        } catch (final WebRTCWrapper.InitializationException e) {
1675            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
1676            webRTCWrapper.close();
1677            sendRetract(Reason.ofThrowable(e));
1678            return;
1679        }
1680        try {
1681            org.webrtc.SessionDescription webRTCSessionDescription =
1682                    this.webRTCWrapper.setLocalDescription().get();
1683            prepareSessionInitiate(webRTCSessionDescription, targetState);
1684        } catch (final Exception e) {
1685            // TODO sending the error text is worthwhile as well. Especially for FailureToSet
1686            // exceptions
1687            failureToInitiateSession(e, targetState);
1688        }
1689    }
1690
1691    private void failureToInitiateSession(final Throwable throwable, final State targetState) {
1692        if (isTerminated()) {
1693            return;
1694        }
1695        Log.d(
1696                Config.LOGTAG,
1697                id.account.getJid().asBareJid() + ": unable to sendSessionInitiate",
1698                Throwables.getRootCause(throwable));
1699        webRTCWrapper.close();
1700        final Reason reason = Reason.ofThrowable(throwable);
1701        if (isInState(targetState)) {
1702            sendSessionTerminate(reason, throwable.getMessage());
1703        } else {
1704            sendRetract(reason);
1705        }
1706    }
1707
1708    private void sendRetract(final Reason reason) {
1709        // TODO embed reason into retract
1710        sendJingleMessage("retract", id.with.asBareJid());
1711        transitionOrThrow(reasonToState(reason));
1712        this.finish();
1713    }
1714
1715    private void prepareSessionInitiate(
1716            final org.webrtc.SessionDescription webRTCSessionDescription, final State targetState) {
1717        final SessionDescription sessionDescription =
1718                SessionDescription.parse(webRTCSessionDescription.description);
1719        final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription, true);
1720        this.initiatorRtpContentMap = rtpContentMap;
1721        final ListenableFuture<RtpContentMap> outgoingContentMapFuture =
1722                encryptSessionInitiate(rtpContentMap);
1723        Futures.addCallback(
1724                outgoingContentMapFuture,
1725                new FutureCallback<RtpContentMap>() {
1726                    @Override
1727                    public void onSuccess(final RtpContentMap outgoingContentMap) {
1728                        sendSessionInitiate(outgoingContentMap, targetState);
1729                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
1730                    }
1731
1732                    @Override
1733                    public void onFailure(@NonNull final Throwable throwable) {
1734                        failureToInitiateSession(throwable, targetState);
1735                    }
1736                },
1737                MoreExecutors.directExecutor());
1738    }
1739
1740    private void sendSessionInitiate(final RtpContentMap rtpContentMap, final State targetState) {
1741        if (isTerminated()) {
1742            Log.w(
1743                    Config.LOGTAG,
1744                    id.account.getJid().asBareJid()
1745                            + ": preparing session was too slow. already terminated. nothing to do.");
1746            return;
1747        }
1748        this.transitionOrThrow(targetState);
1749        final JinglePacket sessionInitiate =
1750                rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
1751        send(sessionInitiate);
1752    }
1753
1754    private ListenableFuture<RtpContentMap> encryptSessionInitiate(
1755            final RtpContentMap rtpContentMap) {
1756        if (this.omemoVerification.hasDeviceId()) {
1757            final ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>>
1758                    verifiedPayloadFuture =
1759                            id.account
1760                                    .getAxolotlService()
1761                                    .encrypt(
1762                                            rtpContentMap,
1763                                            id.with,
1764                                            omemoVerification.getDeviceId());
1765            final ListenableFuture<RtpContentMap> future =
1766                    Futures.transform(
1767                            verifiedPayloadFuture,
1768                            verifiedPayload -> {
1769                                omemoVerification.setSessionFingerprint(
1770                                        verifiedPayload.getFingerprint());
1771                                return verifiedPayload.getPayload();
1772                            },
1773                            MoreExecutors.directExecutor());
1774            if (Config.REQUIRE_RTP_VERIFICATION) {
1775                return future;
1776            }
1777            return Futures.catching(
1778                    future,
1779                    CryptoFailedException.class,
1780                    e -> {
1781                        Log.w(
1782                                Config.LOGTAG,
1783                                id.account.getJid().asBareJid()
1784                                        + ": unable to use OMEMO DTLS verification on outgoing session initiate. falling back",
1785                                e);
1786                        return rtpContentMap;
1787                    },
1788                    MoreExecutors.directExecutor());
1789        } else {
1790            return Futures.immediateFuture(rtpContentMap);
1791        }
1792    }
1793
1794    private void sendSessionTerminate(final Reason reason) {
1795        sendSessionTerminate(reason, null);
1796    }
1797
1798    private void sendSessionTerminate(final Reason reason, final String text) {
1799        final State previous = this.state;
1800        final State target = reasonToState(reason);
1801        transitionOrThrow(target);
1802        if (previous != State.NULL) {
1803            writeLogMessage(target);
1804        }
1805        final JinglePacket jinglePacket =
1806                new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
1807        jinglePacket.setReason(reason, text);
1808        Log.d(Config.LOGTAG, jinglePacket.toString());
1809        send(jinglePacket);
1810        finish();
1811    }
1812
1813    private void sendTransportInfo(
1814            final String contentName, IceUdpTransportInfo.Candidate candidate) {
1815        final RtpContentMap transportInfo;
1816        try {
1817            final RtpContentMap rtpContentMap =
1818                    isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
1819            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
1820        } catch (final Exception e) {
1821            Log.d(
1822                    Config.LOGTAG,
1823                    id.account.getJid().asBareJid()
1824                            + ": unable to prepare transport-info from candidate for content="
1825                            + contentName);
1826            return;
1827        }
1828        final JinglePacket jinglePacket =
1829                transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
1830        send(jinglePacket);
1831    }
1832
1833    private void send(final JinglePacket jinglePacket) {
1834        jinglePacket.setTo(id.with);
1835        xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
1836    }
1837
1838    private synchronized void handleIqResponse(final Account account, final IqPacket response) {
1839        if (response.getType() == IqPacket.TYPE.ERROR) {
1840            handleIqErrorResponse(response);
1841            return;
1842        }
1843        if (response.getType() == IqPacket.TYPE.TIMEOUT) {
1844            handleIqTimeoutResponse(response);
1845        }
1846    }
1847
1848    private void handleIqErrorResponse(final IqPacket response) {
1849        Preconditions.checkArgument(response.getType() == IqPacket.TYPE.ERROR);
1850        final String errorCondition = response.getErrorCondition();
1851        Log.d(
1852                Config.LOGTAG,
1853                id.account.getJid().asBareJid()
1854                        + ": received IQ-error from "
1855                        + response.getFrom()
1856                        + " in RTP session. "
1857                        + errorCondition);
1858        if (isTerminated()) {
1859            Log.i(
1860                    Config.LOGTAG,
1861                    id.account.getJid().asBareJid()
1862                            + ": ignoring error because session was already terminated");
1863            return;
1864        }
1865        this.webRTCWrapper.close();
1866        final State target;
1867        if (Arrays.asList(
1868                        "service-unavailable",
1869                        "recipient-unavailable",
1870                        "remote-server-not-found",
1871                        "remote-server-timeout")
1872                .contains(errorCondition)) {
1873            target = State.TERMINATED_CONNECTIVITY_ERROR;
1874        } else {
1875            target = State.TERMINATED_APPLICATION_FAILURE;
1876        }
1877        transitionOrThrow(target);
1878        this.finish();
1879    }
1880
1881    private void handleIqTimeoutResponse(final IqPacket response) {
1882        Preconditions.checkArgument(response.getType() == IqPacket.TYPE.TIMEOUT);
1883        Log.d(
1884                Config.LOGTAG,
1885                id.account.getJid().asBareJid()
1886                        + ": received IQ timeout in RTP session with "
1887                        + id.with
1888                        + ". terminating with connectivity error");
1889        if (isTerminated()) {
1890            Log.i(
1891                    Config.LOGTAG,
1892                    id.account.getJid().asBareJid()
1893                            + ": ignoring error because session was already terminated");
1894            return;
1895        }
1896        this.webRTCWrapper.close();
1897        transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
1898        this.finish();
1899    }
1900
1901    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
1902        Log.d(
1903                Config.LOGTAG,
1904                id.account.getJid().asBareJid() + ": terminating session with out-of-order");
1905        this.webRTCWrapper.close();
1906        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
1907        respondWithOutOfOrder(jinglePacket);
1908        this.finish();
1909    }
1910
1911    private void respondWithTieBreak(final JinglePacket jinglePacket) {
1912        respondWithJingleError(jinglePacket, "tie-break", "conflict", "cancel");
1913    }
1914
1915    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
1916        respondWithJingleError(jinglePacket, "out-of-order", "unexpected-request", "wait");
1917    }
1918
1919    void respondWithJingleError(
1920            final IqPacket original,
1921            String jingleCondition,
1922            String condition,
1923            String conditionType) {
1924        jingleConnectionManager.respondWithJingleError(
1925                id.account, original, jingleCondition, condition, conditionType);
1926    }
1927
1928    private void respondOk(final JinglePacket jinglePacket) {
1929        xmppConnectionService.sendIqPacket(
1930                id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
1931    }
1932
1933    public RtpEndUserState getEndUserState() {
1934        switch (this.state) {
1935            case NULL:
1936            case PROPOSED:
1937            case SESSION_INITIALIZED:
1938                if (isInitiator()) {
1939                    return RtpEndUserState.RINGING;
1940                } else {
1941                    return RtpEndUserState.INCOMING_CALL;
1942                }
1943            case PROCEED:
1944                if (isInitiator()) {
1945                    return RtpEndUserState.RINGING;
1946                } else {
1947                    return RtpEndUserState.ACCEPTING_CALL;
1948                }
1949            case SESSION_INITIALIZED_PRE_APPROVED:
1950                if (isInitiator()) {
1951                    return RtpEndUserState.RINGING;
1952                } else {
1953                    return RtpEndUserState.CONNECTING;
1954                }
1955            case SESSION_ACCEPTED:
1956                final ContentAddition ca = getPendingContentAddition();
1957                if (ca != null && ca.direction == ContentAddition.Direction.INCOMING) {
1958                    return RtpEndUserState.INCOMING_CONTENT_ADD;
1959                }
1960                return getPeerConnectionStateAsEndUserState();
1961            case REJECTED:
1962            case REJECTED_RACED:
1963            case TERMINATED_DECLINED_OR_BUSY:
1964                if (isInitiator()) {
1965                    return RtpEndUserState.DECLINED_OR_BUSY;
1966                } else {
1967                    return RtpEndUserState.ENDED;
1968                }
1969            case TERMINATED_SUCCESS:
1970            case ACCEPTED:
1971            case RETRACTED:
1972            case TERMINATED_CANCEL_OR_TIMEOUT:
1973                return RtpEndUserState.ENDED;
1974            case RETRACTED_RACED:
1975                if (isInitiator()) {
1976                    return RtpEndUserState.ENDED;
1977                } else {
1978                    return RtpEndUserState.RETRACTED;
1979                }
1980            case TERMINATED_CONNECTIVITY_ERROR:
1981                return zeroDuration()
1982                        ? RtpEndUserState.CONNECTIVITY_ERROR
1983                        : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
1984            case TERMINATED_APPLICATION_FAILURE:
1985                return RtpEndUserState.APPLICATION_ERROR;
1986            case TERMINATED_SECURITY_ERROR:
1987                return RtpEndUserState.SECURITY_ERROR;
1988        }
1989        throw new IllegalStateException(
1990                String.format("%s has no equivalent EndUserState", this.state));
1991    }
1992
1993    private RtpEndUserState getPeerConnectionStateAsEndUserState() {
1994        final PeerConnection.PeerConnectionState state;
1995        try {
1996            state = webRTCWrapper.getState();
1997        } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
1998            // We usually close the WebRTCWrapper *before* transitioning so we might still
1999            // be in SESSION_ACCEPTED even though the peerConnection has been torn down
2000            return RtpEndUserState.ENDING_CALL;
2001        }
2002        switch (state) {
2003            case CONNECTED:
2004                return RtpEndUserState.CONNECTED;
2005            case NEW:
2006            case CONNECTING:
2007                return RtpEndUserState.CONNECTING;
2008            case CLOSED:
2009                return RtpEndUserState.ENDING_CALL;
2010            default:
2011                return zeroDuration()
2012                        ? RtpEndUserState.CONNECTIVITY_ERROR
2013                        : RtpEndUserState.RECONNECTING;
2014        }
2015    }
2016
2017    public ContentAddition getPendingContentAddition() {
2018        final RtpContentMap in = this.incomingContentAdd;
2019        final RtpContentMap out = this.outgoingContentAdd;
2020        if (out != null) {
2021            return ContentAddition.of(ContentAddition.Direction.OUTGOING, out);
2022        } else if (in != null) {
2023            return ContentAddition.of(ContentAddition.Direction.INCOMING, in);
2024        } else {
2025            return null;
2026        }
2027    }
2028
2029    public Set<Media> getMedia() {
2030        final State current = getState();
2031        if (current == State.NULL) {
2032            if (isInitiator()) {
2033                return Preconditions.checkNotNull(
2034                        this.proposedMedia, "RTP connection has not been initialized properly");
2035            }
2036            throw new IllegalStateException("RTP connection has not been initialized yet");
2037        }
2038        if (Arrays.asList(State.PROPOSED, State.PROCEED).contains(current)) {
2039            return Preconditions.checkNotNull(
2040                    this.proposedMedia, "RTP connection has not been initialized properly");
2041        }
2042        final RtpContentMap localContentMap = getLocalContentMap();
2043        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
2044        if (localContentMap != null) {
2045            return localContentMap.getMedia();
2046        } else if (initiatorContentMap != null) {
2047            return initiatorContentMap.getMedia();
2048        } else if (isTerminated()) {
2049            return Collections.emptySet(); //we might fail before we ever got a chance to set media
2050        } else {
2051            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
2052        }
2053    }
2054
2055    public boolean isVerified() {
2056        final String fingerprint = this.omemoVerification.getFingerprint();
2057        if (fingerprint == null) {
2058            return false;
2059        }
2060        final FingerprintStatus status =
2061                id.account.getAxolotlService().getFingerprintTrust(fingerprint);
2062        return status != null && status.isVerified();
2063    }
2064
2065    public boolean addMedia(final Media media) {
2066        final Set<Media> currentMedia = getMedia();
2067        if (currentMedia.contains(media)) {
2068            throw new IllegalStateException(String.format("%s has already been proposed", media));
2069        }
2070        // TODO add state protection - can only add while ACCEPTED or so
2071        Log.d(Config.LOGTAG,"adding media: "+media);
2072        return webRTCWrapper.addTrack(media);
2073    }
2074
2075    public synchronized void acceptCall() {
2076        switch (this.state) {
2077            case PROPOSED:
2078                cancelRingingTimeout();
2079                acceptCallFromProposed();
2080                break;
2081            case SESSION_INITIALIZED:
2082                cancelRingingTimeout();
2083                acceptCallFromSessionInitialized();
2084                break;
2085            case ACCEPTED:
2086                Log.w(
2087                        Config.LOGTAG,
2088                        id.account.getJid().asBareJid()
2089                                + ": the call has already been accepted  with another client. UI was just lagging behind");
2090                break;
2091            case PROCEED:
2092            case SESSION_ACCEPTED:
2093                Log.w(
2094                        Config.LOGTAG,
2095                        id.account.getJid().asBareJid()
2096                                + ": the call has already been accepted. user probably double tapped the UI");
2097                break;
2098            default:
2099                throw new IllegalStateException("Can not accept call from " + this.state);
2100        }
2101    }
2102
2103    public void notifyPhoneCall() {
2104        Log.d(Config.LOGTAG, "a phone call has just been started. killing jingle rtp connections");
2105        if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(this.state)) {
2106            rejectCall();
2107        } else {
2108            endCall();
2109        }
2110    }
2111
2112    public synchronized void rejectCall() {
2113        if (isTerminated()) {
2114            Log.w(
2115                    Config.LOGTAG,
2116                    id.account.getJid().asBareJid()
2117                            + ": received rejectCall() when session has already been terminated. nothing to do");
2118            return;
2119        }
2120        switch (this.state) {
2121            case PROPOSED:
2122                rejectCallFromProposed();
2123                break;
2124            case SESSION_INITIALIZED:
2125                rejectCallFromSessionInitiate();
2126                break;
2127            default:
2128                throw new IllegalStateException("Can not reject call from " + this.state);
2129        }
2130    }
2131
2132    public synchronized void endCall() {
2133        if (isTerminated()) {
2134            Log.w(
2135                    Config.LOGTAG,
2136                    id.account.getJid().asBareJid()
2137                            + ": received endCall() when session has already been terminated. nothing to do");
2138            return;
2139        }
2140        if (isInState(State.PROPOSED) && !isInitiator()) {
2141            rejectCallFromProposed();
2142            return;
2143        }
2144        if (isInState(State.PROCEED)) {
2145            if (isInitiator()) {
2146                retractFromProceed();
2147            } else {
2148                rejectCallFromProceed();
2149            }
2150            return;
2151        }
2152        if (isInitiator()
2153                && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
2154            this.webRTCWrapper.close();
2155            sendSessionTerminate(Reason.CANCEL);
2156            return;
2157        }
2158        if (isInState(State.SESSION_INITIALIZED)) {
2159            rejectCallFromSessionInitiate();
2160            return;
2161        }
2162        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
2163            this.webRTCWrapper.close();
2164            sendSessionTerminate(Reason.SUCCESS);
2165            return;
2166        }
2167        if (isInState(
2168                State.TERMINATED_APPLICATION_FAILURE,
2169                State.TERMINATED_CONNECTIVITY_ERROR,
2170                State.TERMINATED_DECLINED_OR_BUSY)) {
2171            Log.d(
2172                    Config.LOGTAG,
2173                    "ignoring request to end call because already in state " + this.state);
2174            return;
2175        }
2176        throw new IllegalStateException(
2177                "called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
2178    }
2179
2180    private void retractFromProceed() {
2181        Log.d(Config.LOGTAG, "retract from proceed");
2182        this.sendJingleMessage("retract");
2183        closeTransitionLogFinish(State.RETRACTED_RACED);
2184    }
2185
2186    private void closeTransitionLogFinish(final State state) {
2187        this.webRTCWrapper.close();
2188        transitionOrThrow(state);
2189        writeLogMessage(state);
2190        finish();
2191    }
2192
2193    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
2194        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
2195        this.webRTCWrapper.setup(this.xmppConnectionService, AppRTCAudioManager.SpeakerPhonePreference.of(media));
2196        this.webRTCWrapper.initializePeerConnection(media, iceServers);
2197    }
2198
2199    private void acceptCallFromProposed() {
2200        transitionOrThrow(State.PROCEED);
2201        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2202        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
2203        this.sendJingleMessage("proceed");
2204    }
2205
2206    private void rejectCallFromProposed() {
2207        transitionOrThrow(State.REJECTED);
2208        writeLogMessageMissed();
2209        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2210        this.sendJingleMessage("reject");
2211        finish();
2212    }
2213
2214    private void rejectCallFromProceed() {
2215        this.sendJingleMessage("reject");
2216        closeTransitionLogFinish(State.REJECTED_RACED);
2217    }
2218
2219    private void rejectCallFromSessionInitiate() {
2220        webRTCWrapper.close();
2221        sendSessionTerminate(Reason.DECLINE);
2222        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2223    }
2224
2225    private void sendJingleMessage(final String action) {
2226        sendJingleMessage(action, id.with);
2227    }
2228
2229    private void sendJingleMessage(final String action, final Jid to) {
2230        final MessagePacket messagePacket = new MessagePacket();
2231        messagePacket.setType(MessagePacket.TYPE_CHAT); // we want to carbon copy those
2232        messagePacket.setTo(to);
2233        final Element intent =
2234                messagePacket
2235                        .addChild(action, Namespace.JINGLE_MESSAGE)
2236                        .setAttribute("id", id.sessionId);
2237        if ("proceed".equals(action)) {
2238            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
2239            if (isOmemoEnabled()) {
2240                final int deviceId = id.account.getAxolotlService().getOwnDeviceId();
2241                final Element device =
2242                        intent.addChild("device", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
2243                device.setAttribute("id", deviceId);
2244            }
2245        }
2246        messagePacket.addChild("store", "urn:xmpp:hints");
2247        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
2248    }
2249
2250    private boolean isOmemoEnabled() {
2251        final Conversational conversational = message.getConversation();
2252        if (conversational instanceof Conversation) {
2253            return ((Conversation) conversational).getNextEncryption()
2254                    == Message.ENCRYPTION_AXOLOTL;
2255        }
2256        return false;
2257    }
2258
2259    private void acceptCallFromSessionInitialized() {
2260        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2261        sendSessionAccept();
2262    }
2263
2264    private synchronized boolean isInState(State... state) {
2265        return Arrays.asList(state).contains(this.state);
2266    }
2267
2268    private boolean transition(final State target) {
2269        return transition(target, null);
2270    }
2271
2272    private synchronized boolean transition(final State target, final Runnable runnable) {
2273        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
2274        if (validTransitions != null && validTransitions.contains(target)) {
2275            this.state = target;
2276            if (runnable != null) {
2277                runnable.run();
2278            }
2279            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
2280            updateEndUserState();
2281            updateOngoingCallNotification();
2282            return true;
2283        } else {
2284            return false;
2285        }
2286    }
2287
2288    void transitionOrThrow(final State target) {
2289        if (!transition(target)) {
2290            throw new IllegalStateException(
2291                    String.format("Unable to transition from %s to %s", this.state, target));
2292        }
2293    }
2294
2295    @Override
2296    public void onIceCandidate(final IceCandidate iceCandidate) {
2297        final RtpContentMap rtpContentMap =
2298                isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
2299        final IceUdpTransportInfo.Credentials credentials;
2300        try {
2301            credentials = rtpContentMap.getCredentials(iceCandidate.sdpMid);
2302        } catch (final IllegalArgumentException e) {
2303            Log.d(Config.LOGTAG, "ignoring (not sending) candidate: " + iceCandidate, e);
2304            return;
2305        }
2306        final String uFrag = credentials.ufrag;
2307        final IceUdpTransportInfo.Candidate candidate =
2308                IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp, uFrag);
2309        if (candidate == null) {
2310            Log.d(Config.LOGTAG, "ignoring (not sending) candidate: " + iceCandidate);
2311            return;
2312        }
2313        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate);
2314        sendTransportInfo(iceCandidate.sdpMid, candidate);
2315    }
2316
2317    @Override
2318    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
2319        Log.d(
2320                Config.LOGTAG,
2321                id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
2322        this.stateHistory.add(newState);
2323        if (newState == PeerConnection.PeerConnectionState.CONNECTED) {
2324            this.sessionDuration.start();
2325            updateOngoingCallNotification();
2326        } else if (this.sessionDuration.isRunning()) {
2327            this.sessionDuration.stop();
2328            updateOngoingCallNotification();
2329        }
2330
2331        final boolean neverConnected =
2332                !this.stateHistory.contains(PeerConnection.PeerConnectionState.CONNECTED);
2333
2334        if (newState == PeerConnection.PeerConnectionState.FAILED) {
2335            if (neverConnected) {
2336                if (isTerminated()) {
2337                    Log.d(
2338                            Config.LOGTAG,
2339                            id.account.getJid().asBareJid()
2340                                    + ": not sending session-terminate after connectivity error because session is already in state "
2341                                    + this.state);
2342                    return;
2343                }
2344                webRTCWrapper.execute(this::closeWebRTCSessionAfterFailedConnection);
2345                return;
2346            } else {
2347                this.restartIce();
2348            }
2349        }
2350        updateEndUserState();
2351    }
2352
2353    private void restartIce() {
2354        this.stateHistory.clear();
2355        this.webRTCWrapper.restartIce();
2356    }
2357
2358    @Override
2359    public void onRenegotiationNeeded() {
2360        this.webRTCWrapper.execute(this::renegotiate);
2361    }
2362
2363    private void renegotiate() {
2364        final SessionDescription sessionDescription;
2365        try {
2366            sessionDescription = setLocalSessionDescription();
2367        } catch (final Exception e) {
2368            final Throwable cause = Throwables.getRootCause(e);
2369            Log.d(Config.LOGTAG, "failed to renegotiate", cause);
2370            webRTCWrapper.close();
2371            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
2372            return;
2373        }
2374        final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription, isInitiator());
2375        final RtpContentMap currentContentMap = getLocalContentMap();
2376        final boolean iceRestart = currentContentMap.iceRestart(rtpContentMap);
2377        final RtpContentMap.Diff diff = currentContentMap.diff(rtpContentMap);
2378
2379        Log.d(
2380                Config.LOGTAG,
2381                id.getAccount().getJid().asBareJid()
2382                        + ": renegotiate. iceRestart="
2383                        + iceRestart
2384                        + " content id diff="
2385                        + diff);
2386
2387        if (diff.hasModifications() && iceRestart) {
2388            webRTCWrapper.close();
2389            sendSessionTerminate(
2390                    Reason.FAILED_APPLICATION,
2391                    "WebRTC unexpectedly tried to modify content and transport at once");
2392            return;
2393        }
2394
2395        if (iceRestart) {
2396            initiateIceRestart(rtpContentMap);
2397            return;
2398        } else if (diff.isEmpty()) {
2399            Log.d(
2400                    Config.LOGTAG,
2401                    "renegotiation. nothing to do. SignalingState="
2402                            + this.webRTCWrapper.getSignalingState());
2403        }
2404
2405        if (diff.added.size() > 0) {
2406            modifyLocalContentMap(rtpContentMap);
2407            sendContentAdd(rtpContentMap, diff.added);
2408        }
2409    }
2410
2411    private void initiateIceRestart(final RtpContentMap rtpContentMap) {
2412        final RtpContentMap transportInfo = rtpContentMap.transportInfo();
2413        final JinglePacket jinglePacket =
2414                transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
2415        Log.d(Config.LOGTAG, "initiating ice restart: " + jinglePacket);
2416        jinglePacket.setTo(id.with);
2417        xmppConnectionService.sendIqPacket(
2418                id.account,
2419                jinglePacket,
2420                (account, response) -> {
2421                    if (response.getType() == IqPacket.TYPE.RESULT) {
2422                        Log.d(Config.LOGTAG, "received success to our ice restart");
2423                        setLocalContentMap(rtpContentMap);
2424                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
2425                        return;
2426                    }
2427                    if (response.getType() == IqPacket.TYPE.ERROR) {
2428                        if (isTieBreak(response)) {
2429                            Log.d(Config.LOGTAG, "received tie-break as result of ice restart");
2430                            return;
2431                        }
2432                        handleIqErrorResponse(response);
2433                    }
2434                    if (response.getType() == IqPacket.TYPE.TIMEOUT) {
2435                        handleIqTimeoutResponse(response);
2436                    }
2437                });
2438    }
2439
2440    private boolean isTieBreak(final IqPacket response) {
2441        final Element error = response.findChild("error");
2442        return error != null && error.hasChild("tie-break", Namespace.JINGLE_ERRORS);
2443    }
2444
2445    private void sendContentAdd(final RtpContentMap rtpContentMap, final Collection<String> added) {
2446        final RtpContentMap contentAdd = rtpContentMap.toContentModification(added);
2447        this.outgoingContentAdd = contentAdd;
2448        final JinglePacket jinglePacket =
2449                contentAdd.toJinglePacket(JinglePacket.Action.CONTENT_ADD, id.sessionId);
2450        jinglePacket.setTo(id.with);
2451        xmppConnectionService.sendIqPacket(
2452                id.account,
2453                jinglePacket,
2454                (connection, response) -> {
2455                    if (response.getType() == IqPacket.TYPE.RESULT) {
2456                        Log.d(
2457                                Config.LOGTAG,
2458                                id.getAccount().getJid().asBareJid()
2459                                        + ": received ACK to our content-add");
2460                        return;
2461                    }
2462                    if (response.getType() == IqPacket.TYPE.ERROR) {
2463                        if (isTieBreak(response)) {
2464                            this.outgoingContentAdd = null;
2465                            Log.d(Config.LOGTAG, "received tie-break as result of our content-add");
2466                            return;
2467                        }
2468                        handleIqErrorResponse(response);
2469                    }
2470                    if (response.getType() == IqPacket.TYPE.TIMEOUT) {
2471                        handleIqTimeoutResponse(response);
2472                    }
2473                });
2474    }
2475
2476    private void setLocalContentMap(final RtpContentMap rtpContentMap) {
2477        if (isInitiator()) {
2478            this.initiatorRtpContentMap = rtpContentMap;
2479        } else {
2480            this.responderRtpContentMap = rtpContentMap;
2481        }
2482    }
2483
2484    private void setRemoteContentMap(final RtpContentMap rtpContentMap) {
2485        if (isInitiator()) {
2486            this.responderRtpContentMap = rtpContentMap;
2487        } else {
2488            this.initiatorRtpContentMap = rtpContentMap;
2489        }
2490    }
2491
2492    // this method is to be used for content map modifications that modify media
2493    private void modifyLocalContentMap(final RtpContentMap rtpContentMap) {
2494        final RtpContentMap activeContents = rtpContentMap.activeContents();
2495        setLocalContentMap(activeContents);
2496        this.webRTCWrapper.switchSpeakerPhonePreference(
2497                AppRTCAudioManager.SpeakerPhonePreference.of(activeContents.getMedia()));
2498        updateEndUserState();
2499    }
2500
2501    private SessionDescription setLocalSessionDescription()
2502            throws ExecutionException, InterruptedException {
2503        final org.webrtc.SessionDescription sessionDescription =
2504                this.webRTCWrapper.setLocalDescription().get();
2505        return SessionDescription.parse(sessionDescription.description);
2506    }
2507
2508    private void closeWebRTCSessionAfterFailedConnection() {
2509        this.webRTCWrapper.close();
2510        synchronized (this) {
2511            if (isTerminated()) {
2512                Log.d(
2513                        Config.LOGTAG,
2514                        id.account.getJid().asBareJid()
2515                                + ": no need to send session-terminate after failed connection. Other party already did");
2516                return;
2517            }
2518            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
2519        }
2520    }
2521
2522    public boolean zeroDuration() {
2523        return this.sessionDuration.elapsed(TimeUnit.NANOSECONDS) <= 0;
2524    }
2525
2526    public long getCallDuration() {
2527        return this.sessionDuration.elapsed(TimeUnit.MILLISECONDS);
2528    }
2529
2530    public AppRTCAudioManager getAudioManager() {
2531        return webRTCWrapper.getAudioManager();
2532    }
2533
2534    public boolean isMicrophoneEnabled() {
2535        return webRTCWrapper.isMicrophoneEnabled();
2536    }
2537
2538    public boolean setMicrophoneEnabled(final boolean enabled) {
2539        return webRTCWrapper.setMicrophoneEnabled(enabled);
2540    }
2541
2542    public boolean isVideoEnabled() {
2543        return webRTCWrapper.isVideoEnabled();
2544    }
2545
2546    public void setVideoEnabled(final boolean enabled) {
2547        webRTCWrapper.setVideoEnabled(enabled);
2548    }
2549
2550    public boolean isCameraSwitchable() {
2551        return webRTCWrapper.isCameraSwitchable();
2552    }
2553
2554    public boolean isFrontCamera() {
2555        return webRTCWrapper.isFrontCamera();
2556    }
2557
2558    public ListenableFuture<Boolean> switchCamera() {
2559        return webRTCWrapper.switchCamera();
2560    }
2561
2562    @Override
2563    public void onAudioDeviceChanged(
2564            AppRTCAudioManager.AudioDevice selectedAudioDevice,
2565            Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
2566        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2567                selectedAudioDevice, availableAudioDevices);
2568    }
2569
2570    private void updateEndUserState() {
2571        final RtpEndUserState endUserState = getEndUserState();
2572        jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
2573        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2574                id.account, id.with, id.sessionId, endUserState);
2575    }
2576
2577    private void updateOngoingCallNotification() {
2578        final State state = this.state;
2579        if (STATES_SHOWING_ONGOING_CALL.contains(state)) {
2580            final boolean reconnecting;
2581            if (state == State.SESSION_ACCEPTED) {
2582                reconnecting =
2583                        getPeerConnectionStateAsEndUserState() == RtpEndUserState.RECONNECTING;
2584            } else {
2585                reconnecting = false;
2586            }
2587            xmppConnectionService.setOngoingCall(id, getMedia(), reconnecting);
2588        } else {
2589            xmppConnectionService.removeOngoingCall();
2590        }
2591    }
2592
2593    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
2594        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
2595            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2596            request.setTo(id.account.getDomain());
2597            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
2598            xmppConnectionService.sendIqPacket(
2599                    id.account,
2600                    request,
2601                    (account, response) -> {
2602                        ImmutableList.Builder<PeerConnection.IceServer> listBuilder =
2603                                new ImmutableList.Builder<>();
2604                        if (response.getType() == IqPacket.TYPE.RESULT) {
2605                            final Element services =
2606                                    response.findChild(
2607                                            "services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
2608                            final List<Element> children =
2609                                    services == null
2610                                            ? Collections.emptyList()
2611                                            : services.getChildren();
2612                            for (final Element child : children) {
2613                                if ("service".equals(child.getName())) {
2614                                    final String type = child.getAttribute("type");
2615                                    final String host = child.getAttribute("host");
2616                                    final String sport = child.getAttribute("port");
2617                                    final Integer port =
2618                                            sport == null ? null : Ints.tryParse(sport);
2619                                    final String transport = child.getAttribute("transport");
2620                                    final String username = child.getAttribute("username");
2621                                    final String password = child.getAttribute("password");
2622                                    if (Strings.isNullOrEmpty(host) || port == null) {
2623                                        continue;
2624                                    }
2625                                    if (port < 0 || port > 65535) {
2626                                        continue;
2627                                    }
2628
2629
2630
2631
2632                                    if (Arrays.asList("stun", "stuns", "turn", "turns")
2633                                                    .contains(type)
2634                                            && Arrays.asList("udp", "tcp").contains(transport)) {
2635                                        if (Arrays.asList("stuns", "turns").contains(type)
2636                                                && "udp".equals(transport)) {
2637                                            Log.d(
2638                                                    Config.LOGTAG,
2639                                                    id.account.getJid().asBareJid()
2640                                                            + ": skipping invalid combination of udp/tls in external services");
2641                                            continue;
2642                                        }
2643
2644                                        // STUN URLs do not support a query section since M110
2645                                        final String uri;
2646                                        if (Arrays.asList("stun","stuns").contains(type)) {
2647                                            uri = String.format("%s:%s%s", type, IP.wrapIPv6(host),port);
2648                                        } else {
2649                                            uri = String.format(
2650                                                    "%s:%s:%s?transport=%s",
2651                                                    type,
2652                                                    IP.wrapIPv6(host),
2653                                                    port,
2654                                                    transport);
2655                                        }
2656
2657                                        final PeerConnection.IceServer.Builder iceServerBuilder =
2658                                                PeerConnection.IceServer.builder(uri);
2659                                        iceServerBuilder.setTlsCertPolicy(
2660                                                PeerConnection.TlsCertPolicy
2661                                                        .TLS_CERT_POLICY_INSECURE_NO_CHECK);
2662                                        if (username != null && password != null) {
2663                                            iceServerBuilder.setUsername(username);
2664                                            iceServerBuilder.setPassword(password);
2665                                        } else if (Arrays.asList("turn", "turns").contains(type)) {
2666                                            // The WebRTC spec requires throwing an
2667                                            // InvalidAccessError when username (from libwebrtc
2668                                            // source coder)
2669                                            // https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
2670                                            Log.d(
2671                                                    Config.LOGTAG,
2672                                                    id.account.getJid().asBareJid()
2673                                                            + ": skipping "
2674                                                            + type
2675                                                            + "/"
2676                                                            + transport
2677                                                            + " without username and password");
2678                                            continue;
2679                                        }
2680                                        final PeerConnection.IceServer iceServer =
2681                                                iceServerBuilder.createIceServer();
2682                                        Log.d(
2683                                                Config.LOGTAG,
2684                                                id.account.getJid().asBareJid()
2685                                                        + ": discovered ICE Server: "
2686                                                        + iceServer);
2687                                        listBuilder.add(iceServer);
2688                                    }
2689                                }
2690                            }
2691                        }
2692                        final List<PeerConnection.IceServer> iceServers = listBuilder.build();
2693                        if (iceServers.size() == 0) {
2694                            Log.w(
2695                                    Config.LOGTAG,
2696                                    id.account.getJid().asBareJid()
2697                                            + ": no ICE server found "
2698                                            + response);
2699                        }
2700                        onIceServersDiscovered.onIceServersDiscovered(iceServers);
2701                    });
2702        } else {
2703            Log.w(
2704                    Config.LOGTAG,
2705                    id.account.getJid().asBareJid() + ": has no external service discovery");
2706            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
2707        }
2708    }
2709
2710    private void finish() {
2711        if (isTerminated()) {
2712            this.cancelRingingTimeout();
2713            this.webRTCWrapper.verifyClosed();
2714            this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
2715            this.jingleConnectionManager.finishConnectionOrThrow(this);
2716        } else {
2717            throw new IllegalStateException(
2718                    String.format("Unable to call finish from %s", this.state));
2719        }
2720    }
2721
2722    private void writeLogMessage(final State state) {
2723        final long duration = getCallDuration();
2724        if (state == State.TERMINATED_SUCCESS
2725                || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
2726            writeLogMessageSuccess(duration);
2727        } else {
2728            writeLogMessageMissed();
2729        }
2730    }
2731
2732    private void writeLogMessageSuccess(final long duration) {
2733        this.message.setBody(new RtpSessionStatus(true, duration).toString());
2734        this.writeMessage();
2735    }
2736
2737    private void writeLogMessageMissed() {
2738        this.message.setBody(new RtpSessionStatus(false, 0).toString());
2739        this.writeMessage();
2740    }
2741
2742    private void writeMessage() {
2743        final Conversational conversational = message.getConversation();
2744        if (conversational instanceof Conversation) {
2745            ((Conversation) conversational).add(this.message);
2746            xmppConnectionService.createMessageAsync(message);
2747            xmppConnectionService.updateConversationUi();
2748        } else {
2749            throw new IllegalStateException("Somehow the conversation in a message was a stub");
2750        }
2751    }
2752
2753    public State getState() {
2754        return this.state;
2755    }
2756
2757    boolean isTerminated() {
2758        return TERMINATED.contains(this.state);
2759    }
2760
2761    public Optional<VideoTrack> getLocalVideoTrack() {
2762        return webRTCWrapper.getLocalVideoTrack();
2763    }
2764
2765    public Optional<VideoTrack> getRemoteVideoTrack() {
2766        return webRTCWrapper.getRemoteVideoTrack();
2767    }
2768
2769    public EglBase.Context getEglBaseContext() {
2770        return webRTCWrapper.getEglBaseContext();
2771    }
2772
2773    void setProposedMedia(final Set<Media> media) {
2774        this.proposedMedia = media;
2775    }
2776
2777    public void fireStateUpdate() {
2778        final RtpEndUserState endUserState = getEndUserState();
2779        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2780                id.account, id.with, id.sessionId, endUserState);
2781    }
2782
2783    public boolean isSwitchToVideoAvailable() {
2784        final boolean prerequisite =
2785                Media.audioOnly(getMedia())
2786                        && Arrays.asList(RtpEndUserState.CONNECTED, RtpEndUserState.RECONNECTING)
2787                                .contains(getEndUserState());
2788        return prerequisite && remoteHasVideoFeature();
2789    }
2790
2791    private boolean remoteHasVideoFeature() {
2792        final Contact contact = id.getContact();
2793        final Presence presence =
2794                contact.getPresences().get(Strings.nullToEmpty(id.with.getResource()));
2795        final ServiceDiscoveryResult serviceDiscoveryResult =
2796                presence == null ? null : presence.getServiceDiscoveryResult();
2797        final List<String> features =
2798                serviceDiscoveryResult == null ? null : serviceDiscoveryResult.getFeatures();
2799        return features != null && features.contains(Namespace.JINGLE_FEATURE_VIDEO);
2800    }
2801
2802    private interface OnIceServersDiscovered {
2803        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
2804    }
2805}