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