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