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