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.jingle.stanzas.Content;
 44import eu.siacs.conversations.xmpp.jingle.stanzas.FileTransferDescription;
 45import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
 46import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 47import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
 48import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
 49import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
 50import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 51import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 52
 53public class JingleConnectionManager extends AbstractConnectionManager {
 54    static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();
 55    final ToneManager toneManager;
 56    private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals = new HashMap<>();
 57    private final ConcurrentHashMap<AbstractJingleConnection.Id, AbstractJingleConnection> connections = new ConcurrentHashMap<>();
 58
 59    private final Cache<PersistableSessionId, TerminatedRtpSession> terminatedSessions = CacheBuilder.newBuilder()
 60            .expireAfterWrite(24, TimeUnit.HOURS)
 61            .build();
 62
 63    private HashMap<Jid, JingleCandidate> primaryCandidates = new HashMap<>();
 64
 65    public JingleConnectionManager(XmppConnectionService service) {
 66        super(service);
 67        this.toneManager = new ToneManager(service);
 68    }
 69
 70    static String nextRandomId() {
 71        final byte[] id = new byte[16];
 72        new SecureRandom().nextBytes(id);
 73        return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING);
 74    }
 75
 76    public void deliverPacket(final Account account, final JinglePacket packet) {
 77        final String sessionId = packet.getSessionId();
 78        if (sessionId == null) {
 79            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
 80            return;
 81        }
 82        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, packet);
 83        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 84        if (existingJingleConnection != null) {
 85            existingJingleConnection.deliverPacket(packet);
 86        } else if (packet.getAction() == JinglePacket.Action.SESSION_INITIATE) {
 87            final Jid from = packet.getFrom();
 88            final Content content = packet.getJingleContent();
 89            final String descriptionNamespace = content == null ? null : content.getDescriptionNamespace();
 90            final AbstractJingleConnection connection;
 91            if (FileTransferDescription.NAMESPACES.contains(descriptionNamespace)) {
 92                connection = new JingleFileTransferConnection(this, id, from);
 93            } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace) && !usesTor(account)) {
 94                final boolean sessionEnded = this.terminatedSessions.asMap().containsKey(PersistableSessionId.of(id));
 95                final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 96                if (isBusy() || sessionEnded || stranger) {
 97                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": rejected session with " + id.with + " because busy. sessionEnded=" + sessionEnded + ", stranger=" + stranger);
 98                    mXmppConnectionService.sendIqPacket(account, packet.generateResponse(IqPacket.TYPE.RESULT), null);
 99                    final JinglePacket sessionTermination = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
100                    sessionTermination.setTo(id.with);
101                    sessionTermination.setReason(Reason.BUSY, null);
102                    mXmppConnectionService.sendIqPacket(account, sessionTermination, null);
103                    return;
104                }
105                connection = new JingleRtpConnection(this, id, from);
106            } else {
107                respondWithJingleError(account, packet, "unsupported-info", "feature-not-implemented", "cancel");
108                return;
109            }
110            connections.put(id, connection);
111            mXmppConnectionService.updateConversationUi();
112            connection.deliverPacket(packet);
113        } else {
114            Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
115            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
116        }
117    }
118
119    private boolean usesTor(final Account account) {
120        return account.isOnion() || mXmppConnectionService.useTorToConnect();
121    }
122
123    public boolean isBusy() {
124        for (AbstractJingleConnection connection : this.connections.values()) {
125            if (connection instanceof JingleRtpConnection) {
126                if (((JingleRtpConnection) connection).isTerminated()) {
127                    continue;
128                }
129                return true;
130            }
131        }
132        synchronized (this.rtpSessionProposals) {
133            return this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED) || this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING);
134        }
135    }
136
137    private Optional<RtpSessionProposal> findMatchingSessionProposal(final Account account, final Jid with, final Set<Media> media) {
138        synchronized (this.rtpSessionProposals) {
139            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
140                final RtpSessionProposal proposal = entry.getKey();
141                final DeviceDiscoveryState state = entry.getValue();
142                final boolean openProposal = state == DeviceDiscoveryState.DISCOVERED || state == DeviceDiscoveryState.SEARCHING;
143                if (openProposal
144                        && proposal.account == account
145                        && proposal.with.equals(with.asBareJid())
146                        && proposal.media.equals(media)) {
147                    return Optional.of(proposal);
148                }
149            }
150        }
151        return Optional.absent();
152    }
153
154    private boolean hasMatchingRtpSession(final Account account, final Jid with, final Set<Media> media) {
155        for (AbstractJingleConnection connection : this.connections.values()) {
156            if (connection instanceof JingleRtpConnection) {
157                final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
158                if (rtpConnection.isTerminated()) {
159                    continue;
160                }
161                if (rtpConnection.getId().account == account
162                        && rtpConnection.getId().with.asBareJid().equals(with.asBareJid())
163                        && rtpConnection.getMedia().equals(media)) {
164                    return true;
165                }
166            }
167        }
168        return false;
169    }
170
171    private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
172        final boolean notifyForStrangers = mXmppConnectionService.getNotificationService().notificationsFromStrangers();
173        if (notifyForStrangers) {
174            return false;
175        }
176        final Contact contact = account.getRoster().getContact(with);
177        return !contact.showInContactList();
178    }
179
180    ScheduledFuture<?> schedule(final Runnable runnable, final long delay, final TimeUnit timeUnit) {
181        return SCHEDULED_EXECUTOR_SERVICE.schedule(runnable, delay, timeUnit);
182    }
183
184    void respondWithJingleError(final Account account, final IqPacket original, String jingleCondition, String condition, String conditionType) {
185        final IqPacket response = original.generateResponse(IqPacket.TYPE.ERROR);
186        final Element error = response.addChild("error");
187        error.setAttribute("type", conditionType);
188        error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
189        error.addChild(jingleCondition, "urn:xmpp:jingle:errors:1");
190        account.getXmppConnection().sendIqPacket(response, null);
191    }
192
193    public void deliverMessage(final Account account, final Jid to, final Jid from, final Element message, String remoteMsgId, String serverMsgId, long timestamp) {
194        Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
195        final String sessionId = message.getAttribute("id");
196        if (sessionId == null) {
197            return;
198        }
199        if ("accept".equals(message.getName())) {
200            for (AbstractJingleConnection connection : connections.values()) {
201                if (connection instanceof JingleRtpConnection) {
202                    final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
203                    final AbstractJingleConnection.Id id = connection.getId();
204                    if (id.account == account && id.sessionId.equals(sessionId)) {
205                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
206                        return;
207                    }
208                }
209            }
210            return;
211        }
212        final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
213        final boolean addressedDirectly = to != null && to.equals(account.getJid());
214        final AbstractJingleConnection.Id id;
215        if (fromSelf) {
216            if (to != null && to.isFullJid()) {
217                id = AbstractJingleConnection.Id.of(account, to, sessionId);
218            } else {
219                return;
220            }
221        } else {
222            id = AbstractJingleConnection.Id.of(account, from, sessionId);
223        }
224        final AbstractJingleConnection existingJingleConnection = connections.get(id);
225        if (existingJingleConnection != null) {
226            if (existingJingleConnection instanceof JingleRtpConnection) {
227                ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message, serverMsgId, timestamp);
228            } else {
229                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
230            }
231            return;
232        }
233
234        if (fromSelf) {
235            if ("proceed".equals(message.getName())) {
236                final Conversation c = mXmppConnectionService.findOrCreateConversation(account, id.with, false, false);
237                final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
238                if (previousBusy != null) {
239                    previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
240                    if (serverMsgId != null) {
241                        previousBusy.setServerMsgId(serverMsgId);
242                    }
243                    previousBusy.setTime(timestamp);
244                    mXmppConnectionService.updateMessage(previousBusy, true);
245                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": updated previous busy because call got picked up by another device");
246                    return;
247                }
248            }
249            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore jingle message from self");
250            return;
251        }
252
253        if ("propose".equals(message.getName())) {
254            final Propose propose = Propose.upgrade(message);
255            final List<GenericDescription> descriptions = propose.getDescriptions();
256            final Collection<RtpDescription> rtpDescriptions = Collections2.transform(
257                    Collections2.filter(descriptions, d -> d instanceof RtpDescription),
258                    input -> (RtpDescription) input
259            );
260            if (rtpDescriptions.size() > 0 && rtpDescriptions.size() == descriptions.size() && !usesTor(account)) {
261                final Collection<Media> media = Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
262                if (media.contains(Media.UNKNOWN)) {
263                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered unknown media in session proposal. " + propose);
264                    return;
265                }
266                final Optional<RtpSessionProposal> matchingSessionProposal = findMatchingSessionProposal(account, id.with, ImmutableSet.copyOf(media));
267                if (matchingSessionProposal.isPresent()) {
268                    final String ourSessionId = matchingSessionProposal.get().sessionId;
269                    final String theirSessionId = id.sessionId;
270                    if (ComparisonChain.start()
271                            .compare(ourSessionId, theirSessionId)
272                            .compare(account.getJid().toEscapedString(), id.with.toEscapedString())
273                            .result() > 0) {
274                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": our session lost tie break. automatically accepting their session. winning Session=" + theirSessionId);
275                        //TODO a retract for this reason should probably include some indication of tie break
276                        retractSessionProposal(matchingSessionProposal.get());
277                        final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
278                        this.connections.put(id, rtpConnection);
279                        rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
280                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
281                    } else {
282                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": our session won tie break. waiting for other party to accept. winningSession=" + ourSessionId);
283                    }
284                    return;
285                }
286                final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
287                if (isBusy() || stranger) {
288                    writeLogMissedIncoming(account, id.with.asBareJid(), id.sessionId, serverMsgId, timestamp);
289                    if (stranger) {
290                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring call proposal from stranger " + id.with);
291                        return;
292                    }
293                    final int activeDevices = account.activeDevicesWithRtpCapability();
294                    Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
295                    if (activeDevices == 0) {
296                        final MessagePacket reject = mXmppConnectionService.getMessageGenerator().sessionReject(from, sessionId);
297                        mXmppConnectionService.sendMessagePacket(account, reject);
298                    } else {
299                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring proposal because busy on this device but there are other devices");
300                    }
301                } else {
302                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
303                    this.connections.put(id, rtpConnection);
304                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
305                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
306                }
307            } else {
308                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed session with " + rtpDescriptions.size() + " rtp descriptions of " + descriptions.size() + " total descriptions");
309            }
310        } else if (addressedDirectly && "proceed".equals(message.getName())) {
311            synchronized (rtpSessionProposals) {
312                final RtpSessionProposal proposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
313                if (proposal != null) {
314                    rtpSessionProposals.remove(proposal);
315                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
316                    rtpConnection.setProposedMedia(proposal.media);
317                    this.connections.put(id, rtpConnection);
318                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
319                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
320                } else {
321                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver proceed");
322                    if (remoteMsgId == null) {
323                        return;
324                    }
325                    final MessagePacket errorMessage = new MessagePacket();
326                    errorMessage.setTo(from);
327                    errorMessage.setId(remoteMsgId);
328                    errorMessage.setType(MessagePacket.TYPE_ERROR);
329                    final Element error = errorMessage.addChild("error");
330                    error.setAttribute("code", "404");
331                    error.setAttribute("type", "cancel");
332                    error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
333                    mXmppConnectionService.sendMessagePacket(account, errorMessage);
334                }
335            }
336        } else if (addressedDirectly && "reject".equals(message.getName())) {
337            final RtpSessionProposal proposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
338            synchronized (rtpSessionProposals) {
339                if (proposal != null && rtpSessionProposals.remove(proposal) != null) {
340                    writeLogMissedOutgoing(account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
341                    toneManager.transition(RtpEndUserState.DECLINED_OR_BUSY, proposal.media);
342                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, proposal.with, proposal.sessionId, RtpEndUserState.DECLINED_OR_BUSY);
343                } else {
344                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver reject");
345                }
346            }
347        } else {
348            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message"+message);
349        }
350
351    }
352
353    private RtpSessionProposal getRtpSessionProposal(final Account account, Jid from, String sessionId) {
354        for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
355            if (rtpSessionProposal.sessionId.equals(sessionId) && rtpSessionProposal.with.equals(from) && rtpSessionProposal.account.getJid().equals(account.getJid())) {
356                return rtpSessionProposal;
357            }
358        }
359        return null;
360    }
361
362    private void writeLogMissedOutgoing(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
363        final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
364                account,
365                with.asBareJid(),
366                false,
367                false
368        );
369        final Message message = new Message(
370                conversation,
371                Message.STATUS_SEND,
372                Message.TYPE_RTP_SESSION,
373                sessionId
374        );
375        message.setBody(new RtpSessionStatus(false, 0).toString());
376        message.setServerMsgId(serverMsgId);
377        message.setTime(timestamp);
378        writeMessage(message);
379    }
380
381    private void writeLogMissedIncoming(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
382        final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
383                account,
384                with.asBareJid(),
385                false,
386                false
387        );
388        final Message message = new Message(
389                conversation,
390                Message.STATUS_RECEIVED,
391                Message.TYPE_RTP_SESSION,
392                sessionId
393        );
394        message.setBody(new RtpSessionStatus(false, 0).toString());
395        message.setServerMsgId(serverMsgId);
396        message.setTime(timestamp);
397        writeMessage(message);
398    }
399
400    private void writeMessage(final Message message) {
401        final Conversational conversational = message.getConversation();
402        if (conversational instanceof Conversation) {
403            ((Conversation) conversational).add(message);
404            mXmppConnectionService.databaseBackend.createMessage(message);
405            mXmppConnectionService.updateConversationUi();
406        } else {
407            throw new IllegalStateException("Somehow the conversation in a message was a stub");
408        }
409    }
410
411    public void startJingleFileTransfer(final Message message) {
412        Preconditions.checkArgument(message.isFileOrImage(), "Message is not of type file or image");
413        final Transferable old = message.getTransferable();
414        if (old != null) {
415            old.cancel();
416        }
417        final Account account = message.getConversation().getAccount();
418        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
419        final JingleFileTransferConnection connection = new JingleFileTransferConnection(this, id, account.getJid());
420        mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
421        this.connections.put(id, connection);
422        connection.init(message);
423    }
424
425    public Optional<OngoingRtpSession> getOngoingRtpConnection(final Contact contact) {
426        for (final Map.Entry<AbstractJingleConnection.Id, AbstractJingleConnection> entry : this.connections.entrySet()) {
427            if (entry.getValue() instanceof JingleRtpConnection) {
428                final AbstractJingleConnection.Id id = entry.getKey();
429                if (id.account == contact.getAccount() && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
430                    return Optional.of(id);
431                }
432            }
433        }
434        synchronized (this.rtpSessionProposals) {
435            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
436                RtpSessionProposal proposal = entry.getKey();
437                if (proposal.account == contact.getAccount() && contact.getJid().asBareJid().equals(proposal.with)) {
438                    final DeviceDiscoveryState preexistingState = entry.getValue();
439                    if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
440                        return Optional.of(proposal);
441                    }
442                }
443            }
444        }
445        return Optional.absent();
446    }
447
448    void finishConnection(final AbstractJingleConnection connection) {
449        this.connections.remove(connection.getId());
450    }
451
452    void finishConnectionOrThrow(final AbstractJingleConnection connection) {
453        final AbstractJingleConnection.Id id = connection.getId();
454        if (this.connections.remove(id) == null) {
455            throw new IllegalStateException(String.format("Unable to finish connection with id=%s", id.toString()));
456        }
457    }
458
459    public boolean fireJingleRtpConnectionStateUpdates() {
460        boolean firedUpdates = false;
461        for (final AbstractJingleConnection connection : this.connections.values()) {
462            if (connection instanceof JingleRtpConnection) {
463                final JingleRtpConnection jingleRtpConnection = (JingleRtpConnection) connection;
464                if (jingleRtpConnection.isTerminated()) {
465                    continue;
466                }
467                jingleRtpConnection.fireStateUpdate();
468                firedUpdates = true;
469            }
470        }
471        return firedUpdates;
472    }
473
474    void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
475        if (Config.DISABLE_PROXY_LOOKUP) {
476            listener.onPrimaryCandidateFound(false, null);
477            return;
478        }
479        if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
480            final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
481            if (proxy != null) {
482                IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
483                iq.setTo(proxy);
484                iq.query(Namespace.BYTE_STREAMS);
485                account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
486
487                    @Override
488                    public void onIqPacketReceived(Account account, IqPacket packet) {
489                        final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
490                        final String host = streamhost == null ? null : streamhost.getAttribute("host");
491                        final String port = streamhost == null ? null : streamhost.getAttribute("port");
492                        if (host != null && port != null) {
493                            try {
494                                JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
495                                candidate.setHost(host);
496                                candidate.setPort(Integer.parseInt(port));
497                                candidate.setType(JingleCandidate.TYPE_PROXY);
498                                candidate.setJid(proxy);
499                                candidate.setPriority(655360 + (initiator ? 30 : 0));
500                                primaryCandidates.put(account.getJid().asBareJid(), candidate);
501                                listener.onPrimaryCandidateFound(true, candidate);
502                            } catch (final NumberFormatException e) {
503                                listener.onPrimaryCandidateFound(false, null);
504                            }
505                        } else {
506                            listener.onPrimaryCandidateFound(false, null);
507                        }
508                    }
509                });
510            } else {
511                listener.onPrimaryCandidateFound(false, null);
512            }
513
514        } else {
515            listener.onPrimaryCandidateFound(true,
516                    this.primaryCandidates.get(account.getJid().asBareJid()));
517        }
518    }
519
520    public void retractSessionProposal(final Account account, final Jid with) {
521        synchronized (this.rtpSessionProposals) {
522            RtpSessionProposal matchingProposal = null;
523            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
524                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
525                    matchingProposal = proposal;
526                    break;
527                }
528            }
529            if (matchingProposal != null) {
530                retractSessionProposal(matchingProposal);
531            }
532        }
533    }
534
535    private void retractSessionProposal(RtpSessionProposal rtpSessionProposal) {
536        final Account account = rtpSessionProposal.account;
537        toneManager.transition(RtpEndUserState.ENDED, rtpSessionProposal.media);
538        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retracting rtp session proposal with " + rtpSessionProposal.with);
539        this.rtpSessionProposals.remove(rtpSessionProposal);
540        final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
541        writeLogMissedOutgoing(account, rtpSessionProposal.with, rtpSessionProposal.sessionId, null, System.currentTimeMillis());
542        mXmppConnectionService.sendMessagePacket(account, messagePacket);
543    }
544
545    public String initializeRtpSession(final Account account, final Jid with, final Set<Media> media) {
546        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
547        final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
548        rtpConnection.setProposedMedia(media);
549        this.connections.put(id, rtpConnection);
550        rtpConnection.sendSessionInitiate();
551        return id.sessionId;
552    }
553
554    public void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
555        synchronized (this.rtpSessionProposals) {
556            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
557                RtpSessionProposal proposal = entry.getKey();
558                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
559                    final DeviceDiscoveryState preexistingState = entry.getValue();
560                    if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
561                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
562                        toneManager.transition(endUserState, media);
563                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
564                                account,
565                                with,
566                                proposal.sessionId,
567                                endUserState
568                        );
569                        return;
570                    }
571                }
572            }
573            if (isBusy()) {
574                if (hasMatchingRtpSession(account, with, media)) {
575                    Log.d(Config.LOGTAG, "ignoring request to propose jingle session because the other party already created one for us");
576                    return;
577                }
578                throw new IllegalStateException("There is already a running RTP session. This should have been caught by the UI");
579            }
580            final RtpSessionProposal proposal = RtpSessionProposal.of(account, with.asBareJid(), media);
581            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
582            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
583                    account,
584                    proposal.with,
585                    proposal.sessionId,
586                    RtpEndUserState.FINDING_DEVICE
587            );
588            final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
589            Log.d(Config.LOGTAG, messagePacket.toString());
590            mXmppConnectionService.sendMessagePacket(account, messagePacket);
591        }
592    }
593
594    public boolean hasMatchingProposal(final Account account, final Jid with) {
595        synchronized (this.rtpSessionProposals) {
596            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
597                final RtpSessionProposal proposal = entry.getKey();
598                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
599                    return true;
600                }
601            }
602        }
603        return false;
604    }
605
606    public void deliverIbbPacket(Account account, IqPacket packet) {
607        final String sid;
608        final Element payload;
609        if (packet.hasChild("open", Namespace.IBB)) {
610            payload = packet.findChild("open", Namespace.IBB);
611            sid = payload.getAttribute("sid");
612        } else if (packet.hasChild("data", Namespace.IBB)) {
613            payload = packet.findChild("data", Namespace.IBB);
614            sid = payload.getAttribute("sid");
615        } else if (packet.hasChild("close", Namespace.IBB)) {
616            payload = packet.findChild("close", Namespace.IBB);
617            sid = payload.getAttribute("sid");
618        } else {
619            payload = null;
620            sid = null;
621        }
622        if (sid != null) {
623            for (final AbstractJingleConnection connection : this.connections.values()) {
624                if (connection instanceof JingleFileTransferConnection) {
625                    final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
626                    final JingleTransport transport = fileTransfer.getTransport();
627                    if (transport instanceof JingleInBandTransport) {
628                        final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
629                        if (inBandTransport.matches(account, sid)) {
630                            inBandTransport.deliverPayload(packet, payload);
631                        }
632                        return;
633                    }
634                }
635            }
636        }
637        Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
638        account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
639    }
640
641    public void notifyRebound() {
642        for (final AbstractJingleConnection connection : this.connections.values()) {
643            connection.notifyRebound();
644        }
645    }
646
647    public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
648        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
649        final AbstractJingleConnection connection = connections.get(id);
650        if (connection instanceof JingleRtpConnection) {
651            return new WeakReference<>((JingleRtpConnection) connection);
652        }
653        return null;
654    }
655
656    public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
657        synchronized (this.rtpSessionProposals) {
658            final RtpSessionProposal sessionProposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
659            final DeviceDiscoveryState currentState = sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
660            if (currentState == null) {
661                Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
662                return;
663            }
664            if (currentState == DeviceDiscoveryState.DISCOVERED) {
665                Log.d(Config.LOGTAG, "session proposal already at discovered. not going to fall back");
666                return;
667            }
668            this.rtpSessionProposals.put(sessionProposal, target);
669            final RtpEndUserState endUserState = target.toEndUserState();
670            toneManager.transition(endUserState, sessionProposal.media);
671            mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, sessionProposal.with, sessionProposal.sessionId, endUserState);
672            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": flagging session " + sessionId + " as " + target);
673        }
674    }
675
676    public void rejectRtpSession(final String sessionId) {
677        for (final AbstractJingleConnection connection : this.connections.values()) {
678            if (connection.getId().sessionId.equals(sessionId)) {
679                if (connection instanceof JingleRtpConnection) {
680                    ((JingleRtpConnection) connection).rejectCall();
681                }
682            }
683        }
684    }
685
686    public void endRtpSession(final String sessionId) {
687        for (final AbstractJingleConnection connection : this.connections.values()) {
688            if (connection.getId().sessionId.equals(sessionId)) {
689                if (connection instanceof JingleRtpConnection) {
690                    ((JingleRtpConnection) connection).endCall();
691                }
692            }
693        }
694    }
695
696    public void failProceed(Account account, final Jid with, String sessionId) {
697        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
698        final AbstractJingleConnection existingJingleConnection = connections.get(id);
699        if (existingJingleConnection instanceof JingleRtpConnection) {
700            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed();
701        }
702    }
703
704    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
705        if (connections.containsValue(connection)) {
706            return;
707        }
708        final IllegalStateException e = new IllegalStateException("JingleConnection has not been registered with connection manager");
709        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
710        throw e;
711    }
712
713    void setTerminalSessionState(AbstractJingleConnection.Id id, final RtpEndUserState state, final Set<Media> media) {
714        this.terminatedSessions.put(PersistableSessionId.of(id), new TerminatedRtpSession(state, media));
715    }
716
717    public TerminatedRtpSession getTerminalSessionState(final Jid with, final String sessionId) {
718        return this.terminatedSessions.getIfPresent(new PersistableSessionId(with, sessionId));
719    }
720
721    private static class PersistableSessionId {
722        private final Jid with;
723        private final String sessionId;
724
725        private PersistableSessionId(Jid with, String sessionId) {
726            this.with = with;
727            this.sessionId = sessionId;
728        }
729
730        public static PersistableSessionId of(AbstractJingleConnection.Id id) {
731            return new PersistableSessionId(id.with, id.sessionId);
732        }
733
734        @Override
735        public boolean equals(Object o) {
736            if (this == o) return true;
737            if (o == null || getClass() != o.getClass()) return false;
738            PersistableSessionId that = (PersistableSessionId) o;
739            return Objects.equal(with, that.with) &&
740                    Objects.equal(sessionId, that.sessionId);
741        }
742
743        @Override
744        public int hashCode() {
745            return Objects.hashCode(with, sessionId);
746        }
747    }
748
749    public static class TerminatedRtpSession {
750        public final RtpEndUserState state;
751        public final Set<Media> media;
752
753        TerminatedRtpSession(RtpEndUserState state, Set<Media> media) {
754            this.state = state;
755            this.media = media;
756        }
757    }
758
759    public enum DeviceDiscoveryState {
760        SEARCHING, DISCOVERED, FAILED;
761
762        public RtpEndUserState toEndUserState() {
763            switch (this) {
764                case SEARCHING:
765                    return RtpEndUserState.FINDING_DEVICE;
766                case DISCOVERED:
767                    return RtpEndUserState.RINGING;
768                default:
769                    return RtpEndUserState.CONNECTIVITY_ERROR;
770            }
771        }
772    }
773
774    public static class RtpSessionProposal implements OngoingRtpSession {
775        public final Jid with;
776        public final String sessionId;
777        public final Set<Media> media;
778        private final Account account;
779
780        private RtpSessionProposal(Account account, Jid with, String sessionId) {
781            this(account, with, sessionId, Collections.emptySet());
782        }
783
784        private RtpSessionProposal(Account account, Jid with, String sessionId, Set<Media> media) {
785            this.account = account;
786            this.with = with;
787            this.sessionId = sessionId;
788            this.media = media;
789        }
790
791        public static RtpSessionProposal of(Account account, Jid with, Set<Media> media) {
792            return new RtpSessionProposal(account, with, nextRandomId(), media);
793        }
794
795        @Override
796        public boolean equals(Object o) {
797            if (this == o) return true;
798            if (o == null || getClass() != o.getClass()) return false;
799            RtpSessionProposal proposal = (RtpSessionProposal) o;
800            return Objects.equal(account.getJid(), proposal.account.getJid()) &&
801                    Objects.equal(with, proposal.with) &&
802                    Objects.equal(sessionId, proposal.sessionId);
803        }
804
805        @Override
806        public int hashCode() {
807            return Objects.hashCode(account.getJid(), with, sessionId);
808        }
809
810        @Override
811        public Account getAccount() {
812            return account;
813        }
814
815        @Override
816        public Jid getWith() {
817            return with;
818        }
819
820        @Override
821        public String getSessionId() {
822            return sessionId;
823        }
824    }
825}