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