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