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() || 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 boolean isBusy() {
 142        if (mXmppConnectionService.isPhoneInCall()) {
 143            return true;
 144        }
 145        for (AbstractJingleConnection connection : this.connections.values()) {
 146            if (connection instanceof JingleRtpConnection) {
 147                if (((JingleRtpConnection) connection).isTerminated()) {
 148                    continue;
 149                }
 150                return true;
 151            }
 152        }
 153        synchronized (this.rtpSessionProposals) {
 154            return this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED)
 155                    || this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING)
 156                    || this.rtpSessionProposals.containsValue(
 157                            DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED);
 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 boolean hasMatchingRtpSession(
 196            final Account account, final Jid with, final Set<Media> media) {
 197        for (AbstractJingleConnection connection : this.connections.values()) {
 198            if (connection instanceof JingleRtpConnection) {
 199                final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
 200                if (rtpConnection.isTerminated()) {
 201                    continue;
 202                }
 203                if (rtpConnection.getId().account == account
 204                        && rtpConnection.getId().with.asBareJid().equals(with.asBareJid())
 205                        && rtpConnection.getMedia().equals(media)) {
 206                    return true;
 207                }
 208            }
 209        }
 210        return false;
 211    }
 212
 213    private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
 214        final boolean notifyForStrangers =
 215                mXmppConnectionService.getNotificationService().notificationsFromStrangers();
 216        if (notifyForStrangers) {
 217            return false;
 218        }
 219        final Contact contact = account.getRoster().getContact(with);
 220        return !contact.showInContactList();
 221    }
 222
 223    ScheduledFuture<?> schedule(
 224            final Runnable runnable, final long delay, final TimeUnit timeUnit) {
 225        return SCHEDULED_EXECUTOR_SERVICE.schedule(runnable, delay, timeUnit);
 226    }
 227
 228    void respondWithJingleError(
 229            final Account account,
 230            final IqPacket original,
 231            String jingleCondition,
 232            String condition,
 233            String conditionType) {
 234        final IqPacket response = original.generateResponse(IqPacket.TYPE.ERROR);
 235        final Element error = response.addChild("error");
 236        error.setAttribute("type", conditionType);
 237        error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
 238        error.addChild(jingleCondition, Namespace.JINGLE_ERRORS);
 239        account.getXmppConnection().sendIqPacket(response, null);
 240    }
 241
 242    public void deliverMessage(
 243            final Account account,
 244            final Jid to,
 245            final Jid from,
 246            final Element message,
 247            String remoteMsgId,
 248            String serverMsgId,
 249            long timestamp) {
 250        Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
 251        final String sessionId = message.getAttribute("id");
 252        if (sessionId == null) {
 253            return;
 254        }
 255        if ("accept".equals(message.getName())) {
 256            for (AbstractJingleConnection connection : connections.values()) {
 257                if (connection instanceof JingleRtpConnection) {
 258                    final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
 259                    final AbstractJingleConnection.Id id = connection.getId();
 260                    if (id.account == account && id.sessionId.equals(sessionId)) {
 261                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 262                        return;
 263                    }
 264                }
 265            }
 266            return;
 267        }
 268        final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
 269        final boolean addressedDirectly = to != null && to.equals(account.getJid());
 270        final AbstractJingleConnection.Id id;
 271        if (fromSelf) {
 272            if (to != null && to.isFullJid()) {
 273                id = AbstractJingleConnection.Id.of(account, to, sessionId);
 274            } else {
 275                return;
 276            }
 277        } else {
 278            id = AbstractJingleConnection.Id.of(account, from, sessionId);
 279        }
 280        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 281        if (existingJingleConnection != null) {
 282            if (existingJingleConnection instanceof JingleRtpConnection) {
 283                ((JingleRtpConnection) existingJingleConnection)
 284                        .deliveryMessage(from, message, serverMsgId, timestamp);
 285            } else {
 286                Log.d(
 287                        Config.LOGTAG,
 288                        account.getJid().asBareJid()
 289                                + ": "
 290                                + existingJingleConnection.getClass().getName()
 291                                + " does not support jingle messages");
 292            }
 293            return;
 294        }
 295
 296        if (fromSelf) {
 297            if ("proceed".equals(message.getName())) {
 298                final Conversation c =
 299                        mXmppConnectionService.findOrCreateConversation(
 300                                account, id.with, false, false);
 301                final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
 302                if (previousBusy != null) {
 303                    previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
 304                    if (serverMsgId != null) {
 305                        previousBusy.setServerMsgId(serverMsgId);
 306                    }
 307                    previousBusy.setTime(timestamp);
 308                    mXmppConnectionService.updateMessage(previousBusy, true);
 309                    Log.d(
 310                            Config.LOGTAG,
 311                            id.account.getJid().asBareJid()
 312                                    + ": updated previous busy because call got picked up by another device");
 313                    return;
 314                }
 315            }
 316            // TODO handle reject for cases where we don’t have carbon copies (normally reject is to
 317            // be sent to own bare jid as well)
 318            Log.d(
 319                    Config.LOGTAG,
 320                    account.getJid().asBareJid() + ": ignore jingle message from self");
 321            return;
 322        }
 323
 324        if ("propose".equals(message.getName())) {
 325            final Propose propose = Propose.upgrade(message);
 326            final List<GenericDescription> descriptions = propose.getDescriptions();
 327            final Collection<RtpDescription> rtpDescriptions =
 328                    Collections2.transform(
 329                            Collections2.filter(descriptions, d -> d instanceof RtpDescription),
 330                            input -> (RtpDescription) input);
 331            if (rtpDescriptions.size() > 0
 332                    && rtpDescriptions.size() == descriptions.size()
 333                    && isUsingClearNet(account)) {
 334                final Collection<Media> media =
 335                        Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
 336                if (media.contains(Media.UNKNOWN)) {
 337                    Log.d(
 338                            Config.LOGTAG,
 339                            account.getJid().asBareJid()
 340                                    + ": encountered unknown media in session proposal. "
 341                                    + propose);
 342                    return;
 343                }
 344                final Optional<RtpSessionProposal> matchingSessionProposal =
 345                        findMatchingSessionProposal(account, id.with, ImmutableSet.copyOf(media));
 346                if (matchingSessionProposal.isPresent()) {
 347                    final String ourSessionId = matchingSessionProposal.get().sessionId;
 348                    final String theirSessionId = id.sessionId;
 349                    if (ComparisonChain.start()
 350                                    .compare(ourSessionId, theirSessionId)
 351                                    .compare(
 352                                            account.getJid().toEscapedString(),
 353                                            id.with.toEscapedString())
 354                                    .result()
 355                            > 0) {
 356                        Log.d(
 357                                Config.LOGTAG,
 358                                account.getJid().asBareJid()
 359                                        + ": our session lost tie break. automatically accepting their session. winning Session="
 360                                        + theirSessionId);
 361                        // TODO a retract for this reason should probably include some indication of
 362                        // tie break
 363                        retractSessionProposal(matchingSessionProposal.get());
 364                        final JingleRtpConnection rtpConnection =
 365                                new JingleRtpConnection(this, id, from);
 366                        this.connections.put(id, rtpConnection);
 367                        rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 368                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 369                    } else {
 370                        Log.d(
 371                                Config.LOGTAG,
 372                                account.getJid().asBareJid()
 373                                        + ": our session won tie break. waiting for other party to accept. winningSession="
 374                                        + ourSessionId);
 375                    }
 376                    return;
 377                }
 378                final boolean stranger =
 379                        isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 380                if (isBusy() || stranger) {
 381                    writeLogMissedIncoming(
 382                            account, id.with.asBareJid(), id.sessionId, serverMsgId, timestamp);
 383                    if (stranger) {
 384                        Log.d(
 385                                Config.LOGTAG,
 386                                id.account.getJid().asBareJid()
 387                                        + ": ignoring call proposal from stranger "
 388                                        + id.with);
 389                        return;
 390                    }
 391                    final int activeDevices = account.activeDevicesWithRtpCapability();
 392                    Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
 393                    if (activeDevices == 0) {
 394                        final MessagePacket reject =
 395                                mXmppConnectionService
 396                                        .getMessageGenerator()
 397                                        .sessionReject(from, sessionId);
 398                        mXmppConnectionService.sendMessagePacket(account, reject);
 399                    } else {
 400                        Log.d(
 401                                Config.LOGTAG,
 402                                id.account.getJid().asBareJid()
 403                                        + ": ignoring proposal because busy on this device but there are other devices");
 404                    }
 405                } else {
 406                    final JingleRtpConnection rtpConnection =
 407                            new JingleRtpConnection(this, id, from);
 408                    this.connections.put(id, rtpConnection);
 409                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 410                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 411                }
 412            } else {
 413                Log.d(
 414                        Config.LOGTAG,
 415                        account.getJid().asBareJid()
 416                                + ": unable to react to proposed session with "
 417                                + rtpDescriptions.size()
 418                                + " rtp descriptions of "
 419                                + descriptions.size()
 420                                + " total descriptions");
 421            }
 422        } else if (addressedDirectly && "proceed".equals(message.getName())) {
 423            synchronized (rtpSessionProposals) {
 424                final RtpSessionProposal proposal =
 425                        getRtpSessionProposal(account, from.asBareJid(), sessionId);
 426                if (proposal != null) {
 427                    rtpSessionProposals.remove(proposal);
 428                    final JingleRtpConnection rtpConnection =
 429                            new JingleRtpConnection(this, id, account.getJid());
 430                    rtpConnection.setProposedMedia(proposal.media);
 431                    this.connections.put(id, rtpConnection);
 432                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
 433                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 434                } else {
 435                    Log.d(
 436                            Config.LOGTAG,
 437                            account.getJid().asBareJid()
 438                                    + ": no rtp session proposal found for "
 439                                    + from
 440                                    + " to deliver proceed");
 441                    if (remoteMsgId == null) {
 442                        return;
 443                    }
 444                    final MessagePacket errorMessage = new MessagePacket();
 445                    errorMessage.setTo(from);
 446                    errorMessage.setId(remoteMsgId);
 447                    errorMessage.setType(MessagePacket.TYPE_ERROR);
 448                    final Element error = errorMessage.addChild("error");
 449                    error.setAttribute("code", "404");
 450                    error.setAttribute("type", "cancel");
 451                    error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
 452                    mXmppConnectionService.sendMessagePacket(account, errorMessage);
 453                }
 454            }
 455        } else if (addressedDirectly && "reject".equals(message.getName())) {
 456            final RtpSessionProposal proposal =
 457                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
 458            synchronized (rtpSessionProposals) {
 459                if (proposal != null && rtpSessionProposals.remove(proposal) != null) {
 460                    writeLogMissedOutgoing(
 461                            account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
 462                    toneManager.transition(RtpEndUserState.DECLINED_OR_BUSY, proposal.media);
 463                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 464                            account,
 465                            proposal.with,
 466                            proposal.sessionId,
 467                            RtpEndUserState.DECLINED_OR_BUSY);
 468                } else {
 469                    Log.d(
 470                            Config.LOGTAG,
 471                            account.getJid().asBareJid()
 472                                    + ": no rtp session proposal found for "
 473                                    + from
 474                                    + " to deliver reject");
 475                }
 476            }
 477        } else {
 478            Log.d(
 479                    Config.LOGTAG,
 480                    account.getJid().asBareJid()
 481                            + ": retrieved out of order jingle message"
 482                            + message);
 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 void proposeJingleRtpSession(
 729            final Account account, final Jid with, final Set<Media> media) {
 730        synchronized (this.rtpSessionProposals) {
 731            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 732                    this.rtpSessionProposals.entrySet()) {
 733                RtpSessionProposal proposal = entry.getKey();
 734                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 735                    final DeviceDiscoveryState preexistingState = entry.getValue();
 736                    if (preexistingState != null
 737                            && preexistingState != DeviceDiscoveryState.FAILED) {
 738                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
 739                        toneManager.transition(endUserState, media);
 740                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 741                                account, with, proposal.sessionId, endUserState);
 742                        return;
 743                    }
 744                }
 745            }
 746            if (isBusy()) {
 747                if (hasMatchingRtpSession(account, with, media)) {
 748                    Log.d(
 749                            Config.LOGTAG,
 750                            "ignoring request to propose jingle session because the other party already created one for us");
 751                    return;
 752                }
 753                throw new IllegalStateException(
 754                        "There is already a running RTP session. This should have been caught by the UI");
 755            }
 756            final RtpSessionProposal proposal =
 757                    RtpSessionProposal.of(account, with.asBareJid(), media);
 758            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
 759            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 760                    account, proposal.with, proposal.sessionId, RtpEndUserState.FINDING_DEVICE);
 761            final MessagePacket messagePacket =
 762                    mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 763            mXmppConnectionService.sendMessagePacket(account, messagePacket);
 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}