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        boolean firedUpdates = false;
 640        for (final AbstractJingleConnection connection : this.connections.values()) {
 641            if (connection instanceof JingleRtpConnection jingleRtpConnection) {
 642                if (jingleRtpConnection.isTerminated()) {
 643                    continue;
 644                }
 645                jingleRtpConnection.fireStateUpdate();
 646                firedUpdates = true;
 647            }
 648        }
 649        return firedUpdates;
 650    }
 651
 652    public void retractSessionProposal(final Account account, final Jid with) {
 653        synchronized (this.rtpSessionProposals) {
 654            RtpSessionProposal matchingProposal = null;
 655            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
 656                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 657                    matchingProposal = proposal;
 658                    break;
 659                }
 660            }
 661            if (matchingProposal != null) {
 662                retractSessionProposal(matchingProposal);
 663            }
 664        }
 665    }
 666
 667    private void retractSessionProposal(RtpSessionProposal rtpSessionProposal) {
 668        final Account account = rtpSessionProposal.account;
 669        toneManager.transition(RtpEndUserState.ENDED, rtpSessionProposal.media);
 670        Log.d(
 671                Config.LOGTAG,
 672                account.getJid().asBareJid()
 673                        + ": retracting rtp session proposal with "
 674                        + rtpSessionProposal.with);
 675        this.rtpSessionProposals.remove(rtpSessionProposal);
 676        rtpSessionProposal.callIntegration.retracted();
 677        final MessagePacket messagePacket =
 678                mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
 679        writeLogMissedOutgoing(
 680                account,
 681                rtpSessionProposal.with,
 682                rtpSessionProposal.sessionId,
 683                null,
 684                System.currentTimeMillis());
 685        mXmppConnectionService.sendMessagePacket(account, messagePacket);
 686    }
 687
 688    public JingleRtpConnection initializeRtpSession(
 689            final Account account, final Jid with, final Set<Media> media) {
 690        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
 691        final JingleRtpConnection rtpConnection =
 692                new JingleRtpConnection(this, id, account.getJid());
 693        rtpConnection.setProposedMedia(media);
 694        this.connections.put(id, rtpConnection);
 695        rtpConnection.sendSessionInitiate();
 696        return rtpConnection;
 697    }
 698
 699    public RtpSessionProposal proposeJingleRtpSession(
 700            final Account account, final Jid with, final Set<Media> media) {
 701        synchronized (this.rtpSessionProposals) {
 702            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 703                    this.rtpSessionProposals.entrySet()) {
 704                final RtpSessionProposal proposal = entry.getKey();
 705                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 706                    final DeviceDiscoveryState preexistingState = entry.getValue();
 707                    if (preexistingState != null
 708                            && preexistingState != DeviceDiscoveryState.FAILED) {
 709                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
 710                        toneManager.transition(endUserState, media);
 711                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 712                                account, with, proposal.sessionId, endUserState);
 713                        return proposal;
 714                    }
 715                }
 716            }
 717            if (isBusy()) {
 718                if (hasMatchingRtpSession(account, with, media)) {
 719                    Log.d(
 720                            Config.LOGTAG,
 721                            "ignoring request to propose jingle session because the other party already created one for us");
 722                    // TODO return something that we can parse the connection of of
 723                    return null;
 724                }
 725                throw new IllegalStateException(
 726                        "There is already a running RTP session. This should have been caught by the UI");
 727            }
 728            final CallIntegration callIntegration =
 729                    new CallIntegration(mXmppConnectionService.getApplicationContext());
 730            callIntegration.setInitialAudioDevice(CallIntegration.initialAudioDevice(media));
 731            final RtpSessionProposal proposal =
 732                    RtpSessionProposal.of(account, with.asBareJid(), media, callIntegration);
 733            callIntegration.setCallback(new ProposalStateCallback(proposal));
 734            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
 735            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 736                    account, proposal.with, proposal.sessionId, RtpEndUserState.FINDING_DEVICE);
 737            final MessagePacket messagePacket =
 738                    mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 739            mXmppConnectionService.sendMessagePacket(account, messagePacket);
 740            return proposal;
 741        }
 742    }
 743
 744    public boolean hasMatchingProposal(final Account account, final Jid with) {
 745        synchronized (this.rtpSessionProposals) {
 746            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 747                    this.rtpSessionProposals.entrySet()) {
 748                final RtpSessionProposal proposal = entry.getKey();
 749                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 750                    return true;
 751                }
 752            }
 753        }
 754        return false;
 755    }
 756
 757    public void deliverIbbPacket(final Account account, final IqPacket packet) {
 758        final String sid;
 759        final Element payload;
 760        final InbandBytestreamsTransport.PacketType packetType;
 761        if (packet.hasChild("open", Namespace.IBB)) {
 762            packetType = InbandBytestreamsTransport.PacketType.OPEN;
 763            payload = packet.findChild("open", Namespace.IBB);
 764            sid = payload.getAttribute("sid");
 765        } else if (packet.hasChild("data", Namespace.IBB)) {
 766            packetType = InbandBytestreamsTransport.PacketType.DATA;
 767            payload = packet.findChild("data", Namespace.IBB);
 768            sid = payload.getAttribute("sid");
 769        } else if (packet.hasChild("close", Namespace.IBB)) {
 770            packetType = InbandBytestreamsTransport.PacketType.CLOSE;
 771            payload = packet.findChild("close", Namespace.IBB);
 772            sid = payload.getAttribute("sid");
 773        } else {
 774            packetType = null;
 775            payload = null;
 776            sid = null;
 777        }
 778        if (sid == null) {
 779            Log.d(
 780                    Config.LOGTAG,
 781                    account.getJid().asBareJid() + ": unable to deliver ibb packet. missing sid");
 782            account.getXmppConnection()
 783                    .sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
 784            return;
 785        }
 786        for (final AbstractJingleConnection connection : this.connections.values()) {
 787            if (connection instanceof JingleFileTransferConnection fileTransfer) {
 788                final Transport transport = fileTransfer.getTransport();
 789                if (transport instanceof InbandBytestreamsTransport inBandTransport) {
 790                    if (sid.equals(inBandTransport.getStreamId())) {
 791                        if (inBandTransport.deliverPacket(packetType, packet.getFrom(), payload)) {
 792                            account.getXmppConnection()
 793                                    .sendIqPacket(
 794                                            packet.generateResponse(IqPacket.TYPE.RESULT), null);
 795                        } else {
 796                            account.getXmppConnection()
 797                                    .sendIqPacket(
 798                                            packet.generateResponse(IqPacket.TYPE.ERROR), null);
 799                        }
 800                        return;
 801                    }
 802                }
 803            }
 804        }
 805        Log.d(
 806                Config.LOGTAG,
 807                account.getJid().asBareJid() + ": unable to deliver ibb packet with sid=" + sid);
 808        account.getXmppConnection()
 809                .sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
 810    }
 811
 812    public void notifyRebound(final Account account) {
 813        for (final AbstractJingleConnection connection : this.connections.values()) {
 814            connection.notifyRebound();
 815        }
 816        final XmppConnection xmppConnection = account.getXmppConnection();
 817        if (xmppConnection != null && xmppConnection.getFeatures().sm()) {
 818            resendSessionProposals(account);
 819        }
 820    }
 821
 822    public WeakReference<JingleRtpConnection> findJingleRtpConnection(
 823            Account account, Jid with, String sessionId) {
 824        final AbstractJingleConnection.Id id =
 825                AbstractJingleConnection.Id.of(account, with, sessionId);
 826        final AbstractJingleConnection connection = connections.get(id);
 827        if (connection instanceof JingleRtpConnection) {
 828            return new WeakReference<>((JingleRtpConnection) connection);
 829        }
 830        return null;
 831    }
 832
 833    public JingleRtpConnection findJingleRtpConnection(final Account account, final Jid with) {
 834        for (final AbstractJingleConnection connection : this.connections.values()) {
 835            if (connection instanceof JingleRtpConnection rtpConnection) {
 836                if (rtpConnection.isTerminated()) {
 837                    continue;
 838                }
 839                final var id = rtpConnection.getId();
 840                if (id.account == account && account.getJid().equals(with)) {
 841                    return rtpConnection;
 842                }
 843            }
 844        }
 845        return null;
 846    }
 847
 848    private void resendSessionProposals(final Account account) {
 849        synchronized (this.rtpSessionProposals) {
 850            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 851                    this.rtpSessionProposals.entrySet()) {
 852                final RtpSessionProposal proposal = entry.getKey();
 853                if (entry.getValue() == DeviceDiscoveryState.SEARCHING
 854                        && proposal.account == account) {
 855                    Log.d(
 856                            Config.LOGTAG,
 857                            account.getJid().asBareJid()
 858                                    + ": resending session proposal to "
 859                                    + proposal.with);
 860                    final MessagePacket messagePacket =
 861                            mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 862                    mXmppConnectionService.sendMessagePacket(account, messagePacket);
 863                }
 864            }
 865        }
 866    }
 867
 868    public void updateProposedSessionDiscovered(
 869            Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
 870        synchronized (this.rtpSessionProposals) {
 871            final RtpSessionProposal sessionProposal =
 872                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
 873            final DeviceDiscoveryState currentState =
 874                    sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
 875            if (currentState == null) {
 876                Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
 877                return;
 878            }
 879            if (currentState == DeviceDiscoveryState.DISCOVERED) {
 880                Log.d(
 881                        Config.LOGTAG,
 882                        "session proposal already at discovered. not going to fall back");
 883                return;
 884            }
 885            this.rtpSessionProposals.put(sessionProposal, target);
 886            final RtpEndUserState endUserState = target.toEndUserState();
 887            if (endUserState == RtpEndUserState.RINGING) {
 888                sessionProposal.callIntegration.setDialing();
 889            }
 890            // toneManager.transition(endUserState, sessionProposal.media);
 891            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 892                    account, sessionProposal.with, sessionProposal.sessionId, endUserState);
 893            Log.d(
 894                    Config.LOGTAG,
 895                    account.getJid().asBareJid()
 896                            + ": flagging session "
 897                            + sessionId
 898                            + " as "
 899                            + target);
 900        }
 901    }
 902
 903    public void rejectRtpSession(final String sessionId) {
 904        for (final AbstractJingleConnection connection : this.connections.values()) {
 905            if (connection.getId().sessionId.equals(sessionId)) {
 906                if (connection instanceof JingleRtpConnection) {
 907                    try {
 908                        ((JingleRtpConnection) connection).rejectCall();
 909                        return;
 910                    } catch (final IllegalStateException e) {
 911                        Log.w(
 912                                Config.LOGTAG,
 913                                "race condition on rejecting call from notification",
 914                                e);
 915                    }
 916                }
 917            }
 918        }
 919    }
 920
 921    public void endRtpSession(final String sessionId) {
 922        for (final AbstractJingleConnection connection : this.connections.values()) {
 923            if (connection.getId().sessionId.equals(sessionId)) {
 924                if (connection instanceof JingleRtpConnection) {
 925                    ((JingleRtpConnection) connection).endCall();
 926                }
 927            }
 928        }
 929    }
 930
 931    public void failProceed(
 932            Account account, final Jid with, final String sessionId, final String message) {
 933        final AbstractJingleConnection.Id id =
 934                AbstractJingleConnection.Id.of(account, with, sessionId);
 935        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 936        if (existingJingleConnection instanceof JingleRtpConnection) {
 937            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed(message);
 938        }
 939    }
 940
 941    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
 942        if (connections.containsValue(connection)) {
 943            return;
 944        }
 945        final IllegalStateException e =
 946                new IllegalStateException(
 947                        "JingleConnection has not been registered with connection manager");
 948        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
 949        throw e;
 950    }
 951
 952    void setTerminalSessionState(
 953            AbstractJingleConnection.Id id, final RtpEndUserState state, final Set<Media> media) {
 954        this.terminatedSessions.put(
 955                PersistableSessionId.of(id), new TerminatedRtpSession(state, media));
 956    }
 957
 958    public TerminatedRtpSession getTerminalSessionState(final Jid with, final String sessionId) {
 959        return this.terminatedSessions.getIfPresent(new PersistableSessionId(with, sessionId));
 960    }
 961
 962    private static class PersistableSessionId {
 963        private final Jid with;
 964        private final String sessionId;
 965
 966        private PersistableSessionId(Jid with, String sessionId) {
 967            this.with = with;
 968            this.sessionId = sessionId;
 969        }
 970
 971        public static PersistableSessionId of(AbstractJingleConnection.Id id) {
 972            return new PersistableSessionId(id.with, id.sessionId);
 973        }
 974
 975        @Override
 976        public boolean equals(Object o) {
 977            if (this == o) return true;
 978            if (o == null || getClass() != o.getClass()) return false;
 979            PersistableSessionId that = (PersistableSessionId) o;
 980            return Objects.equal(with, that.with) && Objects.equal(sessionId, that.sessionId);
 981        }
 982
 983        @Override
 984        public int hashCode() {
 985            return Objects.hashCode(with, sessionId);
 986        }
 987    }
 988
 989    public static class TerminatedRtpSession {
 990        public final RtpEndUserState state;
 991        public final Set<Media> media;
 992
 993        TerminatedRtpSession(RtpEndUserState state, Set<Media> media) {
 994            this.state = state;
 995            this.media = media;
 996        }
 997    }
 998
 999    public enum DeviceDiscoveryState {
1000        SEARCHING,
1001        SEARCHING_ACKNOWLEDGED,
1002        DISCOVERED,
1003        FAILED;
1004
1005        public RtpEndUserState toEndUserState() {
1006            return switch (this) {
1007                case SEARCHING, SEARCHING_ACKNOWLEDGED -> RtpEndUserState.FINDING_DEVICE;
1008                case DISCOVERED -> RtpEndUserState.RINGING;
1009                default -> RtpEndUserState.CONNECTIVITY_ERROR;
1010            };
1011        }
1012    }
1013
1014    public static class RtpSessionProposal implements OngoingRtpSession {
1015        public final Jid with;
1016        public final String sessionId;
1017        public final Set<Media> media;
1018        private final Account account;
1019        private final CallIntegration callIntegration;
1020
1021        private RtpSessionProposal(
1022                Account account,
1023                Jid with,
1024                String sessionId,
1025                Set<Media> media,
1026                final CallIntegration callIntegration) {
1027            this.account = account;
1028            this.with = with;
1029            this.sessionId = sessionId;
1030            this.media = media;
1031            this.callIntegration = callIntegration;
1032        }
1033
1034        public static RtpSessionProposal of(
1035                Account account,
1036                Jid with,
1037                Set<Media> media,
1038                final CallIntegration callIntegration) {
1039            return new RtpSessionProposal(account, with, nextRandomId(), media, callIntegration);
1040        }
1041
1042        @Override
1043        public boolean equals(Object o) {
1044            if (this == o) return true;
1045            if (o == null || getClass() != o.getClass()) return false;
1046            RtpSessionProposal proposal = (RtpSessionProposal) o;
1047            return Objects.equal(account.getJid(), proposal.account.getJid())
1048                    && Objects.equal(with, proposal.with)
1049                    && Objects.equal(sessionId, proposal.sessionId);
1050        }
1051
1052        @Override
1053        public int hashCode() {
1054            return Objects.hashCode(account.getJid(), with, sessionId);
1055        }
1056
1057        @Override
1058        public Account getAccount() {
1059            return account;
1060        }
1061
1062        @Override
1063        public Jid getWith() {
1064            return with;
1065        }
1066
1067        @Override
1068        public String getSessionId() {
1069            return sessionId;
1070        }
1071
1072        public CallIntegration getCallIntegration() {
1073            return this.callIntegration;
1074        }
1075    }
1076
1077    public class ProposalStateCallback implements CallIntegration.Callback {
1078
1079        private final RtpSessionProposal proposal;
1080
1081        public ProposalStateCallback(final RtpSessionProposal proposal) {
1082            this.proposal = proposal;
1083        }
1084
1085        @Override
1086        public void onCallIntegrationShowIncomingCallUi() {}
1087
1088        @Override
1089        public void onCallIntegrationDisconnect() {
1090            Log.d(Config.LOGTAG, "a phone call has just been started. retracting proposal");
1091            retractSessionProposal(this.proposal);
1092        }
1093
1094        @Override
1095        public void onAudioDeviceChanged(
1096                CallIntegration.AudioDevice selectedAudioDevice,
1097                Set<CallIntegration.AudioDevice> availableAudioDevices) {}
1098    }
1099}