JingleConnectionManager.java

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