JingleConnectionManager.java

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