JingleConnectionManager.java

   1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.telecom.VideoProfile;
   4import android.util.Base64;
   5import android.util.Log;
   6
   7import com.google.common.base.Objects;
   8import com.google.common.base.Optional;
   9import com.google.common.base.Preconditions;
  10import com.google.common.cache.Cache;
  11import com.google.common.cache.CacheBuilder;
  12import com.google.common.collect.Collections2;
  13import com.google.common.collect.ComparisonChain;
  14import com.google.common.collect.ImmutableSet;
  15
  16import eu.siacs.conversations.Config;
  17import eu.siacs.conversations.entities.Account;
  18import eu.siacs.conversations.entities.Contact;
  19import eu.siacs.conversations.entities.Conversation;
  20import eu.siacs.conversations.entities.Conversational;
  21import eu.siacs.conversations.entities.Message;
  22import eu.siacs.conversations.entities.RtpSessionStatus;
  23import eu.siacs.conversations.entities.Transferable;
  24import eu.siacs.conversations.services.AbstractConnectionManager;
  25import eu.siacs.conversations.services.CallIntegration;
  26import eu.siacs.conversations.services.CallIntegrationConnectionService;
  27import eu.siacs.conversations.services.XmppConnectionService;
  28import eu.siacs.conversations.xml.Element;
  29import eu.siacs.conversations.xml.Namespace;
  30import eu.siacs.conversations.xmpp.Jid;
  31import eu.siacs.conversations.xmpp.XmppConnection;
  32import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
  33import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
  34import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  35import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  36import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  37import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  38import eu.siacs.conversations.xmpp.jingle.transports.InbandBytestreamsTransport;
  39import eu.siacs.conversations.xmpp.jingle.transports.Transport;
  40import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  41import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  42
  43import java.lang.ref.WeakReference;
  44import java.security.SecureRandom;
  45import java.util.Collection;
  46import java.util.HashMap;
  47import java.util.List;
  48import java.util.Map;
  49import java.util.Set;
  50import java.util.concurrent.ConcurrentHashMap;
  51import java.util.concurrent.Executors;
  52import java.util.concurrent.ScheduledExecutorService;
  53import java.util.concurrent.ScheduledFuture;
  54import java.util.concurrent.TimeUnit;
  55
  56public class JingleConnectionManager extends AbstractConnectionManager {
  57    public static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE =
  58            Executors.newSingleThreadScheduledExecutor();
  59    private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals =
  60            new HashMap<>();
  61    private final ConcurrentHashMap<AbstractJingleConnection.Id, AbstractJingleConnection>
  62            connections = new ConcurrentHashMap<>();
  63
  64    private final Cache<PersistableSessionId, TerminatedRtpSession> terminatedSessions =
  65            CacheBuilder.newBuilder().expireAfterWrite(24, TimeUnit.HOURS).build();
  66
  67    public JingleConnectionManager(XmppConnectionService service) {
  68        super(service);
  69    }
  70
  71    static String nextRandomId() {
  72        final byte[] id = new byte[16];
  73        new SecureRandom().nextBytes(id);
  74        return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE);
  75    }
  76
  77    public void deliverPacket(final Account account, final JinglePacket packet) {
  78        final String sessionId = packet.getSessionId();
  79        final JinglePacket.Action action = packet.getAction();
  80        if (sessionId == null) {
  81            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
  82            return;
  83        }
  84        if (action == null) {
  85            respondWithJingleError(account, packet, null, "bad-request", "cancel");
  86            return;
  87        }
  88        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, packet);
  89        final AbstractJingleConnection existingJingleConnection = connections.get(id);
  90        if (existingJingleConnection != null) {
  91            existingJingleConnection.deliverPacket(packet);
  92        } else if (action == JinglePacket.Action.SESSION_INITIATE) {
  93            final Jid from = packet.getFrom();
  94            final Content content = packet.getJingleContent();
  95            final String descriptionNamespace =
  96                    content == null ? null : content.getDescriptionNamespace();
  97            final AbstractJingleConnection connection;
  98            if (Namespace.JINGLE_APPS_FILE_TRANSFER.equals(descriptionNamespace)) {
  99                connection = new JingleFileTransferConnection(this, id, from);
 100            } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace)
 101                    && isUsingClearNet(account)) {
 102                final boolean sessionEnded =
 103                        this.terminatedSessions.asMap().containsKey(PersistableSessionId.of(id));
 104                final boolean stranger =
 105                        isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 106                final boolean busy = isBusy();
 107                if (busy || sessionEnded || stranger) {
 108                    Log.d(
 109                            Config.LOGTAG,
 110                            id.account.getJid().asBareJid()
 111                                    + ": rejected session with "
 112                                    + id.with
 113                                    + " because busy. sessionEnded="
 114                                    + sessionEnded
 115                                    + ", stranger="
 116                                    + stranger);
 117                    sendSessionTerminate(account, packet, id);
 118                    if (busy || stranger) {
 119                        writeLogMissedIncoming(
 120                                account,
 121                                id.with,
 122                                id.sessionId,
 123                                null,
 124                                System.currentTimeMillis(),
 125                                stranger);
 126                    }
 127                    return;
 128                }
 129                connection = new JingleRtpConnection(this, id, from);
 130            } else {
 131                respondWithJingleError(
 132                        account, packet, "unsupported-info", "feature-not-implemented", "cancel");
 133                return;
 134            }
 135            connections.put(id, connection);
 136            mXmppConnectionService.updateConversationUi();
 137            connection.deliverPacket(packet);
 138            if (connection instanceof JingleRtpConnection rtpConnection) {
 139                addNewIncomingCall(rtpConnection);
 140            }
 141        } else {
 142            Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
 143            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
 144        }
 145    }
 146
 147    private void addNewIncomingCall(final JingleRtpConnection rtpConnection) {
 148        if (rtpConnection.isTerminated()) {
 149            Log.d(
 150                    Config.LOGTAG,
 151                    "skip call integration because something must have gone during initiate");
 152            return;
 153        }
 154        if (CallIntegrationConnectionService.addNewIncomingCall(
 155                mXmppConnectionService, rtpConnection.getId())) {
 156            return;
 157        }
 158        rtpConnection.integrationFailure();
 159    }
 160
 161    private void sendSessionTerminate(
 162            final Account account, final IqPacket request, final AbstractJingleConnection.Id id) {
 163        mXmppConnectionService.sendIqPacket(
 164                account, request.generateResponse(IqPacket.TYPE.RESULT), null);
 165        final JinglePacket sessionTermination =
 166                new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
 167        sessionTermination.setTo(id.with);
 168        sessionTermination.setReason(Reason.BUSY, null);
 169        mXmppConnectionService.sendIqPacket(account, sessionTermination, null);
 170    }
 171
 172    private boolean isUsingClearNet(final Account account) {
 173        return !account.isOnion() && !mXmppConnectionService.useTorToConnect();
 174    }
 175
 176    public boolean isBusy() {
 177        for (final AbstractJingleConnection connection : this.connections.values()) {
 178            if (connection instanceof JingleRtpConnection rtpConnection) {
 179                if (connection.isTerminated() && rtpConnection.getCallIntegration().isDestroyed()) {
 180                    continue;
 181                }
 182                return true;
 183            }
 184        }
 185        synchronized (this.rtpSessionProposals) {
 186            return this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED)
 187                    || this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING)
 188                    || this.rtpSessionProposals.containsValue(
 189                            DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED);
 190        }
 191    }
 192
 193    public boolean hasJingleRtpConnection(final Account account) {
 194        for (AbstractJingleConnection connection : this.connections.values()) {
 195            if (connection instanceof JingleRtpConnection rtpConnection) {
 196                if (rtpConnection.isTerminated()) {
 197                    continue;
 198                }
 199                if (rtpConnection.id.account == account) {
 200                    return true;
 201                }
 202            }
 203        }
 204        return false;
 205    }
 206
 207    private Optional<RtpSessionProposal> findMatchingSessionProposal(
 208            final Account account, final Jid with, final Set<Media> media) {
 209        synchronized (this.rtpSessionProposals) {
 210            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 211                    this.rtpSessionProposals.entrySet()) {
 212                final RtpSessionProposal proposal = entry.getKey();
 213                final DeviceDiscoveryState state = entry.getValue();
 214                final boolean openProposal =
 215                        state == DeviceDiscoveryState.DISCOVERED
 216                                || state == DeviceDiscoveryState.SEARCHING
 217                                || state == DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED;
 218                if (openProposal
 219                        && proposal.account == account
 220                        && proposal.with.equals(with.asBareJid())
 221                        && proposal.media.equals(media)) {
 222                    return Optional.of(proposal);
 223                }
 224            }
 225        }
 226        return Optional.absent();
 227    }
 228
 229    private boolean hasMatchingRtpSession(
 230            final Account account, final Jid with, final Set<Media> media) {
 231        for (AbstractJingleConnection connection : this.connections.values()) {
 232            if (connection instanceof JingleRtpConnection rtpConnection) {
 233                if (rtpConnection.isTerminated()) {
 234                    continue;
 235                }
 236                if (rtpConnection.getId().account == account
 237                        && rtpConnection.getId().with.asBareJid().equals(with.asBareJid())
 238                        && rtpConnection.getMedia().equals(media)) {
 239                    return true;
 240                }
 241            }
 242        }
 243        return false;
 244    }
 245
 246    private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
 247        final boolean notifyForStrangers =
 248                mXmppConnectionService.getNotificationService().notificationsFromStrangers();
 249        if (notifyForStrangers) {
 250            return false;
 251        }
 252        final Contact contact = account.getRoster().getContact(with);
 253        return !contact.showInContactList();
 254    }
 255
 256    ScheduledFuture<?> schedule(
 257            final Runnable runnable, final long delay, final TimeUnit timeUnit) {
 258        return SCHEDULED_EXECUTOR_SERVICE.schedule(runnable, delay, timeUnit);
 259    }
 260
 261    void respondWithJingleError(
 262            final Account account,
 263            final IqPacket original,
 264            final String jingleCondition,
 265            final String condition,
 266            final String conditionType) {
 267        final IqPacket response = original.generateResponse(IqPacket.TYPE.ERROR);
 268        final Element error = response.addChild("error");
 269        error.setAttribute("type", conditionType);
 270        error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
 271        if (jingleCondition != null) {
 272            error.addChild(jingleCondition, Namespace.JINGLE_ERRORS);
 273        }
 274        account.getXmppConnection().sendIqPacket(response, null);
 275    }
 276
 277    public void deliverMessage(
 278            final Account account,
 279            final Jid to,
 280            final Jid from,
 281            final Element message,
 282            String remoteMsgId,
 283            String serverMsgId,
 284            long timestamp) {
 285        Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
 286        final String sessionId = message.getAttribute("id");
 287        if (sessionId == null) {
 288            return;
 289        }
 290        if ("accept".equals(message.getName())) {
 291            for (AbstractJingleConnection connection : connections.values()) {
 292                if (connection instanceof JingleRtpConnection rtpConnection) {
 293                    final AbstractJingleConnection.Id id = connection.getId();
 294                    if (id.account == account && id.sessionId.equals(sessionId)) {
 295                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 296                        return;
 297                    }
 298                }
 299            }
 300            return;
 301        }
 302        final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
 303        // XEP version 0.6.0 sends proceed, reject, ringing to bare jid
 304        final boolean addressedDirectly = to != null && to.equals(account.getJid());
 305        final AbstractJingleConnection.Id id;
 306        if (fromSelf) {
 307            if (to != null && to.isFullJid()) {
 308                id = AbstractJingleConnection.Id.of(account, to, sessionId);
 309            } else {
 310                return;
 311            }
 312        } else {
 313            id = AbstractJingleConnection.Id.of(account, from, sessionId);
 314        }
 315        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 316        if (existingJingleConnection != null) {
 317            if (existingJingleConnection instanceof JingleRtpConnection) {
 318                ((JingleRtpConnection) existingJingleConnection)
 319                        .deliveryMessage(from, message, serverMsgId, timestamp);
 320            } else {
 321                Log.d(
 322                        Config.LOGTAG,
 323                        account.getJid().asBareJid()
 324                                + ": "
 325                                + existingJingleConnection.getClass().getName()
 326                                + " does not support jingle messages");
 327            }
 328            return;
 329        }
 330
 331        if (fromSelf) {
 332            if ("proceed".equals(message.getName())) {
 333                final Conversation c =
 334                        mXmppConnectionService.findOrCreateConversation(
 335                                account, id.with, false, false);
 336                final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
 337                if (previousBusy != null) {
 338                    previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
 339                    if (serverMsgId != null) {
 340                        previousBusy.setServerMsgId(serverMsgId);
 341                    }
 342                    previousBusy.setTime(timestamp);
 343                    mXmppConnectionService.updateMessage(previousBusy, true);
 344                    Log.d(
 345                            Config.LOGTAG,
 346                            id.account.getJid().asBareJid()
 347                                    + ": updated previous busy because call got picked up by another device");
 348                    mXmppConnectionService.getNotificationService().clearMissedCall(previousBusy);
 349                    return;
 350                }
 351            }
 352            // TODO handle reject for cases where we don’t have carbon copies (normally reject is to
 353            // be sent to own bare jid as well)
 354            Log.d(
 355                    Config.LOGTAG,
 356                    account.getJid().asBareJid() + ": ignore jingle message from self");
 357            return;
 358        }
 359
 360        if ("propose".equals(message.getName())) {
 361            final Propose propose = Propose.upgrade(message);
 362            final List<GenericDescription> descriptions = propose.getDescriptions();
 363            final Collection<RtpDescription> rtpDescriptions =
 364                    Collections2.transform(
 365                            Collections2.filter(descriptions, d -> d instanceof RtpDescription),
 366                            input -> (RtpDescription) input);
 367            if (rtpDescriptions.size() > 0
 368                    && rtpDescriptions.size() == descriptions.size()
 369                    && isUsingClearNet(account)) {
 370                final Collection<Media> media =
 371                        Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
 372                if (media.contains(Media.UNKNOWN)) {
 373                    Log.d(
 374                            Config.LOGTAG,
 375                            account.getJid().asBareJid()
 376                                    + ": encountered unknown media in session proposal. "
 377                                    + propose);
 378                    return;
 379                }
 380                final Optional<RtpSessionProposal> matchingSessionProposal =
 381                        findMatchingSessionProposal(account, id.with, ImmutableSet.copyOf(media));
 382                if (matchingSessionProposal.isPresent()) {
 383                    final String ourSessionId = matchingSessionProposal.get().sessionId;
 384                    final String theirSessionId = id.sessionId;
 385                    if (ComparisonChain.start()
 386                                    .compare(ourSessionId, theirSessionId)
 387                                    .compare(
 388                                            account.getJid().toEscapedString(),
 389                                            id.with.toEscapedString())
 390                                    .result()
 391                            > 0) {
 392                        Log.d(
 393                                Config.LOGTAG,
 394                                account.getJid().asBareJid()
 395                                        + ": our session lost tie break. automatically accepting their session. winning Session="
 396                                        + theirSessionId);
 397                        // TODO a retract for this reason should probably include some indication of
 398                        // tie break
 399                        retractSessionProposal(matchingSessionProposal.get());
 400                        final JingleRtpConnection rtpConnection =
 401                                new JingleRtpConnection(this, id, from);
 402                        this.connections.put(id, rtpConnection);
 403                        rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 404                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 405                        addNewIncomingCall(rtpConnection);
 406                        // TODO actually do the automatic accept?!
 407                    } else {
 408                        Log.d(
 409                                Config.LOGTAG,
 410                                account.getJid().asBareJid()
 411                                        + ": our session won tie break. waiting for other party to accept. winningSession="
 412                                        + ourSessionId);
 413                        // TODO reject their session with <tie-break/>?
 414                    }
 415                    return;
 416                }
 417                final boolean stranger =
 418                        isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 419                if (isBusy() || stranger) {
 420                    writeLogMissedIncoming(
 421                            account,
 422                            id.with.asBareJid(),
 423                            id.sessionId,
 424                            serverMsgId,
 425                            timestamp,
 426                            stranger);
 427                    if (stranger) {
 428                        Log.d(
 429                                Config.LOGTAG,
 430                                id.account.getJid().asBareJid()
 431                                        + ": ignoring call proposal from stranger "
 432                                        + id.with);
 433                        return;
 434                    }
 435                    final int activeDevices = account.activeDevicesWithRtpCapability();
 436                    Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
 437                    if (activeDevices == 0) {
 438                        final MessagePacket reject =
 439                                mXmppConnectionService
 440                                        .getMessageGenerator()
 441                                        .sessionReject(from, sessionId);
 442                        mXmppConnectionService.sendMessagePacket(account, reject);
 443                    } else {
 444                        Log.d(
 445                                Config.LOGTAG,
 446                                id.account.getJid().asBareJid()
 447                                        + ": ignoring proposal because busy on this device but there are other devices");
 448                    }
 449                } else {
 450                    final JingleRtpConnection rtpConnection =
 451                            new JingleRtpConnection(this, id, from);
 452                    this.connections.put(id, rtpConnection);
 453                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 454                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 455                    addNewIncomingCall(rtpConnection);
 456                }
 457            } else {
 458                Log.d(
 459                        Config.LOGTAG,
 460                        account.getJid().asBareJid()
 461                                + ": unable to react to proposed session with "
 462                                + rtpDescriptions.size()
 463                                + " rtp descriptions of "
 464                                + descriptions.size()
 465                                + " total descriptions");
 466            }
 467        } else if (addressedDirectly && "proceed".equals(message.getName())) {
 468            synchronized (rtpSessionProposals) {
 469                final RtpSessionProposal proposal =
 470                        getRtpSessionProposal(account, from.asBareJid(), sessionId);
 471                if (proposal != null) {
 472                    rtpSessionProposals.remove(proposal);
 473                    final JingleRtpConnection rtpConnection =
 474                            new JingleRtpConnection(
 475                                    this, id, account.getJid(), proposal.callIntegration);
 476                    rtpConnection.setProposedMedia(proposal.media);
 477                    this.connections.put(id, rtpConnection);
 478                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
 479                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 480                } else {
 481                    Log.d(
 482                            Config.LOGTAG,
 483                            account.getJid().asBareJid()
 484                                    + ": no rtp session ("
 485                                    + sessionId
 486                                    + ") proposal found for "
 487                                    + from
 488                                    + " to deliver proceed");
 489                    if (remoteMsgId == null) {
 490                        return;
 491                    }
 492                    final MessagePacket errorMessage = new MessagePacket();
 493                    errorMessage.setTo(from);
 494                    errorMessage.setId(remoteMsgId);
 495                    errorMessage.setType(MessagePacket.TYPE_ERROR);
 496                    final Element error = errorMessage.addChild("error");
 497                    error.setAttribute("code", "404");
 498                    error.setAttribute("type", "cancel");
 499                    error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
 500                    mXmppConnectionService.sendMessagePacket(account, errorMessage);
 501                }
 502            }
 503        } else if (addressedDirectly && "reject".equals(message.getName())) {
 504            final RtpSessionProposal proposal =
 505                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
 506            synchronized (rtpSessionProposals) {
 507                if (proposal != null) {
 508                    rtpSessionProposals.remove(proposal);
 509                    proposal.callIntegration.busy();
 510                    writeLogMissedOutgoing(
 511                            account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
 512                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 513                            account,
 514                            proposal.with,
 515                            proposal.sessionId,
 516                            RtpEndUserState.DECLINED_OR_BUSY);
 517                } else {
 518                    Log.d(
 519                            Config.LOGTAG,
 520                            account.getJid().asBareJid()
 521                                    + ": no rtp session proposal found for "
 522                                    + from
 523                                    + " to deliver reject");
 524                }
 525            }
 526        } else if (addressedDirectly && "ringing".equals(message.getName())) {
 527            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + from + " started ringing");
 528            updateProposedSessionDiscovered(
 529                    account, from, sessionId, DeviceDiscoveryState.DISCOVERED);
 530        } else {
 531            Log.d(
 532                    Config.LOGTAG,
 533                    account.getJid()
 534                            + ": received out of order jingle message from="
 535                            + from
 536                            + ", message="
 537                            + message
 538                            + ", addressedDirectly="
 539                            + addressedDirectly);
 540        }
 541    }
 542
 543    private RtpSessionProposal getRtpSessionProposal(
 544            final Account account, Jid from, String sessionId) {
 545        for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
 546            if (rtpSessionProposal.sessionId.equals(sessionId)
 547                    && rtpSessionProposal.with.equals(from)
 548                    && rtpSessionProposal.account.getJid().equals(account.getJid())) {
 549                return rtpSessionProposal;
 550            }
 551        }
 552        return null;
 553    }
 554
 555    private void writeLogMissedOutgoing(
 556            final Account account,
 557            Jid with,
 558            final String sessionId,
 559            String serverMsgId,
 560            long timestamp) {
 561        final Conversation conversation =
 562                mXmppConnectionService.findOrCreateConversation(
 563                        account, with.asBareJid(), false, false);
 564        final Message message =
 565                new Message(conversation, Message.STATUS_SEND, Message.TYPE_RTP_SESSION, sessionId);
 566        message.setBody(new RtpSessionStatus(false, 0).toString());
 567        message.setServerMsgId(serverMsgId);
 568        message.setTime(timestamp);
 569        writeMessage(message);
 570    }
 571
 572    private void writeLogMissedIncoming(
 573            final Account account,
 574            final Jid with,
 575            final String sessionId,
 576            final String serverMsgId,
 577            final long timestamp,
 578            final boolean stranger) {
 579        final Conversation conversation =
 580                mXmppConnectionService.findOrCreateConversation(
 581                        account, with.asBareJid(), false, false);
 582        final Message message =
 583                new Message(
 584                        conversation, Message.STATUS_RECEIVED, Message.TYPE_RTP_SESSION, sessionId);
 585        message.setBody(new RtpSessionStatus(false, 0).toString());
 586        message.setServerMsgId(serverMsgId);
 587        message.setTime(timestamp);
 588        message.setCounterpart(with);
 589        writeMessage(message);
 590        if (stranger) {
 591            return;
 592        }
 593        mXmppConnectionService.getNotificationService().pushMissedCallNow(message);
 594    }
 595
 596    private void writeMessage(final Message message) {
 597        final Conversational conversational = message.getConversation();
 598        if (conversational instanceof Conversation) {
 599            ((Conversation) conversational).add(message);
 600            mXmppConnectionService.databaseBackend.createMessage(message);
 601            mXmppConnectionService.updateConversationUi();
 602        } else {
 603            throw new IllegalStateException("Somehow the conversation in a message was a stub");
 604        }
 605    }
 606
 607    public void startJingleFileTransfer(final Message message) {
 608        Preconditions.checkArgument(
 609                message.isFileOrImage(), "Message is not of type file or image");
 610        final Transferable old = message.getTransferable();
 611        if (old != null) {
 612            old.cancel();
 613        }
 614        final JingleFileTransferConnection connection =
 615                new JingleFileTransferConnection(this, message);
 616        this.connections.put(connection.getId(), connection);
 617        connection.sendSessionInitialize();
 618    }
 619
 620    public Optional<OngoingRtpSession> getOngoingRtpConnection(final Contact contact) {
 621        for (final Map.Entry<AbstractJingleConnection.Id, AbstractJingleConnection> entry :
 622                this.connections.entrySet()) {
 623            if (entry.getValue() instanceof JingleRtpConnection jingleRtpConnection) {
 624                final AbstractJingleConnection.Id id = entry.getKey();
 625                if (id.account == contact.getAccount()
 626                        && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
 627                    return Optional.of(jingleRtpConnection);
 628                }
 629            }
 630        }
 631        synchronized (this.rtpSessionProposals) {
 632            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 633                    this.rtpSessionProposals.entrySet()) {
 634                final RtpSessionProposal proposal = entry.getKey();
 635                if (proposal.account == contact.getAccount()
 636                        && contact.getJid().asBareJid().equals(proposal.with)) {
 637                    final DeviceDiscoveryState preexistingState = entry.getValue();
 638                    if (preexistingState != null
 639                            && preexistingState != DeviceDiscoveryState.FAILED) {
 640                        return Optional.of(proposal);
 641                    }
 642                }
 643            }
 644        }
 645        return Optional.absent();
 646    }
 647
 648    void finishConnectionOrThrow(final AbstractJingleConnection connection) {
 649        final AbstractJingleConnection.Id id = connection.getId();
 650        if (this.connections.remove(id) == null) {
 651            throw new IllegalStateException(
 652                    String.format("Unable to finish connection with id=%s", id));
 653        }
 654        // update chat UI to remove 'ongoing call' icon
 655        mXmppConnectionService.updateConversationUi();
 656    }
 657
 658    public boolean fireJingleRtpConnectionStateUpdates() {
 659        for (final AbstractJingleConnection connection : this.connections.values()) {
 660            if (connection instanceof JingleRtpConnection jingleRtpConnection) {
 661                if (jingleRtpConnection.isTerminated()) {
 662                    continue;
 663                }
 664                jingleRtpConnection.fireStateUpdate();
 665                return true;
 666            }
 667        }
 668        return false;
 669    }
 670
 671    public void retractSessionProposal(final Account account, final Jid with) {
 672        synchronized (this.rtpSessionProposals) {
 673            RtpSessionProposal matchingProposal = null;
 674            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
 675                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 676                    matchingProposal = proposal;
 677                    break;
 678                }
 679            }
 680            if (matchingProposal != null) {
 681                retractSessionProposal(matchingProposal, false);
 682            }
 683        }
 684    }
 685
 686    private void retractSessionProposal(final RtpSessionProposal rtpSessionProposal) {
 687        retractSessionProposal(rtpSessionProposal, true);
 688    }
 689
 690    private void retractSessionProposal(
 691            final RtpSessionProposal rtpSessionProposal, final boolean refresh) {
 692        final Account account = rtpSessionProposal.account;
 693        Log.d(
 694                Config.LOGTAG,
 695                account.getJid().asBareJid()
 696                        + ": retracting rtp session proposal with "
 697                        + rtpSessionProposal.with);
 698        this.rtpSessionProposals.remove(rtpSessionProposal);
 699        rtpSessionProposal.callIntegration.retracted();
 700        if (refresh) {
 701            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 702                    account,
 703                    rtpSessionProposal.with,
 704                    rtpSessionProposal.sessionId,
 705                    RtpEndUserState.RETRACTED);
 706        }
 707        final MessagePacket messagePacket =
 708                mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
 709        writeLogMissedOutgoing(
 710                account,
 711                rtpSessionProposal.with,
 712                rtpSessionProposal.sessionId,
 713                null,
 714                System.currentTimeMillis());
 715        mXmppConnectionService.sendMessagePacket(account, messagePacket);
 716    }
 717
 718    public JingleRtpConnection initializeRtpSession(
 719            final Account account, final Jid with, final Set<Media> media) {
 720        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
 721        final JingleRtpConnection rtpConnection =
 722                new JingleRtpConnection(this, id, account.getJid());
 723        rtpConnection.setProposedMedia(media);
 724        this.connections.put(id, rtpConnection);
 725        rtpConnection.sendSessionInitiate();
 726        return rtpConnection;
 727    }
 728
 729    public RtpSessionProposal proposeJingleRtpSession(
 730            final Account account, final Jid with, final Set<Media> media) {
 731        synchronized (this.rtpSessionProposals) {
 732            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 733                    this.rtpSessionProposals.entrySet()) {
 734                final RtpSessionProposal proposal = entry.getKey();
 735                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 736                    final DeviceDiscoveryState preexistingState = entry.getValue();
 737                    if (preexistingState != null
 738                            && preexistingState != DeviceDiscoveryState.FAILED) {
 739                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
 740                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 741                                account, with, proposal.sessionId, endUserState);
 742                        return proposal;
 743                    }
 744                }
 745            }
 746            if (isBusy()) {
 747                if (hasMatchingRtpSession(account, with, media)) {
 748                    Log.d(
 749                            Config.LOGTAG,
 750                            "ignoring request to propose jingle session because the other party already created one for us");
 751                    // TODO return something that we can parse the connection of of
 752                    return null;
 753                }
 754                throw new IllegalStateException(
 755                        "There is already a running RTP session. This should have been caught by the UI");
 756            }
 757            final CallIntegration callIntegration =
 758                    new CallIntegration(mXmppConnectionService.getApplicationContext());
 759            callIntegration.setVideoState(
 760                    Media.audioOnly(media)
 761                            ? VideoProfile.STATE_AUDIO_ONLY
 762                            : VideoProfile.STATE_BIDIRECTIONAL);
 763            callIntegration.setInitialAudioDevice(CallIntegration.initialAudioDevice(media));
 764            final RtpSessionProposal proposal =
 765                    RtpSessionProposal.of(account, with.asBareJid(), media, callIntegration);
 766            callIntegration.setCallback(new ProposalStateCallback(proposal));
 767            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
 768            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 769                    account, proposal.with, proposal.sessionId, RtpEndUserState.FINDING_DEVICE);
 770            final MessagePacket messagePacket =
 771                    mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 772            mXmppConnectionService.sendMessagePacket(account, messagePacket);
 773            return proposal;
 774        }
 775    }
 776
 777    public void sendJingleMessageFinish(
 778            final Contact contact, final String sessionId, final Reason reason) {
 779        final var account = contact.getAccount();
 780        final MessagePacket messagePacket =
 781                mXmppConnectionService
 782                        .getMessageGenerator()
 783                        .sessionFinish(contact.getJid(), sessionId, reason);
 784        mXmppConnectionService.sendMessagePacket(account, messagePacket);
 785    }
 786
 787    public Optional<RtpSessionProposal> matchingProposal(final Account account, final Jid with) {
 788        synchronized (this.rtpSessionProposals) {
 789            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 790                    this.rtpSessionProposals.entrySet()) {
 791                final RtpSessionProposal proposal = entry.getKey();
 792                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 793                    return Optional.of(proposal);
 794                }
 795            }
 796        }
 797        return Optional.absent();
 798    }
 799
 800    public boolean hasMatchingProposal(final Account account, final Jid with) {
 801        synchronized (this.rtpSessionProposals) {
 802            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 803                    this.rtpSessionProposals.entrySet()) {
 804                final var state = entry.getValue();
 805                final RtpSessionProposal proposal = entry.getKey();
 806                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 807                    // CallIntegrationConnectionService starts RtpSessionActivity with ACTION_VIEW
 808                    // and an EXTRA_LAST_REPORTED_STATE of DISCOVERING devices. however due to
 809                    // possible race conditions the state might have already moved on so we are
 810                    // going
 811                    // to update the UI
 812                    final RtpEndUserState endUserState = state.toEndUserState();
 813                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 814                            account, proposal.with, proposal.sessionId, endUserState);
 815                    return true;
 816                }
 817            }
 818        }
 819        return false;
 820    }
 821
 822    public void deliverIbbPacket(final Account account, final IqPacket packet) {
 823        final String sid;
 824        final Element payload;
 825        final InbandBytestreamsTransport.PacketType packetType;
 826        if (packet.hasChild("open", Namespace.IBB)) {
 827            packetType = InbandBytestreamsTransport.PacketType.OPEN;
 828            payload = packet.findChild("open", Namespace.IBB);
 829            sid = payload.getAttribute("sid");
 830        } else if (packet.hasChild("data", Namespace.IBB)) {
 831            packetType = InbandBytestreamsTransport.PacketType.DATA;
 832            payload = packet.findChild("data", Namespace.IBB);
 833            sid = payload.getAttribute("sid");
 834        } else if (packet.hasChild("close", Namespace.IBB)) {
 835            packetType = InbandBytestreamsTransport.PacketType.CLOSE;
 836            payload = packet.findChild("close", Namespace.IBB);
 837            sid = payload.getAttribute("sid");
 838        } else {
 839            packetType = null;
 840            payload = null;
 841            sid = null;
 842        }
 843        if (sid == null) {
 844            Log.d(
 845                    Config.LOGTAG,
 846                    account.getJid().asBareJid() + ": unable to deliver ibb packet. missing sid");
 847            account.getXmppConnection()
 848                    .sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
 849            return;
 850        }
 851        for (final AbstractJingleConnection connection : this.connections.values()) {
 852            if (connection instanceof JingleFileTransferConnection fileTransfer) {
 853                final Transport transport = fileTransfer.getTransport();
 854                if (transport instanceof InbandBytestreamsTransport inBandTransport) {
 855                    if (sid.equals(inBandTransport.getStreamId())) {
 856                        if (inBandTransport.deliverPacket(packetType, packet.getFrom(), payload)) {
 857                            account.getXmppConnection()
 858                                    .sendIqPacket(
 859                                            packet.generateResponse(IqPacket.TYPE.RESULT), null);
 860                        } else {
 861                            account.getXmppConnection()
 862                                    .sendIqPacket(
 863                                            packet.generateResponse(IqPacket.TYPE.ERROR), null);
 864                        }
 865                        return;
 866                    }
 867                }
 868            }
 869        }
 870        Log.d(
 871                Config.LOGTAG,
 872                account.getJid().asBareJid() + ": unable to deliver ibb packet with sid=" + sid);
 873        account.getXmppConnection()
 874                .sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
 875    }
 876
 877    public void notifyRebound(final Account account) {
 878        for (final AbstractJingleConnection connection : this.connections.values()) {
 879            connection.notifyRebound();
 880        }
 881        final XmppConnection xmppConnection = account.getXmppConnection();
 882        if (xmppConnection != null && xmppConnection.getFeatures().sm()) {
 883            resendSessionProposals(account);
 884        }
 885    }
 886
 887    public WeakReference<JingleRtpConnection> findJingleRtpConnection(
 888            Account account, Jid with, String sessionId) {
 889        final AbstractJingleConnection.Id id =
 890                AbstractJingleConnection.Id.of(account, with, sessionId);
 891        final AbstractJingleConnection connection = connections.get(id);
 892        if (connection instanceof JingleRtpConnection) {
 893            return new WeakReference<>((JingleRtpConnection) connection);
 894        }
 895        return null;
 896    }
 897
 898    public JingleRtpConnection findJingleRtpConnection(final Account account, final Jid with) {
 899        for (final AbstractJingleConnection connection : this.connections.values()) {
 900            if (connection instanceof JingleRtpConnection rtpConnection) {
 901                if (rtpConnection.isTerminated()) {
 902                    continue;
 903                }
 904                final var id = rtpConnection.getId();
 905                if (id.account == account && account.getJid().equals(with)) {
 906                    return rtpConnection;
 907                }
 908            }
 909        }
 910        return null;
 911    }
 912
 913    private void resendSessionProposals(final Account account) {
 914        synchronized (this.rtpSessionProposals) {
 915            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 916                    this.rtpSessionProposals.entrySet()) {
 917                final RtpSessionProposal proposal = entry.getKey();
 918                if (entry.getValue() == DeviceDiscoveryState.SEARCHING
 919                        && proposal.account == account) {
 920                    Log.d(
 921                            Config.LOGTAG,
 922                            account.getJid().asBareJid()
 923                                    + ": resending session proposal to "
 924                                    + proposal.with);
 925                    final MessagePacket messagePacket =
 926                            mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 927                    mXmppConnectionService.sendMessagePacket(account, messagePacket);
 928                }
 929            }
 930        }
 931    }
 932
 933    public void updateProposedSessionDiscovered(
 934            Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
 935        synchronized (this.rtpSessionProposals) {
 936            final RtpSessionProposal sessionProposal =
 937                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
 938            final DeviceDiscoveryState currentState =
 939                    sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
 940            if (currentState == null) {
 941                Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
 942                return;
 943            }
 944            if (currentState == DeviceDiscoveryState.DISCOVERED) {
 945                Log.d(
 946                        Config.LOGTAG,
 947                        "session proposal already at discovered. not going to fall back");
 948                return;
 949            }
 950            this.rtpSessionProposals.put(sessionProposal, target);
 951            final RtpEndUserState endUserState = target.toEndUserState();
 952            if (endUserState == RtpEndUserState.RINGING) {
 953                sessionProposal.callIntegration.setDialing();
 954            }
 955            // toneManager.transition(endUserState, sessionProposal.media);
 956            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 957                    account, sessionProposal.with, sessionProposal.sessionId, endUserState);
 958            Log.d(
 959                    Config.LOGTAG,
 960                    account.getJid().asBareJid()
 961                            + ": flagging session "
 962                            + sessionId
 963                            + " as "
 964                            + target);
 965        }
 966    }
 967
 968    public void rejectRtpSession(final String sessionId) {
 969        for (final AbstractJingleConnection connection : this.connections.values()) {
 970            if (connection.getId().sessionId.equals(sessionId)) {
 971                if (connection instanceof JingleRtpConnection) {
 972                    try {
 973                        ((JingleRtpConnection) connection).rejectCall();
 974                        return;
 975                    } catch (final IllegalStateException e) {
 976                        Log.w(
 977                                Config.LOGTAG,
 978                                "race condition on rejecting call from notification",
 979                                e);
 980                    }
 981                }
 982            }
 983        }
 984    }
 985
 986    public void endRtpSession(final String sessionId) {
 987        for (final AbstractJingleConnection connection : this.connections.values()) {
 988            if (connection.getId().sessionId.equals(sessionId)) {
 989                if (connection instanceof JingleRtpConnection) {
 990                    ((JingleRtpConnection) connection).endCall();
 991                }
 992            }
 993        }
 994    }
 995
 996    public void failProceed(
 997            Account account, final Jid with, final String sessionId, final String message) {
 998        final AbstractJingleConnection.Id id =
 999                AbstractJingleConnection.Id.of(account, with, sessionId);
1000        final AbstractJingleConnection existingJingleConnection = connections.get(id);
1001        if (existingJingleConnection instanceof JingleRtpConnection) {
1002            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed(message);
1003        }
1004    }
1005
1006    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
1007        if (connections.containsValue(connection)) {
1008            return;
1009        }
1010        final IllegalStateException e =
1011                new IllegalStateException(
1012                        "JingleConnection has not been registered with connection manager");
1013        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
1014        throw e;
1015    }
1016
1017    void setTerminalSessionState(
1018            AbstractJingleConnection.Id id, final RtpEndUserState state, final Set<Media> media) {
1019        this.terminatedSessions.put(
1020                PersistableSessionId.of(id), new TerminatedRtpSession(state, media));
1021    }
1022
1023    public TerminatedRtpSession getTerminalSessionState(final Jid with, final String sessionId) {
1024        return this.terminatedSessions.getIfPresent(new PersistableSessionId(with, sessionId));
1025    }
1026
1027    private static class PersistableSessionId {
1028        private final Jid with;
1029        private final String sessionId;
1030
1031        private PersistableSessionId(Jid with, String sessionId) {
1032            this.with = with;
1033            this.sessionId = sessionId;
1034        }
1035
1036        public static PersistableSessionId of(AbstractJingleConnection.Id id) {
1037            return new PersistableSessionId(id.with, id.sessionId);
1038        }
1039
1040        @Override
1041        public boolean equals(Object o) {
1042            if (this == o) return true;
1043            if (o == null || getClass() != o.getClass()) return false;
1044            PersistableSessionId that = (PersistableSessionId) o;
1045            return Objects.equal(with, that.with) && Objects.equal(sessionId, that.sessionId);
1046        }
1047
1048        @Override
1049        public int hashCode() {
1050            return Objects.hashCode(with, sessionId);
1051        }
1052    }
1053
1054    public static class TerminatedRtpSession {
1055        public final RtpEndUserState state;
1056        public final Set<Media> media;
1057
1058        TerminatedRtpSession(RtpEndUserState state, Set<Media> media) {
1059            this.state = state;
1060            this.media = media;
1061        }
1062    }
1063
1064    public enum DeviceDiscoveryState {
1065        SEARCHING,
1066        SEARCHING_ACKNOWLEDGED,
1067        DISCOVERED,
1068        FAILED;
1069
1070        public RtpEndUserState toEndUserState() {
1071            return switch (this) {
1072                case SEARCHING, SEARCHING_ACKNOWLEDGED -> RtpEndUserState.FINDING_DEVICE;
1073                case DISCOVERED -> RtpEndUserState.RINGING;
1074                default -> RtpEndUserState.CONNECTIVITY_ERROR;
1075            };
1076        }
1077    }
1078
1079    public static class RtpSessionProposal implements OngoingRtpSession {
1080        public final Jid with;
1081        public final String sessionId;
1082        public final Set<Media> media;
1083        private final Account account;
1084        private final CallIntegration callIntegration;
1085
1086        private RtpSessionProposal(
1087                Account account,
1088                Jid with,
1089                String sessionId,
1090                Set<Media> media,
1091                final CallIntegration callIntegration) {
1092            this.account = account;
1093            this.with = with;
1094            this.sessionId = sessionId;
1095            this.media = media;
1096            this.callIntegration = callIntegration;
1097        }
1098
1099        public static RtpSessionProposal of(
1100                Account account,
1101                Jid with,
1102                Set<Media> media,
1103                final CallIntegration callIntegration) {
1104            return new RtpSessionProposal(account, with, nextRandomId(), media, callIntegration);
1105        }
1106
1107        @Override
1108        public boolean equals(Object o) {
1109            if (this == o) return true;
1110            if (o == null || getClass() != o.getClass()) return false;
1111            RtpSessionProposal proposal = (RtpSessionProposal) o;
1112            return Objects.equal(account.getJid(), proposal.account.getJid())
1113                    && Objects.equal(with, proposal.with)
1114                    && Objects.equal(sessionId, proposal.sessionId);
1115        }
1116
1117        @Override
1118        public int hashCode() {
1119            return Objects.hashCode(account.getJid(), with, sessionId);
1120        }
1121
1122        @Override
1123        public Account getAccount() {
1124            return account;
1125        }
1126
1127        @Override
1128        public Jid getWith() {
1129            return with;
1130        }
1131
1132        @Override
1133        public String getSessionId() {
1134            return sessionId;
1135        }
1136
1137        @Override
1138        public CallIntegration getCallIntegration() {
1139            return this.callIntegration;
1140        }
1141
1142        @Override
1143        public Set<Media> getMedia() {
1144            return this.media;
1145        }
1146    }
1147
1148    public class ProposalStateCallback implements CallIntegration.Callback {
1149
1150        private final RtpSessionProposal proposal;
1151
1152        public ProposalStateCallback(final RtpSessionProposal proposal) {
1153            this.proposal = proposal;
1154        }
1155
1156        @Override
1157        public void onCallIntegrationShowIncomingCallUi() {}
1158
1159        @Override
1160        public void onCallIntegrationDisconnect() {
1161            Log.d(Config.LOGTAG, "a phone call has just been started. retracting proposal");
1162            retractSessionProposal(this.proposal);
1163        }
1164
1165        @Override
1166        public void onAudioDeviceChanged(
1167                final CallIntegration.AudioDevice selectedAudioDevice,
1168                final Set<CallIntegration.AudioDevice> availableAudioDevices) {
1169            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
1170                    selectedAudioDevice, availableAudioDevices);
1171        }
1172
1173        @Override
1174        public void onCallIntegrationReject() {}
1175
1176        @Override
1177        public void onCallIntegrationAnswer() {}
1178
1179        @Override
1180        public void onCallIntegrationSilence() {}
1181    }
1182}