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.Preconditions;
8
9import java.lang.ref.WeakReference;
10import java.security.SecureRandom;
11import java.util.HashMap;
12import java.util.Map;
13import java.util.concurrent.ConcurrentHashMap;
14
15import eu.siacs.conversations.Config;
16import eu.siacs.conversations.entities.Account;
17import eu.siacs.conversations.entities.Message;
18import eu.siacs.conversations.entities.Transferable;
19import eu.siacs.conversations.services.AbstractConnectionManager;
20import eu.siacs.conversations.services.XmppConnectionService;
21import eu.siacs.conversations.xml.Element;
22import eu.siacs.conversations.xml.Namespace;
23import eu.siacs.conversations.xmpp.OnIqPacketReceived;
24import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
25import eu.siacs.conversations.xmpp.jingle.stanzas.FileTransferDescription;
26import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
27import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
28import eu.siacs.conversations.xmpp.stanzas.IqPacket;
29import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
30import rocks.xmpp.addr.Jid;
31
32public class JingleConnectionManager extends AbstractConnectionManager {
33 private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals = new HashMap<>();
34 private final Map<AbstractJingleConnection.Id, AbstractJingleConnection> connections = new ConcurrentHashMap<>();
35
36 private HashMap<Jid, JingleCandidate> primaryCandidates = new HashMap<>();
37
38 public JingleConnectionManager(XmppConnectionService service) {
39 super(service);
40 }
41
42 static String nextRandomId() {
43 final byte[] id = new byte[16];
44 new SecureRandom().nextBytes(id);
45 return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING);
46 }
47
48 public void deliverPacket(final Account account, final JinglePacket packet) {
49 final String sessionId = packet.getSessionId();
50 if (sessionId == null) {
51 respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
52 return;
53 }
54 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, packet);
55 final AbstractJingleConnection existingJingleConnection = connections.get(id);
56 if (existingJingleConnection != null) {
57 existingJingleConnection.deliverPacket(packet);
58 } else if (packet.getAction() == JinglePacket.Action.SESSION_INITIATE) {
59 final Jid from = packet.getFrom();
60 final Content content = packet.getJingleContent();
61 final String descriptionNamespace = content == null ? null : content.getDescriptionNamespace();
62 final AbstractJingleConnection connection;
63 if (FileTransferDescription.NAMESPACES.contains(descriptionNamespace)) {
64 connection = new JingleFileTransferConnection(this, id, from);
65 } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace) && !usesTor(account)) {
66 if (isBusy()) {
67 mXmppConnectionService.sendIqPacket(account, packet.generateResponse(IqPacket.TYPE.RESULT), null);
68 final JinglePacket sessionTermination = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
69 sessionTermination.setTo(id.with);
70 sessionTermination.setReason(Reason.BUSY, null);
71 mXmppConnectionService.sendIqPacket(account, sessionTermination, null);
72 return;
73 }
74 connection = new JingleRtpConnection(this, id, from);
75 } else {
76 respondWithJingleError(account, packet, "unsupported-info", "feature-not-implemented", "cancel");
77 return;
78 }
79 connections.put(id, connection);
80 connection.deliverPacket(packet);
81 } else {
82 Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
83 respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
84 }
85 }
86
87 private boolean usesTor(final Account account) {
88 return account.isOnion() || mXmppConnectionService.useTorToConnect();
89 }
90
91 private boolean isBusy() {
92 for (AbstractJingleConnection connection : this.connections.values()) {
93 if (connection instanceof JingleRtpConnection) {
94 return true;
95 }
96 }
97 synchronized (this.rtpSessionProposals) {
98 return this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED) || this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING);
99 }
100 }
101
102 public void respondWithJingleError(final Account account, final IqPacket original, String jingleCondition, String condition, String conditionType) {
103 final IqPacket response = original.generateResponse(IqPacket.TYPE.ERROR);
104 final Element error = response.addChild("error");
105 error.setAttribute("type", conditionType);
106 error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
107 error.addChild(jingleCondition, "urn:xmpp:jingle:errors:1");
108 account.getXmppConnection().sendIqPacket(response, null);
109 }
110
111 public void deliverMessage(final Account account, final Jid to, final Jid from, final Element message) {
112 Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
113 final String sessionId = message.getAttribute("id");
114 if (sessionId == null) {
115 return;
116 }
117 if ("accept".equals(message.getName())) {
118 for (AbstractJingleConnection connection : connections.values()) {
119 if (connection instanceof JingleRtpConnection) {
120 final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
121 final AbstractJingleConnection.Id id = connection.getId();
122 if (id.account == account && id.sessionId.equals(sessionId)) {
123 rtpConnection.deliveryMessage(from, message);
124 return;
125 }
126 }
127 }
128 return;
129 }
130 final boolean addressedToSelf = from.asBareJid().equals(account.getJid().asBareJid());
131 final AbstractJingleConnection.Id id;
132 if (addressedToSelf) {
133 if (to.isFullJid()) {
134 id = AbstractJingleConnection.Id.of(account, to, sessionId);
135 } else {
136 return;
137 }
138 } else {
139 id = AbstractJingleConnection.Id.of(account, from, sessionId);
140 }
141 final AbstractJingleConnection existingJingleConnection = connections.get(id);
142 if (existingJingleConnection != null) {
143 if (existingJingleConnection instanceof JingleRtpConnection) {
144 ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message);
145 } else {
146 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
147 }
148 return;
149 }
150
151 if (addressedToSelf) {
152 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore jingle message from self");
153 }
154
155 if ("propose".equals(message.getName())) {
156 final Element description = message.findChild("description");
157 final String namespace = description == null ? null : description.getNamespace();
158 if (Namespace.JINGLE_APPS_RTP.equals(namespace) && !usesTor(account)) {
159 if (isBusy()) {
160 final MessagePacket reject = mXmppConnectionService.getMessageGenerator().sessionReject(from, sessionId);
161 mXmppConnectionService.sendMessagePacket(account, reject);
162 } else {
163 final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
164 this.connections.put(id, rtpConnection);
165 rtpConnection.deliveryMessage(from, message);
166 }
167 } else {
168 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed " + namespace + " session");
169 }
170 } else if ("proceed".equals(message.getName())) {
171
172 final RtpSessionProposal proposal = new RtpSessionProposal(account, from.asBareJid(), sessionId);
173 synchronized (rtpSessionProposals) {
174 if (rtpSessionProposals.remove(proposal) != null) {
175 final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
176 this.connections.put(id, rtpConnection);
177 rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
178 rtpConnection.deliveryMessage(from, message);
179 } else {
180 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver proceed");
181 }
182 }
183 } else if ("reject".equals(message.getName())) {
184 final RtpSessionProposal proposal = new RtpSessionProposal(account, from.asBareJid(), sessionId);
185 synchronized (rtpSessionProposals) {
186 if (rtpSessionProposals.remove(proposal) != null) {
187 mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, proposal.with, proposal.sessionId, RtpEndUserState.DECLINED_OR_BUSY);
188 } else {
189 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver reject");
190 }
191 }
192 } else {
193 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message");
194 }
195
196 }
197
198 public void startJingleFileTransfer(final Message message) {
199 Preconditions.checkArgument(message.isFileOrImage(), "Message is not of type file or image");
200 final Transferable old = message.getTransferable();
201 if (old != null) {
202 old.cancel();
203 }
204 final Account account = message.getConversation().getAccount();
205 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
206 final JingleFileTransferConnection connection = new JingleFileTransferConnection(this, id, account.getJid());
207 mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
208 this.connections.put(id, connection);
209 connection.init(message);
210 }
211
212 void finishConnection(final AbstractJingleConnection connection) {
213 this.connections.remove(connection.getId());
214 }
215
216 void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
217 if (Config.DISABLE_PROXY_LOOKUP) {
218 listener.onPrimaryCandidateFound(false, null);
219 return;
220 }
221 if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
222 final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
223 if (proxy != null) {
224 IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
225 iq.setTo(proxy);
226 iq.query(Namespace.BYTE_STREAMS);
227 account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
228
229 @Override
230 public void onIqPacketReceived(Account account, IqPacket packet) {
231 final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
232 final String host = streamhost == null ? null : streamhost.getAttribute("host");
233 final String port = streamhost == null ? null : streamhost.getAttribute("port");
234 if (host != null && port != null) {
235 try {
236 JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
237 candidate.setHost(host);
238 candidate.setPort(Integer.parseInt(port));
239 candidate.setType(JingleCandidate.TYPE_PROXY);
240 candidate.setJid(proxy);
241 candidate.setPriority(655360 + (initiator ? 30 : 0));
242 primaryCandidates.put(account.getJid().asBareJid(), candidate);
243 listener.onPrimaryCandidateFound(true, candidate);
244 } catch (final NumberFormatException e) {
245 listener.onPrimaryCandidateFound(false, null);
246 }
247 } else {
248 listener.onPrimaryCandidateFound(false, null);
249 }
250 }
251 });
252 } else {
253 listener.onPrimaryCandidateFound(false, null);
254 }
255
256 } else {
257 listener.onPrimaryCandidateFound(true,
258 this.primaryCandidates.get(account.getJid().asBareJid()));
259 }
260 }
261
262 public void retractSessionProposal(final Account account, final Jid with) {
263 synchronized (this.rtpSessionProposals) {
264 RtpSessionProposal matchingProposal = null;
265 for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
266 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
267 matchingProposal = proposal;
268 break;
269 }
270 }
271 if (matchingProposal != null) {
272 this.rtpSessionProposals.remove(matchingProposal);
273 final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionRetract(matchingProposal);
274 Log.d(Config.LOGTAG, messagePacket.toString());
275 mXmppConnectionService.sendMessagePacket(account, messagePacket);
276
277 }
278 }
279 }
280
281 public void proposeJingleRtpSession(final Account account, final Jid with) {
282 synchronized (this.rtpSessionProposals) {
283 for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
284 RtpSessionProposal proposal = entry.getKey();
285 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
286 final DeviceDiscoveryState preexistingState = entry.getValue();
287 if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
288 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
289 account,
290 with,
291 proposal.sessionId,
292 preexistingState.toEndUserState()
293 );
294 return;
295 }
296 }
297 }
298 final RtpSessionProposal proposal = RtpSessionProposal.of(account, with.asBareJid());
299 this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
300 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
301 account,
302 proposal.with,
303 proposal.sessionId,
304 RtpEndUserState.FINDING_DEVICE
305 );
306 final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
307 Log.d(Config.LOGTAG, messagePacket.toString());
308 mXmppConnectionService.sendMessagePacket(account, messagePacket);
309 }
310 }
311
312 public void deliverIbbPacket(Account account, IqPacket packet) {
313 final String sid;
314 final Element payload;
315 if (packet.hasChild("open", Namespace.IBB)) {
316 payload = packet.findChild("open", Namespace.IBB);
317 sid = payload.getAttribute("sid");
318 } else if (packet.hasChild("data", Namespace.IBB)) {
319 payload = packet.findChild("data", Namespace.IBB);
320 sid = payload.getAttribute("sid");
321 } else if (packet.hasChild("close", Namespace.IBB)) {
322 payload = packet.findChild("close", Namespace.IBB);
323 sid = payload.getAttribute("sid");
324 } else {
325 payload = null;
326 sid = null;
327 }
328 if (sid != null) {
329 for (final AbstractJingleConnection connection : this.connections.values()) {
330 if (connection instanceof JingleFileTransferConnection) {
331 final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
332 final JingleTransport transport = fileTransfer.getTransport();
333 if (transport instanceof JingleInBandTransport) {
334 final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
335 if (inBandTransport.matches(account, sid)) {
336 inBandTransport.deliverPayload(packet, payload);
337 }
338 return;
339 }
340 }
341 }
342 }
343 Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
344 account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
345 }
346
347 public void cancelInTransmission() {
348 for (AbstractJingleConnection connection : this.connections.values()) {
349 /*if (connection.getJingleStatus() == JingleFileTransferConnection.JINGLE_STATUS_TRANSMITTING) {
350 connection.abort("connectivity-error");
351 }*/
352 }
353 }
354
355 public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
356 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, Jid.ofEscaped(with), sessionId);
357 final AbstractJingleConnection connection = connections.get(id);
358 if (connection instanceof JingleRtpConnection) {
359 return new WeakReference<>((JingleRtpConnection) connection);
360 }
361 return null;
362 }
363
364 public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
365 final RtpSessionProposal sessionProposal = new RtpSessionProposal(account, from.asBareJid(), sessionId);
366 synchronized (this.rtpSessionProposals) {
367 final DeviceDiscoveryState currentState = rtpSessionProposals.get(sessionProposal);
368 if (currentState == null) {
369 Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
370 return;
371 }
372 if (currentState == DeviceDiscoveryState.DISCOVERED) {
373 Log.d(Config.LOGTAG, "session proposal already at discovered. not going to fall back");
374 return;
375 }
376 this.rtpSessionProposals.put(sessionProposal, target);
377 mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, sessionProposal.with, sessionProposal.sessionId, target.toEndUserState());
378 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": flagging session " + sessionId + " as " + target);
379 }
380 }
381
382 public void rejectRtpSession(final String sessionId) {
383 for (final AbstractJingleConnection connection : this.connections.values()) {
384 if (connection.getId().sessionId.equals(sessionId)) {
385 if (connection instanceof JingleRtpConnection) {
386 ((JingleRtpConnection) connection).rejectCall();
387 }
388 }
389 }
390 }
391
392 public void endRtpSession(final String sessionId) {
393 for (final AbstractJingleConnection connection : this.connections.values()) {
394 if (connection.getId().sessionId.equals(sessionId)) {
395 if (connection instanceof JingleRtpConnection) {
396 ((JingleRtpConnection) connection).endCall();
397 }
398 }
399 }
400 }
401
402 public void failProceed(Account account, final Jid with, String sessionId) {
403 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
404 final AbstractJingleConnection existingJingleConnection = connections.get(id);
405 if (existingJingleConnection instanceof JingleRtpConnection) {
406 ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed();
407 }
408 }
409
410 public enum DeviceDiscoveryState {
411 SEARCHING, DISCOVERED, FAILED;
412
413 public RtpEndUserState toEndUserState() {
414 switch (this) {
415 case SEARCHING:
416 return RtpEndUserState.FINDING_DEVICE;
417 case DISCOVERED:
418 return RtpEndUserState.RINGING;
419 default:
420 return RtpEndUserState.CONNECTIVITY_ERROR;
421 }
422 }
423 }
424
425 public static class RtpSessionProposal {
426 public final Jid with;
427 public final String sessionId;
428 private final Account account;
429
430 private RtpSessionProposal(Account account, Jid with, String sessionId) {
431 this.account = account;
432 this.with = with;
433 this.sessionId = sessionId;
434 }
435
436 public static RtpSessionProposal of(Account account, Jid with) {
437 return new RtpSessionProposal(account, with, nextRandomId());
438 }
439
440 @Override
441 public boolean equals(Object o) {
442 if (this == o) return true;
443 if (o == null || getClass() != o.getClass()) return false;
444 RtpSessionProposal proposal = (RtpSessionProposal) o;
445 return Objects.equal(account.getJid(), proposal.account.getJid()) &&
446 Objects.equal(with, proposal.with) &&
447 Objects.equal(sessionId, proposal.sessionId);
448 }
449
450 @Override
451 public int hashCode() {
452 return Objects.hashCode(account.getJid(), with, sessionId);
453 }
454 }
455}