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