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