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