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