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        this.connections.remove(connection.getId());
451    }
452
453    void finishConnectionOrThrow(final AbstractJingleConnection connection) {
454        final AbstractJingleConnection.Id id = connection.getId();
455        if (this.connections.remove(id) == null) {
456            throw new IllegalStateException(String.format("Unable to finish connection with id=%s", id.toString()));
457        }
458    }
459
460    void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
461        if (Config.DISABLE_PROXY_LOOKUP) {
462            listener.onPrimaryCandidateFound(false, null);
463            return;
464        }
465        if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
466            final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
467            if (proxy != null) {
468                IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
469                iq.setTo(proxy);
470                iq.query(Namespace.BYTE_STREAMS);
471                account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
472
473                    @Override
474                    public void onIqPacketReceived(Account account, IqPacket packet) {
475                        final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
476                        final String host = streamhost == null ? null : streamhost.getAttribute("host");
477                        final String port = streamhost == null ? null : streamhost.getAttribute("port");
478                        if (host != null && port != null) {
479                            try {
480                                JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
481                                candidate.setHost(host);
482                                candidate.setPort(Integer.parseInt(port));
483                                candidate.setType(JingleCandidate.TYPE_PROXY);
484                                candidate.setJid(proxy);
485                                candidate.setPriority(655360 + (initiator ? 30 : 0));
486                                primaryCandidates.put(account.getJid().asBareJid(), candidate);
487                                listener.onPrimaryCandidateFound(true, candidate);
488                            } catch (final NumberFormatException e) {
489                                listener.onPrimaryCandidateFound(false, null);
490                            }
491                        } else {
492                            listener.onPrimaryCandidateFound(false, null);
493                        }
494                    }
495                });
496            } else {
497                listener.onPrimaryCandidateFound(false, null);
498            }
499
500        } else {
501            listener.onPrimaryCandidateFound(true,
502                    this.primaryCandidates.get(account.getJid().asBareJid()));
503        }
504    }
505
506    public void retractSessionProposal(final Account account, final Jid with) {
507        synchronized (this.rtpSessionProposals) {
508            RtpSessionProposal matchingProposal = null;
509            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
510                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
511                    matchingProposal = proposal;
512                    break;
513                }
514            }
515            if (matchingProposal != null) {
516                retractSessionProposal(matchingProposal);
517            }
518        }
519    }
520
521    private void retractSessionProposal(RtpSessionProposal rtpSessionProposal) {
522        final Account account = rtpSessionProposal.account;
523        toneManager.transition(RtpEndUserState.ENDED, rtpSessionProposal.media);
524        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retracting rtp session proposal with " + rtpSessionProposal.with);
525        this.rtpSessionProposals.remove(rtpSessionProposal);
526        final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
527        writeLogMissedOutgoing(account, rtpSessionProposal.with, rtpSessionProposal.sessionId, null, System.currentTimeMillis());
528        mXmppConnectionService.sendMessagePacket(account, messagePacket);
529    }
530
531    public String initializeRtpSession(final Account account, final Jid with, final Set<Media> media) {
532        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
533        final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
534        rtpConnection.setProposedMedia(media);
535        this.connections.put(id, rtpConnection);
536        rtpConnection.sendSessionInitiate();
537        return id.sessionId;
538    }
539
540    public void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
541        synchronized (this.rtpSessionProposals) {
542            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
543                RtpSessionProposal proposal = entry.getKey();
544                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
545                    final DeviceDiscoveryState preexistingState = entry.getValue();
546                    if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
547                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
548                        toneManager.transition(endUserState, media);
549                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
550                                account,
551                                with,
552                                proposal.sessionId,
553                                endUserState
554                        );
555                        return;
556                    }
557                }
558            }
559            if (isBusy()) {
560                if (hasMatchingRtpSession(account, with, media)) {
561                    Log.d(Config.LOGTAG, "ignoring request to propose jingle session because the other party already created one for us");
562                    return;
563                }
564                throw new IllegalStateException("There is already a running RTP session. This should have been caught by the UI");
565            }
566            final RtpSessionProposal proposal = RtpSessionProposal.of(account, with.asBareJid(), media);
567            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
568            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
569                    account,
570                    proposal.with,
571                    proposal.sessionId,
572                    RtpEndUserState.FINDING_DEVICE
573            );
574            final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
575            Log.d(Config.LOGTAG, messagePacket.toString());
576            mXmppConnectionService.sendMessagePacket(account, messagePacket);
577        }
578    }
579
580    public void deliverIbbPacket(Account account, IqPacket packet) {
581        final String sid;
582        final Element payload;
583        if (packet.hasChild("open", Namespace.IBB)) {
584            payload = packet.findChild("open", Namespace.IBB);
585            sid = payload.getAttribute("sid");
586        } else if (packet.hasChild("data", Namespace.IBB)) {
587            payload = packet.findChild("data", Namespace.IBB);
588            sid = payload.getAttribute("sid");
589        } else if (packet.hasChild("close", Namespace.IBB)) {
590            payload = packet.findChild("close", Namespace.IBB);
591            sid = payload.getAttribute("sid");
592        } else {
593            payload = null;
594            sid = null;
595        }
596        if (sid != null) {
597            for (final AbstractJingleConnection connection : this.connections.values()) {
598                if (connection instanceof JingleFileTransferConnection) {
599                    final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
600                    final JingleTransport transport = fileTransfer.getTransport();
601                    if (transport instanceof JingleInBandTransport) {
602                        final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
603                        if (inBandTransport.matches(account, sid)) {
604                            inBandTransport.deliverPayload(packet, payload);
605                        }
606                        return;
607                    }
608                }
609            }
610        }
611        Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
612        account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
613    }
614
615    public void notifyRebound() {
616        for (final AbstractJingleConnection connection : this.connections.values()) {
617            connection.notifyRebound();
618        }
619    }
620
621    public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
622        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
623        final AbstractJingleConnection connection = connections.get(id);
624        if (connection instanceof JingleRtpConnection) {
625            return new WeakReference<>((JingleRtpConnection) connection);
626        }
627        return null;
628    }
629
630    public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
631        synchronized (this.rtpSessionProposals) {
632            final RtpSessionProposal sessionProposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
633            final DeviceDiscoveryState currentState = sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
634            if (currentState == null) {
635                Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
636                return;
637            }
638            if (currentState == DeviceDiscoveryState.DISCOVERED) {
639                Log.d(Config.LOGTAG, "session proposal already at discovered. not going to fall back");
640                return;
641            }
642            this.rtpSessionProposals.put(sessionProposal, target);
643            final RtpEndUserState endUserState = target.toEndUserState();
644            toneManager.transition(endUserState, sessionProposal.media);
645            mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, sessionProposal.with, sessionProposal.sessionId, endUserState);
646            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": flagging session " + sessionId + " as " + target);
647        }
648    }
649
650    public void rejectRtpSession(final String sessionId) {
651        for (final AbstractJingleConnection connection : this.connections.values()) {
652            if (connection.getId().sessionId.equals(sessionId)) {
653                if (connection instanceof JingleRtpConnection) {
654                    ((JingleRtpConnection) connection).rejectCall();
655                }
656            }
657        }
658    }
659
660    public void endRtpSession(final String sessionId) {
661        for (final AbstractJingleConnection connection : this.connections.values()) {
662            if (connection.getId().sessionId.equals(sessionId)) {
663                if (connection instanceof JingleRtpConnection) {
664                    ((JingleRtpConnection) connection).endCall();
665                }
666            }
667        }
668    }
669
670    public void failProceed(Account account, final Jid with, String sessionId) {
671        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
672        final AbstractJingleConnection existingJingleConnection = connections.get(id);
673        if (existingJingleConnection instanceof JingleRtpConnection) {
674            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed();
675        }
676    }
677
678    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
679        if (connections.containsValue(connection)) {
680            return;
681        }
682        final IllegalStateException e = new IllegalStateException("JingleConnection has not been registered with connection manager");
683        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
684        throw e;
685    }
686
687    void endSession(AbstractJingleConnection.Id id, final AbstractJingleConnection.State state) {
688        this.endedSessions.put(PersistableSessionId.of(id), state);
689    }
690
691    private static class PersistableSessionId {
692        private final Jid with;
693        private final String sessionId;
694
695        private PersistableSessionId(Jid with, String sessionId) {
696            this.with = with;
697            this.sessionId = sessionId;
698        }
699
700        public static PersistableSessionId of(AbstractJingleConnection.Id id) {
701            return new PersistableSessionId(id.with, id.sessionId);
702        }
703
704        @Override
705        public boolean equals(Object o) {
706            if (this == o) return true;
707            if (o == null || getClass() != o.getClass()) return false;
708            PersistableSessionId that = (PersistableSessionId) o;
709            return Objects.equal(with, that.with) &&
710                    Objects.equal(sessionId, that.sessionId);
711        }
712
713        @Override
714        public int hashCode() {
715            return Objects.hashCode(with, sessionId);
716        }
717    }
718
719    public enum DeviceDiscoveryState {
720        SEARCHING, DISCOVERED, FAILED;
721
722        public RtpEndUserState toEndUserState() {
723            switch (this) {
724                case SEARCHING:
725                    return RtpEndUserState.FINDING_DEVICE;
726                case DISCOVERED:
727                    return RtpEndUserState.RINGING;
728                default:
729                    return RtpEndUserState.CONNECTIVITY_ERROR;
730            }
731        }
732    }
733
734    public static class RtpSessionProposal implements OngoingRtpSession {
735        public final Jid with;
736        public final String sessionId;
737        public final Set<Media> media;
738        private final Account account;
739
740        private RtpSessionProposal(Account account, Jid with, String sessionId) {
741            this(account, with, sessionId, Collections.emptySet());
742        }
743
744        private RtpSessionProposal(Account account, Jid with, String sessionId, Set<Media> media) {
745            this.account = account;
746            this.with = with;
747            this.sessionId = sessionId;
748            this.media = media;
749        }
750
751        public static RtpSessionProposal of(Account account, Jid with, Set<Media> media) {
752            return new RtpSessionProposal(account, with, nextRandomId(), media);
753        }
754
755        @Override
756        public boolean equals(Object o) {
757            if (this == o) return true;
758            if (o == null || getClass() != o.getClass()) return false;
759            RtpSessionProposal proposal = (RtpSessionProposal) o;
760            return Objects.equal(account.getJid(), proposal.account.getJid()) &&
761                    Objects.equal(with, proposal.with) &&
762                    Objects.equal(sessionId, proposal.sessionId);
763        }
764
765        @Override
766        public int hashCode() {
767            return Objects.hashCode(account.getJid(), with, sessionId);
768        }
769
770        @Override
771        public Account getAccount() {
772            return account;
773        }
774
775        @Override
776        public Jid getWith() {
777            return with;
778        }
779
780        @Override
781        public String getSessionId() {
782            return sessionId;
783        }
784    }
785}