JingleRtpConnection.java

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