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