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