JingleConnectionManager.java

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