1package eu.siacs.conversations.xmpp.jingle;
2
3import android.telecom.VideoProfile;
4import android.util.Base64;
5import android.util.Log;
6
7import androidx.annotation.Nullable;
8
9import com.google.common.base.Objects;
10import com.google.common.base.Optional;
11import com.google.common.base.Preconditions;
12import com.google.common.cache.Cache;
13import com.google.common.cache.CacheBuilder;
14import com.google.common.collect.Collections2;
15import com.google.common.collect.ComparisonChain;
16import com.google.common.collect.ImmutableSet;
17
18import eu.siacs.conversations.Config;
19import eu.siacs.conversations.entities.Account;
20import eu.siacs.conversations.entities.Contact;
21import eu.siacs.conversations.entities.Conversation;
22import eu.siacs.conversations.entities.Conversational;
23import eu.siacs.conversations.entities.Message;
24import eu.siacs.conversations.entities.RtpSessionStatus;
25import eu.siacs.conversations.entities.Transferable;
26import eu.siacs.conversations.services.AbstractConnectionManager;
27import eu.siacs.conversations.services.CallIntegration;
28import eu.siacs.conversations.services.CallIntegrationConnectionService;
29import eu.siacs.conversations.services.XmppConnectionService;
30import eu.siacs.conversations.xml.Element;
31import eu.siacs.conversations.xml.Namespace;
32import eu.siacs.conversations.xmpp.Jid;
33import eu.siacs.conversations.xmpp.XmppConnection;
34import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
35import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
36import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
37import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
38import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
39import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
40import eu.siacs.conversations.xmpp.jingle.transports.InbandBytestreamsTransport;
41import eu.siacs.conversations.xmpp.jingle.transports.Transport;
42import eu.siacs.conversations.xmpp.stanzas.IqPacket;
43import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
44
45import java.lang.ref.WeakReference;
46import java.security.SecureRandom;
47import java.util.Collection;
48import java.util.HashMap;
49import java.util.List;
50import java.util.Map;
51import java.util.Set;
52import java.util.concurrent.ConcurrentHashMap;
53import java.util.concurrent.Executors;
54import java.util.concurrent.ScheduledExecutorService;
55import java.util.concurrent.ScheduledFuture;
56import java.util.concurrent.TimeUnit;
57
58public class JingleConnectionManager extends AbstractConnectionManager {
59 public static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE =
60 Executors.newSingleThreadScheduledExecutor();
61 private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals =
62 new HashMap<>();
63 private final ConcurrentHashMap<AbstractJingleConnection.Id, AbstractJingleConnection>
64 connections = new ConcurrentHashMap<>();
65
66 private final Cache<PersistableSessionId, TerminatedRtpSession> terminatedSessions =
67 CacheBuilder.newBuilder().expireAfterWrite(24, TimeUnit.HOURS).build();
68
69 public JingleConnectionManager(XmppConnectionService service) {
70 super(service);
71 }
72
73 static String nextRandomId() {
74 final byte[] id = new byte[16];
75 new SecureRandom().nextBytes(id);
76 return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE);
77 }
78
79 public void deliverPacket(final Account account, final JinglePacket packet) {
80 final String sessionId = packet.getSessionId();
81 final JinglePacket.Action action = packet.getAction();
82 if (sessionId == null) {
83 respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
84 return;
85 }
86 if (action == null) {
87 respondWithJingleError(account, packet, null, "bad-request", "cancel");
88 return;
89 }
90 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, packet);
91 final AbstractJingleConnection existingJingleConnection = connections.get(id);
92 if (existingJingleConnection != null) {
93 existingJingleConnection.deliverPacket(packet);
94 } else if (action == JinglePacket.Action.SESSION_INITIATE) {
95 final Jid from = packet.getFrom();
96 final Content content = packet.getJingleContent();
97 final String descriptionNamespace =
98 content == null ? null : content.getDescriptionNamespace();
99 final AbstractJingleConnection connection;
100 if (Namespace.JINGLE_APPS_FILE_TRANSFER.equals(descriptionNamespace)) {
101 connection = new JingleFileTransferConnection(this, id, from);
102 } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace)
103 && isUsingClearNet(account)) {
104 final boolean sessionEnded =
105 this.terminatedSessions.asMap().containsKey(PersistableSessionId.of(id));
106 final boolean stranger =
107 isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
108 final boolean busy = isBusy();
109 if (busy || sessionEnded || stranger) {
110 Log.d(
111 Config.LOGTAG,
112 id.account.getJid().asBareJid()
113 + ": rejected session with "
114 + id.with
115 + " because busy. sessionEnded="
116 + sessionEnded
117 + ", stranger="
118 + stranger);
119 sendSessionTerminate(account, packet, id);
120 if (busy || stranger) {
121 writeLogMissedIncoming(
122 account,
123 id.with,
124 id.sessionId,
125 null,
126 System.currentTimeMillis(),
127 stranger);
128 }
129 return;
130 }
131 connection = new JingleRtpConnection(this, id, from);
132 } else {
133 respondWithJingleError(
134 account, packet, "unsupported-info", "feature-not-implemented", "cancel");
135 return;
136 }
137 connections.put(id, connection);
138 mXmppConnectionService.updateConversationUi();
139 connection.deliverPacket(packet);
140 if (connection instanceof JingleRtpConnection rtpConnection) {
141 addNewIncomingCall(rtpConnection);
142 }
143 } else {
144 Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
145 respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
146 }
147 }
148
149 private void addNewIncomingCall(final JingleRtpConnection rtpConnection) {
150 if (rtpConnection.isTerminated()) {
151 Log.d(
152 Config.LOGTAG,
153 "skip call integration because something must have gone during initiate");
154 return;
155 }
156 if (CallIntegrationConnectionService.addNewIncomingCall(
157 mXmppConnectionService, rtpConnection.getId())) {
158 return;
159 }
160 rtpConnection.integrationFailure();
161 }
162
163 private void sendSessionTerminate(
164 final Account account, final IqPacket request, final AbstractJingleConnection.Id id) {
165 mXmppConnectionService.sendIqPacket(
166 account, request.generateResponse(IqPacket.TYPE.RESULT), null);
167 final JinglePacket sessionTermination =
168 new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
169 sessionTermination.setTo(id.with);
170 sessionTermination.setReason(Reason.BUSY, null);
171 mXmppConnectionService.sendIqPacket(account, sessionTermination, null);
172 }
173
174 private boolean isUsingClearNet(final Account account) {
175 return !account.isOnion() && !mXmppConnectionService.useTorToConnect();
176 }
177
178 public boolean isBusy() {
179 for (final AbstractJingleConnection connection : this.connections.values()) {
180 if (connection instanceof JingleRtpConnection rtpConnection) {
181 if (connection.isTerminated() && rtpConnection.getCallIntegration().isDestroyed()) {
182 continue;
183 }
184 return true;
185 }
186 }
187 synchronized (this.rtpSessionProposals) {
188 return this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED)
189 || this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING)
190 || this.rtpSessionProposals.containsValue(
191 DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED);
192 }
193 }
194
195 public boolean hasJingleRtpConnection(final Account account) {
196 for (AbstractJingleConnection connection : this.connections.values()) {
197 if (connection instanceof JingleRtpConnection rtpConnection) {
198 if (rtpConnection.isTerminated()) {
199 continue;
200 }
201 if (rtpConnection.id.account == account) {
202 return true;
203 }
204 }
205 }
206 return false;
207 }
208
209 private Optional<RtpSessionProposal> findMatchingSessionProposal(
210 final Account account, final Jid with, final Set<Media> media) {
211 synchronized (this.rtpSessionProposals) {
212 for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
213 this.rtpSessionProposals.entrySet()) {
214 final RtpSessionProposal proposal = entry.getKey();
215 final DeviceDiscoveryState state = entry.getValue();
216 final boolean openProposal =
217 state == DeviceDiscoveryState.DISCOVERED
218 || state == DeviceDiscoveryState.SEARCHING
219 || state == DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED;
220 if (openProposal
221 && proposal.account == account
222 && proposal.with.equals(with.asBareJid())
223 && proposal.media.equals(media)) {
224 return Optional.of(proposal);
225 }
226 }
227 }
228 return Optional.absent();
229 }
230
231 private boolean hasMatchingRtpSession(
232 final Account account, final Jid with, final Set<Media> media) {
233 for (AbstractJingleConnection connection : this.connections.values()) {
234 if (connection instanceof JingleRtpConnection rtpConnection) {
235 if (rtpConnection.isTerminated()) {
236 continue;
237 }
238 if (rtpConnection.getId().account == account
239 && rtpConnection.getId().with.asBareJid().equals(with.asBareJid())
240 && rtpConnection.getMedia().equals(media)) {
241 return true;
242 }
243 }
244 }
245 return false;
246 }
247
248 private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
249 final boolean notifyForStrangers =
250 mXmppConnectionService.getNotificationService().notificationsFromStrangers();
251 if (notifyForStrangers) {
252 return false;
253 }
254 final Contact contact = account.getRoster().getContact(with);
255 return !contact.showInContactList();
256 }
257
258 ScheduledFuture<?> schedule(
259 final Runnable runnable, final long delay, final TimeUnit timeUnit) {
260 return SCHEDULED_EXECUTOR_SERVICE.schedule(runnable, delay, timeUnit);
261 }
262
263 void respondWithJingleError(
264 final Account account,
265 final IqPacket original,
266 final String jingleCondition,
267 final String condition,
268 final String conditionType) {
269 final IqPacket response = original.generateResponse(IqPacket.TYPE.ERROR);
270 final Element error = response.addChild("error");
271 error.setAttribute("type", conditionType);
272 error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
273 if (jingleCondition != null) {
274 error.addChild(jingleCondition, Namespace.JINGLE_ERRORS);
275 }
276 account.getXmppConnection().sendIqPacket(response, null);
277 }
278
279 public void deliverMessage(
280 final Account account,
281 final Jid to,
282 final Jid from,
283 final Element message,
284 String remoteMsgId,
285 String serverMsgId,
286 long timestamp) {
287 Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
288 final String sessionId = message.getAttribute("id");
289 if (sessionId == null) {
290 return;
291 }
292 if ("accept".equals(message.getName())) {
293 for (AbstractJingleConnection connection : connections.values()) {
294 if (connection instanceof JingleRtpConnection rtpConnection) {
295 final AbstractJingleConnection.Id id = connection.getId();
296 if (id.account == account && id.sessionId.equals(sessionId)) {
297 rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
298 return;
299 }
300 }
301 }
302 return;
303 }
304 final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
305 // XEP version 0.6.0 sends proceed, reject, ringing to bare jid
306 final boolean addressedDirectly = to != null && to.equals(account.getJid());
307 final AbstractJingleConnection.Id id;
308 if (fromSelf) {
309 if (to != null && to.isFullJid()) {
310 id = AbstractJingleConnection.Id.of(account, to, sessionId);
311 } else {
312 return;
313 }
314 } else {
315 id = AbstractJingleConnection.Id.of(account, from, sessionId);
316 }
317 final AbstractJingleConnection existingJingleConnection = connections.get(id);
318 if (existingJingleConnection != null) {
319 if (existingJingleConnection instanceof JingleRtpConnection) {
320 ((JingleRtpConnection) existingJingleConnection)
321 .deliveryMessage(from, message, serverMsgId, timestamp);
322 } else {
323 Log.d(
324 Config.LOGTAG,
325 account.getJid().asBareJid()
326 + ": "
327 + existingJingleConnection.getClass().getName()
328 + " does not support jingle messages");
329 }
330 return;
331 }
332
333 if (fromSelf) {
334 if ("proceed".equals(message.getName())) {
335 final Conversation c =
336 mXmppConnectionService.findOrCreateConversation(
337 account, id.with, false, false);
338 final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
339 if (previousBusy != null) {
340 previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
341 if (serverMsgId != null) {
342 previousBusy.setServerMsgId(serverMsgId);
343 }
344 previousBusy.setTime(timestamp);
345 mXmppConnectionService.updateMessage(previousBusy, true);
346 Log.d(
347 Config.LOGTAG,
348 id.account.getJid().asBareJid()
349 + ": updated previous busy because call got picked up by another device");
350 mXmppConnectionService.getNotificationService().clearMissedCall(previousBusy);
351 return;
352 }
353 }
354 // TODO handle reject for cases where we don’t have carbon copies (normally reject is to
355 // be sent to own bare jid as well)
356 Log.d(
357 Config.LOGTAG,
358 account.getJid().asBareJid() + ": ignore jingle message from self");
359 return;
360 }
361
362 if ("propose".equals(message.getName())) {
363 final Propose propose = Propose.upgrade(message);
364 final List<GenericDescription> descriptions = propose.getDescriptions();
365 final Collection<RtpDescription> rtpDescriptions =
366 Collections2.transform(
367 Collections2.filter(descriptions, d -> d instanceof RtpDescription),
368 input -> (RtpDescription) input);
369 if (rtpDescriptions.size() > 0
370 && rtpDescriptions.size() == descriptions.size()
371 && isUsingClearNet(account)) {
372 final Collection<Media> media =
373 Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
374 if (media.contains(Media.UNKNOWN)) {
375 Log.d(
376 Config.LOGTAG,
377 account.getJid().asBareJid()
378 + ": encountered unknown media in session proposal. "
379 + propose);
380 return;
381 }
382 final Optional<RtpSessionProposal> matchingSessionProposal =
383 findMatchingSessionProposal(account, id.with, ImmutableSet.copyOf(media));
384 if (matchingSessionProposal.isPresent()) {
385 final String ourSessionId = matchingSessionProposal.get().sessionId;
386 final String theirSessionId = id.sessionId;
387 if (ComparisonChain.start()
388 .compare(ourSessionId, theirSessionId)
389 .compare(
390 account.getJid().toEscapedString(),
391 id.with.toEscapedString())
392 .result()
393 > 0) {
394 Log.d(
395 Config.LOGTAG,
396 account.getJid().asBareJid()
397 + ": our session lost tie break. automatically accepting their session. winning Session="
398 + theirSessionId);
399 // TODO a retract for this reason should probably include some indication of
400 // tie break
401 retractSessionProposal(matchingSessionProposal.get());
402 final JingleRtpConnection rtpConnection =
403 new JingleRtpConnection(this, id, from);
404 this.connections.put(id, rtpConnection);
405 rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
406 rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
407 addNewIncomingCall(rtpConnection);
408 // TODO actually do the automatic accept?!
409 } else {
410 Log.d(
411 Config.LOGTAG,
412 account.getJid().asBareJid()
413 + ": our session won tie break. waiting for other party to accept. winningSession="
414 + ourSessionId);
415 // TODO reject their session with <tie-break/>?
416 }
417 return;
418 }
419 final boolean stranger =
420 isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
421 if (isBusy() || stranger) {
422 writeLogMissedIncoming(
423 account,
424 id.with.asBareJid(),
425 id.sessionId,
426 serverMsgId,
427 timestamp,
428 stranger);
429 if (stranger) {
430 Log.d(
431 Config.LOGTAG,
432 id.account.getJid().asBareJid()
433 + ": ignoring call proposal from stranger "
434 + id.with);
435 return;
436 }
437 final int activeDevices = account.activeDevicesWithRtpCapability();
438 Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
439 if (activeDevices == 0) {
440 final MessagePacket reject =
441 mXmppConnectionService
442 .getMessageGenerator()
443 .sessionReject(from, sessionId);
444 mXmppConnectionService.sendMessagePacket(account, reject);
445 } else {
446 Log.d(
447 Config.LOGTAG,
448 id.account.getJid().asBareJid()
449 + ": ignoring proposal because busy on this device but there are other devices");
450 }
451 } else {
452 final JingleRtpConnection rtpConnection =
453 new JingleRtpConnection(this, id, from);
454 this.connections.put(id, rtpConnection);
455 rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
456 rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
457 addNewIncomingCall(rtpConnection);
458 }
459 } else {
460 Log.d(
461 Config.LOGTAG,
462 account.getJid().asBareJid()
463 + ": unable to react to proposed session with "
464 + rtpDescriptions.size()
465 + " rtp descriptions of "
466 + descriptions.size()
467 + " total descriptions");
468 }
469 } else if (addressedDirectly && "proceed".equals(message.getName())) {
470 synchronized (rtpSessionProposals) {
471 final RtpSessionProposal proposal =
472 getRtpSessionProposal(account, from.asBareJid(), sessionId);
473 if (proposal != null) {
474 rtpSessionProposals.remove(proposal);
475 final JingleRtpConnection rtpConnection =
476 new JingleRtpConnection(
477 this, id, account.getJid(), proposal.callIntegration);
478 rtpConnection.setProposedMedia(proposal.media);
479 this.connections.put(id, rtpConnection);
480 rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
481 rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
482 } else {
483 Log.d(
484 Config.LOGTAG,
485 account.getJid().asBareJid()
486 + ": no rtp session ("
487 + sessionId
488 + ") proposal found for "
489 + from
490 + " to deliver proceed");
491 if (remoteMsgId == null) {
492 return;
493 }
494 final MessagePacket errorMessage = new MessagePacket();
495 errorMessage.setTo(from);
496 errorMessage.setId(remoteMsgId);
497 errorMessage.setType(MessagePacket.TYPE_ERROR);
498 final Element error = errorMessage.addChild("error");
499 error.setAttribute("code", "404");
500 error.setAttribute("type", "cancel");
501 error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
502 mXmppConnectionService.sendMessagePacket(account, errorMessage);
503 }
504 }
505 } else if (addressedDirectly && "reject".equals(message.getName())) {
506 final RtpSessionProposal proposal =
507 getRtpSessionProposal(account, from.asBareJid(), sessionId);
508 synchronized (rtpSessionProposals) {
509 if (proposal != null) {
510 setTerminalSessionState(proposal, RtpEndUserState.DECLINED_OR_BUSY);
511 rtpSessionProposals.remove(proposal);
512 proposal.callIntegration.busy();
513 writeLogMissedOutgoing(
514 account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
515 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
516 account,
517 proposal.with,
518 proposal.sessionId,
519 RtpEndUserState.DECLINED_OR_BUSY);
520 } else {
521 Log.d(
522 Config.LOGTAG,
523 account.getJid().asBareJid()
524 + ": no rtp session proposal found for "
525 + from
526 + " to deliver reject");
527 }
528 }
529 } else if (addressedDirectly && "ringing".equals(message.getName())) {
530 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + from + " started ringing");
531 updateProposedSessionDiscovered(
532 account, from, sessionId, DeviceDiscoveryState.DISCOVERED);
533 } else {
534 Log.d(
535 Config.LOGTAG,
536 account.getJid()
537 + ": received out of order jingle message from="
538 + from
539 + ", message="
540 + message
541 + ", addressedDirectly="
542 + addressedDirectly);
543 }
544 }
545
546 private RtpSessionProposal getRtpSessionProposal(
547 final Account account, Jid from, String sessionId) {
548 for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
549 if (rtpSessionProposal.sessionId.equals(sessionId)
550 && rtpSessionProposal.with.equals(from)
551 && rtpSessionProposal.account.getJid().equals(account.getJid())) {
552 return rtpSessionProposal;
553 }
554 }
555 return null;
556 }
557
558 private void writeLogMissedOutgoing(
559 final Account account,
560 Jid with,
561 final String sessionId,
562 String serverMsgId,
563 long timestamp) {
564 final Conversation conversation =
565 mXmppConnectionService.findOrCreateConversation(
566 account, with.asBareJid(), false, false);
567 final Message message =
568 new Message(conversation, Message.STATUS_SEND, Message.TYPE_RTP_SESSION, sessionId);
569 message.setBody(new RtpSessionStatus(false, 0).toString());
570 message.setServerMsgId(serverMsgId);
571 message.setTime(timestamp);
572 writeMessage(message);
573 }
574
575 private void writeLogMissedIncoming(
576 final Account account,
577 final Jid with,
578 final String sessionId,
579 final String serverMsgId,
580 final long timestamp,
581 final boolean stranger) {
582 final Conversation conversation =
583 mXmppConnectionService.findOrCreateConversation(
584 account, with.asBareJid(), false, false);
585 final Message message =
586 new Message(
587 conversation, Message.STATUS_RECEIVED, Message.TYPE_RTP_SESSION, sessionId);
588 message.setBody(new RtpSessionStatus(false, 0).toString());
589 message.setServerMsgId(serverMsgId);
590 message.setTime(timestamp);
591 message.setCounterpart(with);
592 writeMessage(message);
593 if (stranger) {
594 return;
595 }
596 mXmppConnectionService.getNotificationService().pushMissedCallNow(message);
597 }
598
599 private void writeMessage(final Message message) {
600 final Conversational conversational = message.getConversation();
601 if (conversational instanceof Conversation) {
602 ((Conversation) conversational).add(message);
603 mXmppConnectionService.databaseBackend.createMessage(message);
604 mXmppConnectionService.updateConversationUi();
605 } else {
606 throw new IllegalStateException("Somehow the conversation in a message was a stub");
607 }
608 }
609
610 public void startJingleFileTransfer(final Message message) {
611 Preconditions.checkArgument(
612 message.isFileOrImage(), "Message is not of type file or image");
613 final Transferable old = message.getTransferable();
614 if (old != null) {
615 old.cancel();
616 }
617 final JingleFileTransferConnection connection =
618 new JingleFileTransferConnection(this, message);
619 this.connections.put(connection.getId(), connection);
620 connection.sendSessionInitialize();
621 }
622
623 public Optional<OngoingRtpSession> getOngoingRtpConnection(final Contact contact) {
624 for (final Map.Entry<AbstractJingleConnection.Id, AbstractJingleConnection> entry :
625 this.connections.entrySet()) {
626 if (entry.getValue() instanceof JingleRtpConnection jingleRtpConnection) {
627 final AbstractJingleConnection.Id id = entry.getKey();
628 if (id.account == contact.getAccount()
629 && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
630 return Optional.of(jingleRtpConnection);
631 }
632 }
633 }
634 synchronized (this.rtpSessionProposals) {
635 for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
636 this.rtpSessionProposals.entrySet()) {
637 final RtpSessionProposal proposal = entry.getKey();
638 if (proposal.account == contact.getAccount()
639 && contact.getJid().asBareJid().equals(proposal.with)) {
640 final DeviceDiscoveryState preexistingState = entry.getValue();
641 if (preexistingState != null
642 && preexistingState != DeviceDiscoveryState.FAILED) {
643 return Optional.of(proposal);
644 }
645 }
646 }
647 }
648 return Optional.absent();
649 }
650
651 void finishConnectionOrThrow(final AbstractJingleConnection connection) {
652 final AbstractJingleConnection.Id id = connection.getId();
653 if (this.connections.remove(id) == null) {
654 throw new IllegalStateException(
655 String.format("Unable to finish connection with id=%s", id));
656 }
657 // update chat UI to remove 'ongoing call' icon
658 mXmppConnectionService.updateConversationUi();
659 }
660
661 public boolean fireJingleRtpConnectionStateUpdates() {
662 for (final AbstractJingleConnection connection : this.connections.values()) {
663 if (connection instanceof JingleRtpConnection jingleRtpConnection) {
664 if (jingleRtpConnection.isTerminated()) {
665 continue;
666 }
667 jingleRtpConnection.fireStateUpdate();
668 return true;
669 }
670 }
671 return false;
672 }
673
674 public void retractSessionProposal(final Account account, final Jid with) {
675 synchronized (this.rtpSessionProposals) {
676 RtpSessionProposal matchingProposal = null;
677 for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
678 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
679 matchingProposal = proposal;
680 break;
681 }
682 }
683 if (matchingProposal != null) {
684 retractSessionProposal(matchingProposal, false);
685 }
686 }
687 }
688
689 private void retractSessionProposal(final RtpSessionProposal rtpSessionProposal) {
690 retractSessionProposal(rtpSessionProposal, true);
691 }
692
693 private void retractSessionProposal(
694 final RtpSessionProposal rtpSessionProposal, final boolean refresh) {
695 final Account account = rtpSessionProposal.account;
696 Log.d(
697 Config.LOGTAG,
698 account.getJid().asBareJid()
699 + ": retracting rtp session proposal with "
700 + rtpSessionProposal.with);
701 this.rtpSessionProposals.remove(rtpSessionProposal);
702 rtpSessionProposal.callIntegration.retracted();
703 if (refresh) {
704 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
705 account,
706 rtpSessionProposal.with,
707 rtpSessionProposal.sessionId,
708 RtpEndUserState.RETRACTED);
709 }
710 final MessagePacket messagePacket =
711 mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
712 writeLogMissedOutgoing(
713 account,
714 rtpSessionProposal.with,
715 rtpSessionProposal.sessionId,
716 null,
717 System.currentTimeMillis());
718 mXmppConnectionService.sendMessagePacket(account, messagePacket);
719 }
720
721 public JingleRtpConnection initializeRtpSession(
722 final Account account, final Jid with, final Set<Media> media) {
723 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
724 final JingleRtpConnection rtpConnection =
725 new JingleRtpConnection(this, id, account.getJid());
726 rtpConnection.setProposedMedia(media);
727 this.connections.put(id, rtpConnection);
728 rtpConnection.sendSessionInitiate();
729 return rtpConnection;
730 }
731
732 public @Nullable RtpSessionProposal proposeJingleRtpSession(
733 final Account account, final Jid with, final Set<Media> media) {
734 synchronized (this.rtpSessionProposals) {
735 for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
736 this.rtpSessionProposals.entrySet()) {
737 final RtpSessionProposal proposal = entry.getKey();
738 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
739 final DeviceDiscoveryState preexistingState = entry.getValue();
740 if (preexistingState != null
741 && preexistingState != DeviceDiscoveryState.FAILED) {
742 final RtpEndUserState endUserState = preexistingState.toEndUserState();
743 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
744 account, with, proposal.sessionId, endUserState);
745 return proposal;
746 }
747 }
748 }
749 if (isBusy()) {
750 if (hasMatchingRtpSession(account, with, media)) {
751 Log.d(
752 Config.LOGTAG,
753 "ignoring request to propose jingle session because the other party already created one for us");
754 // TODO return something that we can parse the connection of of
755 return null;
756 }
757 throw new IllegalStateException(
758 "There is already a running RTP session. This should have been caught by the UI");
759 }
760 final CallIntegration callIntegration =
761 new CallIntegration(mXmppConnectionService.getApplicationContext());
762 callIntegration.setVideoState(
763 Media.audioOnly(media)
764 ? VideoProfile.STATE_AUDIO_ONLY
765 : VideoProfile.STATE_BIDIRECTIONAL);
766 callIntegration.setInitialAudioDevice(CallIntegration.initialAudioDevice(media));
767 final RtpSessionProposal proposal =
768 RtpSessionProposal.of(account, with.asBareJid(), media, callIntegration);
769 callIntegration.setCallback(new ProposalStateCallback(proposal));
770 this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
771 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
772 account, proposal.with, proposal.sessionId, RtpEndUserState.FINDING_DEVICE);
773 final MessagePacket messagePacket =
774 mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
775 mXmppConnectionService.sendMessagePacket(account, messagePacket);
776 return proposal;
777 }
778 }
779
780 public void sendJingleMessageFinish(
781 final Contact contact, final String sessionId, final Reason reason) {
782 final var account = contact.getAccount();
783 final MessagePacket messagePacket =
784 mXmppConnectionService
785 .getMessageGenerator()
786 .sessionFinish(contact.getJid(), sessionId, reason);
787 mXmppConnectionService.sendMessagePacket(account, messagePacket);
788 }
789
790 public Optional<RtpSessionProposal> matchingProposal(final Account account, final Jid with) {
791 synchronized (this.rtpSessionProposals) {
792 for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
793 this.rtpSessionProposals.entrySet()) {
794 final RtpSessionProposal proposal = entry.getKey();
795 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
796 return Optional.of(proposal);
797 }
798 }
799 }
800 return Optional.absent();
801 }
802
803 public boolean hasMatchingProposal(final Account account, final Jid with) {
804 synchronized (this.rtpSessionProposals) {
805 for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
806 this.rtpSessionProposals.entrySet()) {
807 final var state = entry.getValue();
808 final RtpSessionProposal proposal = entry.getKey();
809 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
810 // CallIntegrationConnectionService starts RtpSessionActivity with ACTION_VIEW
811 // and an EXTRA_LAST_REPORTED_STATE of DISCOVERING devices. however due to
812 // possible race conditions the state might have already moved on so we are
813 // going
814 // to update the UI
815 final RtpEndUserState endUserState = state.toEndUserState();
816 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
817 account, proposal.with, proposal.sessionId, endUserState);
818 return true;
819 }
820 }
821 }
822 return false;
823 }
824
825 public void deliverIbbPacket(final Account account, final IqPacket packet) {
826 final String sid;
827 final Element payload;
828 final InbandBytestreamsTransport.PacketType packetType;
829 if (packet.hasChild("open", Namespace.IBB)) {
830 packetType = InbandBytestreamsTransport.PacketType.OPEN;
831 payload = packet.findChild("open", Namespace.IBB);
832 sid = payload.getAttribute("sid");
833 } else if (packet.hasChild("data", Namespace.IBB)) {
834 packetType = InbandBytestreamsTransport.PacketType.DATA;
835 payload = packet.findChild("data", Namespace.IBB);
836 sid = payload.getAttribute("sid");
837 } else if (packet.hasChild("close", Namespace.IBB)) {
838 packetType = InbandBytestreamsTransport.PacketType.CLOSE;
839 payload = packet.findChild("close", Namespace.IBB);
840 sid = payload.getAttribute("sid");
841 } else {
842 packetType = null;
843 payload = null;
844 sid = null;
845 }
846 if (sid == null) {
847 Log.d(
848 Config.LOGTAG,
849 account.getJid().asBareJid() + ": unable to deliver ibb packet. missing sid");
850 account.getXmppConnection()
851 .sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
852 return;
853 }
854 for (final AbstractJingleConnection connection : this.connections.values()) {
855 if (connection instanceof JingleFileTransferConnection fileTransfer) {
856 final Transport transport = fileTransfer.getTransport();
857 if (transport instanceof InbandBytestreamsTransport inBandTransport) {
858 if (sid.equals(inBandTransport.getStreamId())) {
859 if (inBandTransport.deliverPacket(packetType, packet.getFrom(), payload)) {
860 account.getXmppConnection()
861 .sendIqPacket(
862 packet.generateResponse(IqPacket.TYPE.RESULT), null);
863 } else {
864 account.getXmppConnection()
865 .sendIqPacket(
866 packet.generateResponse(IqPacket.TYPE.ERROR), null);
867 }
868 return;
869 }
870 }
871 }
872 }
873 Log.d(
874 Config.LOGTAG,
875 account.getJid().asBareJid() + ": unable to deliver ibb packet with sid=" + sid);
876 account.getXmppConnection()
877 .sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
878 }
879
880 public void notifyRebound(final Account account) {
881 for (final AbstractJingleConnection connection : this.connections.values()) {
882 connection.notifyRebound();
883 }
884 final XmppConnection xmppConnection = account.getXmppConnection();
885 if (xmppConnection != null && xmppConnection.getFeatures().sm()) {
886 resendSessionProposals(account);
887 }
888 }
889
890 public WeakReference<JingleRtpConnection> findJingleRtpConnection(
891 Account account, Jid with, String sessionId) {
892 final AbstractJingleConnection.Id id =
893 AbstractJingleConnection.Id.of(account, with, sessionId);
894 final AbstractJingleConnection connection = connections.get(id);
895 if (connection instanceof JingleRtpConnection) {
896 return new WeakReference<>((JingleRtpConnection) connection);
897 }
898 return null;
899 }
900
901 public JingleRtpConnection findJingleRtpConnection(final Account account, final Jid with) {
902 for (final AbstractJingleConnection connection : this.connections.values()) {
903 if (connection instanceof JingleRtpConnection rtpConnection) {
904 if (rtpConnection.isTerminated()) {
905 continue;
906 }
907 final var id = rtpConnection.getId();
908 if (id.account == account && account.getJid().equals(with)) {
909 return rtpConnection;
910 }
911 }
912 }
913 return null;
914 }
915
916 private void resendSessionProposals(final Account account) {
917 synchronized (this.rtpSessionProposals) {
918 for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
919 this.rtpSessionProposals.entrySet()) {
920 final RtpSessionProposal proposal = entry.getKey();
921 if (entry.getValue() == DeviceDiscoveryState.SEARCHING
922 && proposal.account == account) {
923 Log.d(
924 Config.LOGTAG,
925 account.getJid().asBareJid()
926 + ": resending session proposal to "
927 + proposal.with);
928 final MessagePacket messagePacket =
929 mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
930 mXmppConnectionService.sendMessagePacket(account, messagePacket);
931 }
932 }
933 }
934 }
935
936 public void updateProposedSessionDiscovered(
937 Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
938 synchronized (this.rtpSessionProposals) {
939 final RtpSessionProposal sessionProposal =
940 getRtpSessionProposal(account, from.asBareJid(), sessionId);
941 final DeviceDiscoveryState currentState =
942 sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
943 if (currentState == null) {
944 Log.d(
945 Config.LOGTAG,
946 "unable to find session proposal for session id "
947 + sessionId
948 + " target="
949 + target);
950 return;
951 }
952 if (currentState == DeviceDiscoveryState.DISCOVERED) {
953 Log.d(
954 Config.LOGTAG,
955 "session proposal already at discovered. not going to fall back");
956 return;
957 }
958
959 Log.d(
960 Config.LOGTAG,
961 account.getJid().asBareJid()
962 + ": flagging session "
963 + sessionId
964 + " as "
965 + target);
966
967 final RtpEndUserState endUserState = target.toEndUserState();
968
969 if (target == DeviceDiscoveryState.FAILED) {
970 Log.d(Config.LOGTAG, "removing session proposal after failure");
971 setTerminalSessionState(sessionProposal, endUserState);
972 this.rtpSessionProposals.remove(sessionProposal);
973 sessionProposal.getCallIntegration().error();
974 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
975 account,
976 sessionProposal.with,
977 sessionProposal.sessionId,
978 endUserState);
979 return;
980 }
981
982 this.rtpSessionProposals.put(sessionProposal, target);
983
984 if (endUserState == RtpEndUserState.RINGING) {
985 sessionProposal.callIntegration.setDialing();
986 }
987
988 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
989 account, sessionProposal.with, sessionProposal.sessionId, endUserState);
990 }
991 }
992
993 public void rejectRtpSession(final String sessionId) {
994 for (final AbstractJingleConnection connection : this.connections.values()) {
995 if (connection.getId().sessionId.equals(sessionId)) {
996 if (connection instanceof JingleRtpConnection) {
997 try {
998 ((JingleRtpConnection) connection).rejectCall();
999 return;
1000 } catch (final IllegalStateException e) {
1001 Log.w(
1002 Config.LOGTAG,
1003 "race condition on rejecting call from notification",
1004 e);
1005 }
1006 }
1007 }
1008 }
1009 }
1010
1011 public void endRtpSession(final String sessionId) {
1012 for (final AbstractJingleConnection connection : this.connections.values()) {
1013 if (connection.getId().sessionId.equals(sessionId)) {
1014 if (connection instanceof JingleRtpConnection) {
1015 ((JingleRtpConnection) connection).endCall();
1016 }
1017 }
1018 }
1019 }
1020
1021 public void failProceed(
1022 Account account, final Jid with, final String sessionId, final String message) {
1023 final AbstractJingleConnection.Id id =
1024 AbstractJingleConnection.Id.of(account, with, sessionId);
1025 final AbstractJingleConnection existingJingleConnection = connections.get(id);
1026 if (existingJingleConnection instanceof JingleRtpConnection) {
1027 ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed(message);
1028 }
1029 }
1030
1031 void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
1032 if (connections.containsValue(connection)) {
1033 return;
1034 }
1035 final IllegalStateException e =
1036 new IllegalStateException(
1037 "JingleConnection has not been registered with connection manager");
1038 Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
1039 throw e;
1040 }
1041
1042 void setTerminalSessionState(
1043 AbstractJingleConnection.Id id, final RtpEndUserState state, final Set<Media> media) {
1044 this.terminatedSessions.put(
1045 PersistableSessionId.of(id), new TerminatedRtpSession(state, media));
1046 }
1047
1048 void setTerminalSessionState(final RtpSessionProposal proposal, final RtpEndUserState state) {
1049 this.terminatedSessions.put(
1050 PersistableSessionId.of(proposal), new TerminatedRtpSession(state, proposal.media));
1051 }
1052
1053 public TerminatedRtpSession getTerminalSessionState(final Jid with, final String sessionId) {
1054 return this.terminatedSessions.getIfPresent(new PersistableSessionId(with, sessionId));
1055 }
1056
1057 private static class PersistableSessionId {
1058 private final Jid with;
1059 private final String sessionId;
1060
1061 private PersistableSessionId(Jid with, String sessionId) {
1062 this.with = with;
1063 this.sessionId = sessionId;
1064 }
1065
1066 public static PersistableSessionId of(final AbstractJingleConnection.Id id) {
1067 return new PersistableSessionId(id.with, id.sessionId);
1068 }
1069
1070 public static PersistableSessionId of(final RtpSessionProposal proposal) {
1071 return new PersistableSessionId(proposal.with, proposal.sessionId);
1072 }
1073
1074 @Override
1075 public boolean equals(Object o) {
1076 if (this == o) return true;
1077 if (o == null || getClass() != o.getClass()) return false;
1078 PersistableSessionId that = (PersistableSessionId) o;
1079 return Objects.equal(with, that.with) && Objects.equal(sessionId, that.sessionId);
1080 }
1081
1082 @Override
1083 public int hashCode() {
1084 return Objects.hashCode(with, sessionId);
1085 }
1086 }
1087
1088 public static class TerminatedRtpSession {
1089 public final RtpEndUserState state;
1090 public final Set<Media> media;
1091
1092 TerminatedRtpSession(RtpEndUserState state, Set<Media> media) {
1093 this.state = state;
1094 this.media = media;
1095 }
1096 }
1097
1098 public enum DeviceDiscoveryState {
1099 SEARCHING,
1100 SEARCHING_ACKNOWLEDGED,
1101 DISCOVERED,
1102 FAILED;
1103
1104 public RtpEndUserState toEndUserState() {
1105 return switch (this) {
1106 case SEARCHING, SEARCHING_ACKNOWLEDGED -> RtpEndUserState.FINDING_DEVICE;
1107 case DISCOVERED -> RtpEndUserState.RINGING;
1108 default -> RtpEndUserState.CONNECTIVITY_ERROR;
1109 };
1110 }
1111 }
1112
1113 public static class RtpSessionProposal implements OngoingRtpSession {
1114 public final Jid with;
1115 public final String sessionId;
1116 public final Set<Media> media;
1117 private final Account account;
1118 private final CallIntegration callIntegration;
1119
1120 private RtpSessionProposal(
1121 Account account,
1122 Jid with,
1123 String sessionId,
1124 Set<Media> media,
1125 final CallIntegration callIntegration) {
1126 this.account = account;
1127 this.with = with;
1128 this.sessionId = sessionId;
1129 this.media = media;
1130 this.callIntegration = callIntegration;
1131 }
1132
1133 public static RtpSessionProposal of(
1134 Account account,
1135 Jid with,
1136 Set<Media> media,
1137 final CallIntegration callIntegration) {
1138 return new RtpSessionProposal(account, with, nextRandomId(), media, callIntegration);
1139 }
1140
1141 @Override
1142 public boolean equals(Object o) {
1143 if (this == o) return true;
1144 if (o == null || getClass() != o.getClass()) return false;
1145 RtpSessionProposal proposal = (RtpSessionProposal) o;
1146 return Objects.equal(account.getJid(), proposal.account.getJid())
1147 && Objects.equal(with, proposal.with)
1148 && Objects.equal(sessionId, proposal.sessionId);
1149 }
1150
1151 @Override
1152 public int hashCode() {
1153 return Objects.hashCode(account.getJid(), with, sessionId);
1154 }
1155
1156 @Override
1157 public Account getAccount() {
1158 return account;
1159 }
1160
1161 @Override
1162 public Jid getWith() {
1163 return with;
1164 }
1165
1166 @Override
1167 public String getSessionId() {
1168 return sessionId;
1169 }
1170
1171 @Override
1172 public CallIntegration getCallIntegration() {
1173 return this.callIntegration;
1174 }
1175
1176 @Override
1177 public Set<Media> getMedia() {
1178 return this.media;
1179 }
1180 }
1181
1182 public class ProposalStateCallback implements CallIntegration.Callback {
1183
1184 private final RtpSessionProposal proposal;
1185
1186 public ProposalStateCallback(final RtpSessionProposal proposal) {
1187 this.proposal = proposal;
1188 }
1189
1190 @Override
1191 public void onCallIntegrationShowIncomingCallUi() {}
1192
1193 @Override
1194 public void onCallIntegrationDisconnect() {
1195 Log.d(Config.LOGTAG, "a phone call has just been started. retracting proposal");
1196 retractSessionProposal(this.proposal);
1197 }
1198
1199 @Override
1200 public void onAudioDeviceChanged(
1201 final CallIntegration.AudioDevice selectedAudioDevice,
1202 final Set<CallIntegration.AudioDevice> availableAudioDevices) {
1203 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
1204 selectedAudioDevice, availableAudioDevices);
1205 }
1206
1207 @Override
1208 public void onCallIntegrationReject() {}
1209
1210 @Override
1211 public void onCallIntegrationAnswer() {}
1212
1213 @Override
1214 public void onCallIntegrationSilence() {}
1215 }
1216}