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