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