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 remoteMsgId, 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 boolean addressedDirectly = to != null && to.equals(account.getJid());
178        final AbstractJingleConnection.Id id;
179        if (fromSelf) {
180            if (to != null && to.isFullJid()) {
181                id = AbstractJingleConnection.Id.of(account, to, sessionId);
182            } else {
183                return;
184            }
185        } else {
186            id = AbstractJingleConnection.Id.of(account, from, sessionId);
187        }
188        final AbstractJingleConnection existingJingleConnection = connections.get(id);
189        if (existingJingleConnection != null) {
190            if (existingJingleConnection instanceof JingleRtpConnection) {
191                ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message, serverMsgId, timestamp);
192            } else {
193                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
194            }
195            return;
196        }
197
198        if (fromSelf) {
199            if ("proceed".equals(message.getName())) {
200                final Conversation c = mXmppConnectionService.findOrCreateConversation(account, id.with, false, false);
201                final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
202                if (previousBusy != null) {
203                    previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
204                    if (serverMsgId != null) {
205                        previousBusy.setServerMsgId(serverMsgId);
206                    }
207                    previousBusy.setTime(timestamp);
208                    mXmppConnectionService.updateMessage(previousBusy, true);
209                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": updated previous busy because call got picked up by another device");
210                    return;
211                }
212            }
213            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore jingle message from self");
214            return;
215        }
216
217        if ("propose".equals(message.getName())) {
218            final Propose propose = Propose.upgrade(message);
219            final List<GenericDescription> descriptions = propose.getDescriptions();
220            final Collection<RtpDescription> rtpDescriptions = Collections2.transform(
221                    Collections2.filter(descriptions, d -> d instanceof RtpDescription),
222                    input -> (RtpDescription) input
223            );
224            if (rtpDescriptions.size() > 0 && rtpDescriptions.size() == descriptions.size() && !usesTor(account)) {
225                final Collection<Media> media = Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
226                if (media.contains(Media.UNKNOWN)) {
227                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered unknown media in session proposal. " + propose);
228                    return;
229                }
230                final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
231                if (isBusy() || stranger) {
232                    writeLogMissedIncoming(account, id.with.asBareJid(), id.sessionId, serverMsgId, timestamp);
233                    if (stranger) {
234                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring call proposal from stranger " + id.with);
235                        return;
236                    }
237                    final int activeDevices = account.activeDevicesWithRtpCapability();
238                    Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
239                    if (activeDevices == 0) {
240                        final MessagePacket reject = mXmppConnectionService.getMessageGenerator().sessionReject(from, sessionId);
241                        mXmppConnectionService.sendMessagePacket(account, reject);
242                    } else {
243                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring proposal because busy on this device but there are other devices");
244                    }
245                } else {
246                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
247                    this.connections.put(id, rtpConnection);
248                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
249                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
250                }
251            } else {
252                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed session with " + rtpDescriptions.size() + " rtp descriptions of " + descriptions.size() + " total descriptions");
253            }
254        } else if (addressedDirectly && "proceed".equals(message.getName())) {
255            synchronized (rtpSessionProposals) {
256                final RtpSessionProposal proposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
257                if (proposal != null) {
258                    rtpSessionProposals.remove(proposal);
259                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
260                    rtpConnection.setProposedMedia(proposal.media);
261                    this.connections.put(id, rtpConnection);
262                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
263                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
264                } else {
265                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver proceed");
266                    if (remoteMsgId == null) {
267                        return;
268                    }
269                    final MessagePacket errorMessage = new MessagePacket();
270                    errorMessage.setTo(from);
271                    errorMessage.setId(remoteMsgId);
272                    errorMessage.setType(MessagePacket.TYPE_ERROR);
273                    final Element error = errorMessage.addChild("error");
274                    error.setAttribute("code", "404");
275                    error.setAttribute("type", "cancel");
276                    error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
277                    mXmppConnectionService.sendMessagePacket(account, errorMessage);
278                }
279            }
280        } else if (addressedDirectly && "reject".equals(message.getName())) {
281            final RtpSessionProposal proposal = new RtpSessionProposal(account, from.asBareJid(), sessionId);
282            synchronized (rtpSessionProposals) {
283                if (rtpSessionProposals.remove(proposal) != null) {
284                    writeLogMissedOutgoing(account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
285                    toneManager.transition(RtpEndUserState.DECLINED_OR_BUSY);
286                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, proposal.with, proposal.sessionId, RtpEndUserState.DECLINED_OR_BUSY);
287                } else {
288                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver reject");
289                }
290            }
291        } else {
292            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message");
293        }
294
295    }
296
297    private RtpSessionProposal getRtpSessionProposal(final Account account, Jid from, String sessionId) {
298        for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
299            if (rtpSessionProposal.sessionId.equals(sessionId) && rtpSessionProposal.with.equals(from) && rtpSessionProposal.account.getJid().equals(account.getJid())) {
300                return rtpSessionProposal;
301            }
302        }
303        return null;
304    }
305
306    private void writeLogMissedOutgoing(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
307        final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
308                account,
309                with.asBareJid(),
310                false,
311                false
312        );
313        final Message message = new Message(
314                conversation,
315                Message.STATUS_SEND,
316                Message.TYPE_RTP_SESSION,
317                sessionId
318        );
319        message.setBody(new RtpSessionStatus(false, 0).toString());
320        message.setServerMsgId(serverMsgId);
321        message.setTime(timestamp);
322        writeMessage(message);
323    }
324
325    private void writeLogMissedIncoming(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
326        final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
327                account,
328                with.asBareJid(),
329                false,
330                false
331        );
332        final Message message = new Message(
333                conversation,
334                Message.STATUS_RECEIVED,
335                Message.TYPE_RTP_SESSION,
336                sessionId
337        );
338        message.setBody(new RtpSessionStatus(false, 0).toString());
339        message.setServerMsgId(serverMsgId);
340        message.setTime(timestamp);
341        writeMessage(message);
342    }
343
344    private void writeMessage(final Message message) {
345        final Conversational conversational = message.getConversation();
346        if (conversational instanceof Conversation) {
347            ((Conversation) conversational).add(message);
348            mXmppConnectionService.databaseBackend.createMessage(message);
349            mXmppConnectionService.updateConversationUi();
350        } else {
351            throw new IllegalStateException("Somehow the conversation in a message was a stub");
352        }
353    }
354
355    public void startJingleFileTransfer(final Message message) {
356        Preconditions.checkArgument(message.isFileOrImage(), "Message is not of type file or image");
357        final Transferable old = message.getTransferable();
358        if (old != null) {
359            old.cancel();
360        }
361        final Account account = message.getConversation().getAccount();
362        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
363        final JingleFileTransferConnection connection = new JingleFileTransferConnection(this, id, account.getJid());
364        mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
365        this.connections.put(id, connection);
366        connection.init(message);
367    }
368
369    public Optional<OngoingRtpSession> getOngoingRtpConnection(final Contact contact) {
370        for (final Map.Entry<AbstractJingleConnection.Id, AbstractJingleConnection> entry : this.connections.entrySet()) {
371            if (entry.getValue() instanceof JingleRtpConnection) {
372                final AbstractJingleConnection.Id id = entry.getKey();
373                if (id.account == contact.getAccount() && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
374                    return Optional.of(id);
375                }
376            }
377        }
378        synchronized (this.rtpSessionProposals) {
379            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
380                RtpSessionProposal proposal = entry.getKey();
381                if (proposal.account == contact.getAccount() && contact.getJid().asBareJid().equals(proposal.with)) {
382                    final DeviceDiscoveryState preexistingState = entry.getValue();
383                    if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
384                        return Optional.of(proposal);
385                    }
386                }
387            }
388        }
389        return Optional.absent();
390    }
391
392    void finishConnection(final AbstractJingleConnection connection) {
393        this.connections.remove(connection.getId());
394    }
395
396    void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
397        if (Config.DISABLE_PROXY_LOOKUP) {
398            listener.onPrimaryCandidateFound(false, null);
399            return;
400        }
401        if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
402            final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
403            if (proxy != null) {
404                IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
405                iq.setTo(proxy);
406                iq.query(Namespace.BYTE_STREAMS);
407                account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
408
409                    @Override
410                    public void onIqPacketReceived(Account account, IqPacket packet) {
411                        final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
412                        final String host = streamhost == null ? null : streamhost.getAttribute("host");
413                        final String port = streamhost == null ? null : streamhost.getAttribute("port");
414                        if (host != null && port != null) {
415                            try {
416                                JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
417                                candidate.setHost(host);
418                                candidate.setPort(Integer.parseInt(port));
419                                candidate.setType(JingleCandidate.TYPE_PROXY);
420                                candidate.setJid(proxy);
421                                candidate.setPriority(655360 + (initiator ? 30 : 0));
422                                primaryCandidates.put(account.getJid().asBareJid(), candidate);
423                                listener.onPrimaryCandidateFound(true, candidate);
424                            } catch (final NumberFormatException e) {
425                                listener.onPrimaryCandidateFound(false, null);
426                            }
427                        } else {
428                            listener.onPrimaryCandidateFound(false, null);
429                        }
430                    }
431                });
432            } else {
433                listener.onPrimaryCandidateFound(false, null);
434            }
435
436        } else {
437            listener.onPrimaryCandidateFound(true,
438                    this.primaryCandidates.get(account.getJid().asBareJid()));
439        }
440    }
441
442    public void retractSessionProposal(final Account account, final Jid with) {
443        synchronized (this.rtpSessionProposals) {
444            RtpSessionProposal matchingProposal = null;
445            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
446                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
447                    matchingProposal = proposal;
448                    break;
449                }
450            }
451            if (matchingProposal != null) {
452                toneManager.transition(RtpEndUserState.ENDED);
453                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retracting rtp session proposal with " + with);
454                this.rtpSessionProposals.remove(matchingProposal);
455                final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionRetract(matchingProposal);
456                writeLogMissedOutgoing(account, matchingProposal.with, matchingProposal.sessionId, null, System.currentTimeMillis());
457                mXmppConnectionService.sendMessagePacket(account, messagePacket);
458            }
459        }
460    }
461
462    public void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
463        synchronized (this.rtpSessionProposals) {
464            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
465                RtpSessionProposal proposal = entry.getKey();
466                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
467                    final DeviceDiscoveryState preexistingState = entry.getValue();
468                    if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
469                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
470                        toneManager.transition(endUserState);
471                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
472                                account,
473                                with,
474                                proposal.sessionId,
475                                endUserState
476                        );
477                        return;
478                    }
479                }
480            }
481            if (isBusy()) {
482                throw new IllegalStateException("There is already a running RTP session. This should have been caught by the UI");
483            }
484            final RtpSessionProposal proposal = RtpSessionProposal.of(account, with.asBareJid(), media);
485            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
486            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
487                    account,
488                    proposal.with,
489                    proposal.sessionId,
490                    RtpEndUserState.FINDING_DEVICE
491            );
492            final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
493            Log.d(Config.LOGTAG, messagePacket.toString());
494            mXmppConnectionService.sendMessagePacket(account, messagePacket);
495        }
496    }
497
498    public void deliverIbbPacket(Account account, IqPacket packet) {
499        final String sid;
500        final Element payload;
501        if (packet.hasChild("open", Namespace.IBB)) {
502            payload = packet.findChild("open", Namespace.IBB);
503            sid = payload.getAttribute("sid");
504        } else if (packet.hasChild("data", Namespace.IBB)) {
505            payload = packet.findChild("data", Namespace.IBB);
506            sid = payload.getAttribute("sid");
507        } else if (packet.hasChild("close", Namespace.IBB)) {
508            payload = packet.findChild("close", Namespace.IBB);
509            sid = payload.getAttribute("sid");
510        } else {
511            payload = null;
512            sid = null;
513        }
514        if (sid != null) {
515            for (final AbstractJingleConnection connection : this.connections.values()) {
516                if (connection instanceof JingleFileTransferConnection) {
517                    final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
518                    final JingleTransport transport = fileTransfer.getTransport();
519                    if (transport instanceof JingleInBandTransport) {
520                        final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
521                        if (inBandTransport.matches(account, sid)) {
522                            inBandTransport.deliverPayload(packet, payload);
523                        }
524                        return;
525                    }
526                }
527            }
528        }
529        Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
530        account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
531    }
532
533    public void notifyRebound() {
534        for (final AbstractJingleConnection connection : this.connections.values()) {
535            connection.notifyRebound();
536        }
537    }
538
539    public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
540        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, Jid.ofEscaped(with), sessionId);
541        final AbstractJingleConnection connection = connections.get(id);
542        if (connection instanceof JingleRtpConnection) {
543            return new WeakReference<>((JingleRtpConnection) connection);
544        }
545        return null;
546    }
547
548    public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
549        synchronized (this.rtpSessionProposals) {
550            final RtpSessionProposal sessionProposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
551            final DeviceDiscoveryState currentState = sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
552            if (currentState == null) {
553                Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
554                return;
555            }
556            if (currentState == DeviceDiscoveryState.DISCOVERED) {
557                Log.d(Config.LOGTAG, "session proposal already at discovered. not going to fall back");
558                return;
559            }
560            this.rtpSessionProposals.put(sessionProposal, target);
561            final RtpEndUserState endUserState = target.toEndUserState();
562            toneManager.transition(endUserState);
563            mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, sessionProposal.with, sessionProposal.sessionId, endUserState);
564            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": flagging session " + sessionId + " as " + target);
565        }
566    }
567
568    public void rejectRtpSession(final String sessionId) {
569        for (final AbstractJingleConnection connection : this.connections.values()) {
570            if (connection.getId().sessionId.equals(sessionId)) {
571                if (connection instanceof JingleRtpConnection) {
572                    ((JingleRtpConnection) connection).rejectCall();
573                }
574            }
575        }
576    }
577
578    public void endRtpSession(final String sessionId) {
579        for (final AbstractJingleConnection connection : this.connections.values()) {
580            if (connection.getId().sessionId.equals(sessionId)) {
581                if (connection instanceof JingleRtpConnection) {
582                    ((JingleRtpConnection) connection).endCall();
583                }
584            }
585        }
586    }
587
588    public void failProceed(Account account, final Jid with, String sessionId) {
589        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
590        final AbstractJingleConnection existingJingleConnection = connections.get(id);
591        if (existingJingleConnection instanceof JingleRtpConnection) {
592            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed();
593        }
594    }
595
596    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
597        if (connections.containsValue(connection)) {
598            return;
599        }
600        final IllegalStateException e = new IllegalStateException("JingleConnection has not been registered with connection manager");
601        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
602        throw e;
603    }
604
605    public void endSession(AbstractJingleConnection.Id id, final AbstractJingleConnection.State state) {
606        this.endedSessions.put(PersistableSessionId.of(id), state);
607    }
608
609    private static class PersistableSessionId {
610        private final Jid with;
611        private final String sessionId;
612
613        private PersistableSessionId(Jid with, String sessionId) {
614            this.with = with;
615            this.sessionId = sessionId;
616        }
617
618        public static PersistableSessionId of(AbstractJingleConnection.Id id) {
619            return new PersistableSessionId(id.with, id.sessionId);
620        }
621
622        @Override
623        public boolean equals(Object o) {
624            if (this == o) return true;
625            if (o == null || getClass() != o.getClass()) return false;
626            PersistableSessionId that = (PersistableSessionId) o;
627            return Objects.equal(with, that.with) &&
628                    Objects.equal(sessionId, that.sessionId);
629        }
630
631        @Override
632        public int hashCode() {
633            return Objects.hashCode(with, sessionId);
634        }
635    }
636
637    public enum DeviceDiscoveryState {
638        SEARCHING, DISCOVERED, FAILED;
639
640        public RtpEndUserState toEndUserState() {
641            switch (this) {
642                case SEARCHING:
643                    return RtpEndUserState.FINDING_DEVICE;
644                case DISCOVERED:
645                    return RtpEndUserState.RINGING;
646                default:
647                    return RtpEndUserState.CONNECTIVITY_ERROR;
648            }
649        }
650    }
651
652    public static class RtpSessionProposal implements OngoingRtpSession {
653        public final Jid with;
654        public final String sessionId;
655        public final Set<Media> media;
656        private final Account account;
657
658        private RtpSessionProposal(Account account, Jid with, String sessionId) {
659            this(account, with, sessionId, Collections.emptySet());
660        }
661
662        private RtpSessionProposal(Account account, Jid with, String sessionId, Set<Media> media) {
663            this.account = account;
664            this.with = with;
665            this.sessionId = sessionId;
666            this.media = media;
667        }
668
669        public static RtpSessionProposal of(Account account, Jid with, Set<Media> media) {
670            return new RtpSessionProposal(account, with, nextRandomId(), media);
671        }
672
673        @Override
674        public boolean equals(Object o) {
675            if (this == o) return true;
676            if (o == null || getClass() != o.getClass()) return false;
677            RtpSessionProposal proposal = (RtpSessionProposal) o;
678            return Objects.equal(account.getJid(), proposal.account.getJid()) &&
679                    Objects.equal(with, proposal.with) &&
680                    Objects.equal(sessionId, proposal.sessionId);
681        }
682
683        @Override
684        public int hashCode() {
685            return Objects.hashCode(account.getJid(), with, sessionId);
686        }
687
688        @Override
689        public Account getAccount() {
690            return account;
691        }
692
693        @Override
694        public Jid getWith() {
695            return with;
696        }
697
698        @Override
699        public String getSessionId() {
700            return sessionId;
701        }
702    }
703}