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().asBareJid()
 478                            + ": retrieved out of order jingle message"
 479                            + message);
 480        }
 481    }
 482
 483    private RtpSessionProposal getRtpSessionProposal(
 484            final Account account, Jid from, String sessionId) {
 485        for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
 486            if (rtpSessionProposal.sessionId.equals(sessionId)
 487                    && rtpSessionProposal.with.equals(from)
 488                    && rtpSessionProposal.account.getJid().equals(account.getJid())) {
 489                return rtpSessionProposal;
 490            }
 491        }
 492        return null;
 493    }
 494
 495    private void writeLogMissedOutgoing(
 496            final Account account,
 497            Jid with,
 498            final String sessionId,
 499            String serverMsgId,
 500            long timestamp) {
 501        final Conversation conversation =
 502                mXmppConnectionService.findOrCreateConversation(
 503                        account, with.asBareJid(), false, false);
 504        final Message message =
 505                new Message(conversation, Message.STATUS_SEND, Message.TYPE_RTP_SESSION, sessionId);
 506        message.setBody(new RtpSessionStatus(false, 0).toString());
 507        message.setServerMsgId(serverMsgId);
 508        message.setTime(timestamp);
 509        writeMessage(message);
 510    }
 511
 512    private void writeLogMissedIncoming(
 513            final Account account,
 514            Jid with,
 515            final String sessionId,
 516            String serverMsgId,
 517            long timestamp) {
 518        final Conversation conversation =
 519                mXmppConnectionService.findOrCreateConversation(
 520                        account, with.asBareJid(), false, false);
 521        final Message message =
 522                new Message(
 523                        conversation, Message.STATUS_RECEIVED, Message.TYPE_RTP_SESSION, sessionId);
 524        message.setBody(new RtpSessionStatus(false, 0).toString());
 525        message.setServerMsgId(serverMsgId);
 526        message.setTime(timestamp);
 527        writeMessage(message);
 528    }
 529
 530    private void writeMessage(final Message message) {
 531        final Conversational conversational = message.getConversation();
 532        if (conversational instanceof Conversation) {
 533            ((Conversation) conversational).add(message);
 534            mXmppConnectionService.databaseBackend.createMessage(message);
 535            mXmppConnectionService.updateConversationUi();
 536        } else {
 537            throw new IllegalStateException("Somehow the conversation in a message was a stub");
 538        }
 539    }
 540
 541    public void startJingleFileTransfer(final Message message) {
 542        Preconditions.checkArgument(
 543                message.isFileOrImage(), "Message is not of type file or image");
 544        final Transferable old = message.getTransferable();
 545        if (old != null) {
 546            old.cancel();
 547        }
 548        final Account account = message.getConversation().getAccount();
 549        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
 550        final JingleFileTransferConnection connection =
 551                new JingleFileTransferConnection(this, id, account.getJid());
 552        mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
 553        this.connections.put(id, connection);
 554        connection.init(message);
 555    }
 556
 557    public Optional<OngoingRtpSession> getOngoingRtpConnection(final Contact contact) {
 558        for (final Map.Entry<AbstractJingleConnection.Id, AbstractJingleConnection> entry :
 559                this.connections.entrySet()) {
 560            if (entry.getValue() instanceof JingleRtpConnection) {
 561                final AbstractJingleConnection.Id id = entry.getKey();
 562                if (id.account == contact.getAccount()
 563                        && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
 564                    return Optional.of(id);
 565                }
 566            }
 567        }
 568        synchronized (this.rtpSessionProposals) {
 569            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 570                    this.rtpSessionProposals.entrySet()) {
 571                final RtpSessionProposal proposal = entry.getKey();
 572                if (proposal.account == contact.getAccount()
 573                        && contact.getJid().asBareJid().equals(proposal.with)) {
 574                    final DeviceDiscoveryState preexistingState = entry.getValue();
 575                    if (preexistingState != null
 576                            && preexistingState != DeviceDiscoveryState.FAILED) {
 577                        return Optional.of(proposal);
 578                    }
 579                }
 580            }
 581        }
 582        return Optional.absent();
 583    }
 584
 585    void finishConnection(final AbstractJingleConnection connection) {
 586        this.connections.remove(connection.getId());
 587    }
 588
 589    void finishConnectionOrThrow(final AbstractJingleConnection connection) {
 590        final AbstractJingleConnection.Id id = connection.getId();
 591        if (this.connections.remove(id) == null) {
 592            throw new IllegalStateException(
 593                    String.format("Unable to finish connection with id=%s", id.toString()));
 594        }
 595    }
 596
 597    public boolean fireJingleRtpConnectionStateUpdates() {
 598        boolean firedUpdates = false;
 599        for (final AbstractJingleConnection connection : this.connections.values()) {
 600            if (connection instanceof JingleRtpConnection) {
 601                final JingleRtpConnection jingleRtpConnection = (JingleRtpConnection) connection;
 602                if (jingleRtpConnection.isTerminated()) {
 603                    continue;
 604                }
 605                jingleRtpConnection.fireStateUpdate();
 606                firedUpdates = true;
 607            }
 608        }
 609        return firedUpdates;
 610    }
 611
 612    void getPrimaryCandidate(
 613            final Account account,
 614            final boolean initiator,
 615            final OnPrimaryCandidateFound listener) {
 616        if (Config.DISABLE_PROXY_LOOKUP) {
 617            listener.onPrimaryCandidateFound(false, null);
 618            return;
 619        }
 620        if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
 621            final Jid proxy =
 622                    account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
 623            if (proxy != null) {
 624                IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 625                iq.setTo(proxy);
 626                iq.query(Namespace.BYTE_STREAMS);
 627                account.getXmppConnection()
 628                        .sendIqPacket(
 629                                iq,
 630                                new OnIqPacketReceived() {
 631
 632                                    @Override
 633                                    public void onIqPacketReceived(
 634                                            Account account, IqPacket packet) {
 635                                        final Element streamhost =
 636                                                packet.query()
 637                                                        .findChild(
 638                                                                "streamhost",
 639                                                                Namespace.BYTE_STREAMS);
 640                                        final String host =
 641                                                streamhost == null
 642                                                        ? null
 643                                                        : streamhost.getAttribute("host");
 644                                        final String port =
 645                                                streamhost == null
 646                                                        ? null
 647                                                        : streamhost.getAttribute("port");
 648                                        if (host != null && port != null) {
 649                                            try {
 650                                                JingleCandidate candidate =
 651                                                        new JingleCandidate(nextRandomId(), true);
 652                                                candidate.setHost(host);
 653                                                candidate.setPort(Integer.parseInt(port));
 654                                                candidate.setType(JingleCandidate.TYPE_PROXY);
 655                                                candidate.setJid(proxy);
 656                                                candidate.setPriority(
 657                                                        655360 + (initiator ? 30 : 0));
 658                                                primaryCandidates.put(
 659                                                        account.getJid().asBareJid(), candidate);
 660                                                listener.onPrimaryCandidateFound(true, candidate);
 661                                            } catch (final NumberFormatException e) {
 662                                                listener.onPrimaryCandidateFound(false, null);
 663                                            }
 664                                        } else {
 665                                            listener.onPrimaryCandidateFound(false, null);
 666                                        }
 667                                    }
 668                                });
 669            } else {
 670                listener.onPrimaryCandidateFound(false, null);
 671            }
 672
 673        } else {
 674            listener.onPrimaryCandidateFound(
 675                    true, this.primaryCandidates.get(account.getJid().asBareJid()));
 676        }
 677    }
 678
 679    public void retractSessionProposal(final Account account, final Jid with) {
 680        synchronized (this.rtpSessionProposals) {
 681            RtpSessionProposal matchingProposal = null;
 682            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
 683                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 684                    matchingProposal = proposal;
 685                    break;
 686                }
 687            }
 688            if (matchingProposal != null) {
 689                retractSessionProposal(matchingProposal);
 690            }
 691        }
 692    }
 693
 694    private void retractSessionProposal(RtpSessionProposal rtpSessionProposal) {
 695        final Account account = rtpSessionProposal.account;
 696        toneManager.transition(RtpEndUserState.ENDED, rtpSessionProposal.media);
 697        Log.d(
 698                Config.LOGTAG,
 699                account.getJid().asBareJid()
 700                        + ": retracting rtp session proposal with "
 701                        + rtpSessionProposal.with);
 702        this.rtpSessionProposals.remove(rtpSessionProposal);
 703        final MessagePacket messagePacket =
 704                mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
 705        writeLogMissedOutgoing(
 706                account,
 707                rtpSessionProposal.with,
 708                rtpSessionProposal.sessionId,
 709                null,
 710                System.currentTimeMillis());
 711        mXmppConnectionService.sendMessagePacket(account, messagePacket);
 712    }
 713
 714    public String initializeRtpSession(
 715            final Account account, final Jid with, final Set<Media> media) {
 716        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
 717        final JingleRtpConnection rtpConnection =
 718                new JingleRtpConnection(this, id, account.getJid());
 719        rtpConnection.setProposedMedia(media);
 720        this.connections.put(id, rtpConnection);
 721        rtpConnection.sendSessionInitiate();
 722        return id.sessionId;
 723    }
 724
 725    public String proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
 726        synchronized (this.rtpSessionProposals) {
 727            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 728                    this.rtpSessionProposals.entrySet()) {
 729                RtpSessionProposal proposal = entry.getKey();
 730                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 731                    final DeviceDiscoveryState preexistingState = entry.getValue();
 732                    if (preexistingState != null
 733                            && preexistingState != DeviceDiscoveryState.FAILED) {
 734                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
 735                        toneManager.transition(endUserState, media);
 736                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 737                                account,
 738                                with,
 739                                proposal.sessionId,
 740                                endUserState
 741                        );
 742                        return proposal.sessionId;
 743                    }
 744                }
 745            }
 746            String busyCode = isBusy();
 747            if (busyCode != null) {
 748                String sessionId = hasMatchingRtpSession(account, with, media);
 749                if (sessionId != null) {
 750                    Log.d(Config.LOGTAG, "ignoring request to propose jingle session because the other party already created one for us: " + sessionId);
 751                    return sessionId;
 752                }
 753                throw new IllegalStateException("There is already a running RTP session: " + busyCode);
 754            }
 755            final RtpSessionProposal proposal =
 756                    RtpSessionProposal.of(account, with.asBareJid(), media);
 757            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
 758            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 759                    account, proposal.with, proposal.sessionId, RtpEndUserState.FINDING_DEVICE);
 760            final MessagePacket messagePacket =
 761                    mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 762            mXmppConnectionService.sendMessagePacket(account, messagePacket);
 763            return proposal.sessionId;
 764        }
 765    }
 766
 767    public boolean hasMatchingProposal(final Account account, final Jid with) {
 768        synchronized (this.rtpSessionProposals) {
 769            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 770                    this.rtpSessionProposals.entrySet()) {
 771                final RtpSessionProposal proposal = entry.getKey();
 772                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 773                    return true;
 774                }
 775            }
 776        }
 777        return false;
 778    }
 779
 780    public void deliverIbbPacket(Account account, IqPacket packet) {
 781        final String sid;
 782        final Element payload;
 783        if (packet.hasChild("open", Namespace.IBB)) {
 784            payload = packet.findChild("open", Namespace.IBB);
 785            sid = payload.getAttribute("sid");
 786        } else if (packet.hasChild("data", Namespace.IBB)) {
 787            payload = packet.findChild("data", Namespace.IBB);
 788            sid = payload.getAttribute("sid");
 789        } else if (packet.hasChild("close", Namespace.IBB)) {
 790            payload = packet.findChild("close", Namespace.IBB);
 791            sid = payload.getAttribute("sid");
 792        } else {
 793            payload = null;
 794            sid = null;
 795        }
 796        if (sid != null) {
 797            for (final AbstractJingleConnection connection : this.connections.values()) {
 798                if (connection instanceof JingleFileTransferConnection) {
 799                    final JingleFileTransferConnection fileTransfer =
 800                            (JingleFileTransferConnection) connection;
 801                    final JingleTransport transport = fileTransfer.getTransport();
 802                    if (transport instanceof JingleInBandTransport) {
 803                        final JingleInBandTransport inBandTransport =
 804                                (JingleInBandTransport) transport;
 805                        if (inBandTransport.matches(account, sid)) {
 806                            inBandTransport.deliverPayload(packet, payload);
 807                        }
 808                        return;
 809                    }
 810                }
 811            }
 812        }
 813        Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
 814        account.getXmppConnection()
 815                .sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
 816    }
 817
 818    public void notifyRebound(final Account account) {
 819        for (final AbstractJingleConnection connection : this.connections.values()) {
 820            connection.notifyRebound();
 821        }
 822        final XmppConnection xmppConnection = account.getXmppConnection();
 823        if (xmppConnection != null && xmppConnection.getFeatures().sm()) {
 824            resendSessionProposals(account);
 825        }
 826    }
 827
 828    public WeakReference<JingleRtpConnection> findJingleRtpConnection(
 829            Account account, Jid with, String sessionId) {
 830        final AbstractJingleConnection.Id id =
 831                AbstractJingleConnection.Id.of(account, with, sessionId);
 832        final AbstractJingleConnection connection = connections.get(id);
 833        if (connection instanceof JingleRtpConnection) {
 834            return new WeakReference<>((JingleRtpConnection) connection);
 835        }
 836        return null;
 837    }
 838
 839    private void resendSessionProposals(final Account account) {
 840        synchronized (this.rtpSessionProposals) {
 841            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 842                    this.rtpSessionProposals.entrySet()) {
 843                final RtpSessionProposal proposal = entry.getKey();
 844                if (entry.getValue() == DeviceDiscoveryState.SEARCHING
 845                        && proposal.account == account) {
 846                    Log.d(
 847                            Config.LOGTAG,
 848                            account.getJid().asBareJid()
 849                                    + ": resending session proposal to "
 850                                    + proposal.with);
 851                    final MessagePacket messagePacket =
 852                            mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 853                    mXmppConnectionService.sendMessagePacket(account, messagePacket);
 854                }
 855            }
 856        }
 857    }
 858
 859    public void updateProposedSessionDiscovered(
 860            Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
 861        synchronized (this.rtpSessionProposals) {
 862            final RtpSessionProposal sessionProposal =
 863                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
 864            final DeviceDiscoveryState currentState =
 865                    sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
 866            if (currentState == null) {
 867                Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
 868                return;
 869            }
 870            if (currentState == DeviceDiscoveryState.DISCOVERED) {
 871                Log.d(
 872                        Config.LOGTAG,
 873                        "session proposal already at discovered. not going to fall back");
 874                return;
 875            }
 876            this.rtpSessionProposals.put(sessionProposal, target);
 877            final RtpEndUserState endUserState = target.toEndUserState();
 878            toneManager.transition(endUserState, sessionProposal.media);
 879            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 880                    account, sessionProposal.with, sessionProposal.sessionId, endUserState);
 881            Log.d(
 882                    Config.LOGTAG,
 883                    account.getJid().asBareJid()
 884                            + ": flagging session "
 885                            + sessionId
 886                            + " as "
 887                            + target);
 888        }
 889    }
 890
 891    public void rejectRtpSession(final String sessionId) {
 892        for (final AbstractJingleConnection connection : this.connections.values()) {
 893            if (connection.getId().sessionId.equals(sessionId)) {
 894                if (connection instanceof JingleRtpConnection) {
 895                    try {
 896                        ((JingleRtpConnection) connection).rejectCall();
 897                        return;
 898                    } catch (final IllegalStateException e) {
 899                        Log.w(
 900                                Config.LOGTAG,
 901                                "race condition on rejecting call from notification",
 902                                e);
 903                    }
 904                }
 905            }
 906        }
 907    }
 908
 909    public void endRtpSession(final String sessionId) {
 910        for (final AbstractJingleConnection connection : this.connections.values()) {
 911            if (connection.getId().sessionId.equals(sessionId)) {
 912                if (connection instanceof JingleRtpConnection) {
 913                    ((JingleRtpConnection) connection).endCall();
 914                }
 915            }
 916        }
 917    }
 918
 919    public void failProceed(Account account, final Jid with, final String sessionId, final String message) {
 920        final AbstractJingleConnection.Id id =
 921                AbstractJingleConnection.Id.of(account, with, sessionId);
 922        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 923        if (existingJingleConnection instanceof JingleRtpConnection) {
 924            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed(message);
 925        }
 926    }
 927
 928    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
 929        if (connections.containsValue(connection)) {
 930            return;
 931        }
 932        final IllegalStateException e =
 933                new IllegalStateException(
 934                        "JingleConnection has not been registered with connection manager");
 935        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
 936        throw e;
 937    }
 938
 939    void setTerminalSessionState(
 940            AbstractJingleConnection.Id id, final RtpEndUserState state, final Set<Media> media) {
 941        this.terminatedSessions.put(
 942                PersistableSessionId.of(id), new TerminatedRtpSession(state, media));
 943    }
 944
 945    public TerminatedRtpSession getTerminalSessionState(final Jid with, final String sessionId) {
 946        return this.terminatedSessions.getIfPresent(new PersistableSessionId(with, sessionId));
 947    }
 948
 949    private static class PersistableSessionId {
 950        private final Jid with;
 951        private final String sessionId;
 952
 953        private PersistableSessionId(Jid with, String sessionId) {
 954            this.with = with;
 955            this.sessionId = sessionId;
 956        }
 957
 958        public static PersistableSessionId of(AbstractJingleConnection.Id id) {
 959            return new PersistableSessionId(id.with, id.sessionId);
 960        }
 961
 962        @Override
 963        public boolean equals(Object o) {
 964            if (this == o) return true;
 965            if (o == null || getClass() != o.getClass()) return false;
 966            PersistableSessionId that = (PersistableSessionId) o;
 967            return Objects.equal(with, that.with) && Objects.equal(sessionId, that.sessionId);
 968        }
 969
 970        @Override
 971        public int hashCode() {
 972            return Objects.hashCode(with, sessionId);
 973        }
 974    }
 975
 976    public static class TerminatedRtpSession {
 977        public final RtpEndUserState state;
 978        public final Set<Media> media;
 979
 980        TerminatedRtpSession(RtpEndUserState state, Set<Media> media) {
 981            this.state = state;
 982            this.media = media;
 983        }
 984    }
 985
 986    public enum DeviceDiscoveryState {
 987        SEARCHING,
 988        SEARCHING_ACKNOWLEDGED,
 989        DISCOVERED,
 990        FAILED;
 991
 992        public RtpEndUserState toEndUserState() {
 993            switch (this) {
 994                case SEARCHING:
 995                case SEARCHING_ACKNOWLEDGED:
 996                    return RtpEndUserState.FINDING_DEVICE;
 997                case DISCOVERED:
 998                    return RtpEndUserState.RINGING;
 999                default:
1000                    return RtpEndUserState.CONNECTIVITY_ERROR;
1001            }
1002        }
1003    }
1004
1005    public static class RtpSessionProposal implements OngoingRtpSession {
1006        public final Jid with;
1007        public final String sessionId;
1008        public final Set<Media> media;
1009        private final Account account;
1010
1011        private RtpSessionProposal(Account account, Jid with, String sessionId) {
1012            this(account, with, sessionId, Collections.emptySet());
1013        }
1014
1015        private RtpSessionProposal(Account account, Jid with, String sessionId, Set<Media> media) {
1016            this.account = account;
1017            this.with = with;
1018            this.sessionId = sessionId;
1019            this.media = media;
1020        }
1021
1022        public static RtpSessionProposal of(Account account, Jid with, Set<Media> media) {
1023            return new RtpSessionProposal(account, with, nextRandomId(), media);
1024        }
1025
1026        @Override
1027        public boolean equals(Object o) {
1028            if (this == o) return true;
1029            if (o == null || getClass() != o.getClass()) return false;
1030            RtpSessionProposal proposal = (RtpSessionProposal) o;
1031            return Objects.equal(account.getJid(), proposal.account.getJid())
1032                    && Objects.equal(with, proposal.with)
1033                    && Objects.equal(sessionId, proposal.sessionId);
1034        }
1035
1036        @Override
1037        public int hashCode() {
1038            return Objects.hashCode(account.getJid(), with, sessionId);
1039        }
1040
1041        @Override
1042        public Account getAccount() {
1043            return account;
1044        }
1045
1046        @Override
1047        public Jid getWith() {
1048            return with;
1049        }
1050
1051        @Override
1052        public String getSessionId() {
1053            return sessionId;
1054        }
1055    }
1056}