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 carbonCopy = from.asBareJid().equals(account.getJid().asBareJid());
131 final Jid with;
132 if (account.getJid().asBareJid().equals(from.asBareJid())) {
133 with = to;
134 } else {
135 with = from;
136 }
137 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received jingle message from " + from + " with=" + with + " " + message);
138 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
139 final AbstractJingleConnection existingJingleConnection = connections.get(id);
140 if (existingJingleConnection != null) {
141 if (existingJingleConnection instanceof JingleRtpConnection) {
142 ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message);
143 } else {
144 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
145 }
146 return;
147 }
148 if (carbonCopy) {
149 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore jingle message from self");
150 return;
151 }
152
153 if ("propose".equals(message.getName())) {
154 final Element description = message.findChild("description");
155 final String namespace = description == null ? null : description.getNamespace();
156 if (Namespace.JINGLE_APPS_RTP.equals(namespace) && !usesTor(account)) {
157 if (isBusy()) {
158 final MessagePacket reject = mXmppConnectionService.getMessageGenerator().sessionReject(from, sessionId);
159 mXmppConnectionService.sendMessagePacket(account, reject);
160 } else {
161 final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, with);
162 this.connections.put(id, rtpConnection);
163 rtpConnection.deliveryMessage(from, message);
164 }
165 } else {
166 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed " + namespace + " session");
167 }
168 } else if ("proceed".equals(message.getName())) {
169
170 final RtpSessionProposal proposal = new RtpSessionProposal(account, with.asBareJid(), sessionId);
171 synchronized (rtpSessionProposals) {
172 if (rtpSessionProposals.remove(proposal) != null) {
173 final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
174 this.connections.put(id, rtpConnection);
175 rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
176 rtpConnection.deliveryMessage(from, message);
177 } else {
178 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + with + " to deliver proceed");
179 }
180 }
181 } else if ("reject".equals(message.getName())) {
182 final RtpSessionProposal proposal = new RtpSessionProposal(account, with.asBareJid(), sessionId);
183 synchronized (rtpSessionProposals) {
184 if (rtpSessionProposals.remove(proposal) != null) {
185 mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, proposal.with, proposal.sessionId, RtpEndUserState.DECLINED_OR_BUSY);
186 } else {
187 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + with + " to deliver reject");
188 }
189 }
190 } else {
191 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message");
192 }
193
194 }
195
196 public void startJingleFileTransfer(final Message message) {
197 Preconditions.checkArgument(message.isFileOrImage(), "Message is not of type file or image");
198 final Transferable old = message.getTransferable();
199 if (old != null) {
200 old.cancel();
201 }
202 final Account account = message.getConversation().getAccount();
203 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
204 final JingleFileTransferConnection connection = new JingleFileTransferConnection(this, id, account.getJid());
205 mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
206 this.connections.put(id, connection);
207 connection.init(message);
208 }
209
210 void finishConnection(final AbstractJingleConnection connection) {
211 this.connections.remove(connection.getId());
212 }
213
214 void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
215 if (Config.DISABLE_PROXY_LOOKUP) {
216 listener.onPrimaryCandidateFound(false, null);
217 return;
218 }
219 if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
220 final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
221 if (proxy != null) {
222 IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
223 iq.setTo(proxy);
224 iq.query(Namespace.BYTE_STREAMS);
225 account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
226
227 @Override
228 public void onIqPacketReceived(Account account, IqPacket packet) {
229 final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
230 final String host = streamhost == null ? null : streamhost.getAttribute("host");
231 final String port = streamhost == null ? null : streamhost.getAttribute("port");
232 if (host != null && port != null) {
233 try {
234 JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
235 candidate.setHost(host);
236 candidate.setPort(Integer.parseInt(port));
237 candidate.setType(JingleCandidate.TYPE_PROXY);
238 candidate.setJid(proxy);
239 candidate.setPriority(655360 + (initiator ? 30 : 0));
240 primaryCandidates.put(account.getJid().asBareJid(), candidate);
241 listener.onPrimaryCandidateFound(true, candidate);
242 } catch (final NumberFormatException e) {
243 listener.onPrimaryCandidateFound(false, null);
244 }
245 } else {
246 listener.onPrimaryCandidateFound(false, null);
247 }
248 }
249 });
250 } else {
251 listener.onPrimaryCandidateFound(false, null);
252 }
253
254 } else {
255 listener.onPrimaryCandidateFound(true,
256 this.primaryCandidates.get(account.getJid().asBareJid()));
257 }
258 }
259
260 public void retractSessionProposal(final Account account, final Jid with) {
261 synchronized (this.rtpSessionProposals) {
262 RtpSessionProposal matchingProposal = null;
263 for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
264 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
265 matchingProposal = proposal;
266 break;
267 }
268 }
269 if (matchingProposal != null) {
270 this.rtpSessionProposals.remove(matchingProposal);
271 final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionRetract(matchingProposal);
272 Log.d(Config.LOGTAG, messagePacket.toString());
273 mXmppConnectionService.sendMessagePacket(account, messagePacket);
274
275 }
276 }
277 }
278
279 public void proposeJingleRtpSession(final Account account, final Jid with) {
280 synchronized (this.rtpSessionProposals) {
281 for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
282 RtpSessionProposal proposal = entry.getKey();
283 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
284 final DeviceDiscoveryState preexistingState = entry.getValue();
285 if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
286 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
287 account,
288 with,
289 proposal.sessionId,
290 preexistingState.toEndUserState()
291 );
292 return;
293 }
294 }
295 }
296 final RtpSessionProposal proposal = RtpSessionProposal.of(account, with.asBareJid());
297 this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
298 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
299 account,
300 proposal.with,
301 proposal.sessionId,
302 RtpEndUserState.FINDING_DEVICE
303 );
304 final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
305 Log.d(Config.LOGTAG, messagePacket.toString());
306 mXmppConnectionService.sendMessagePacket(account, messagePacket);
307 }
308 }
309
310 public void deliverIbbPacket(Account account, IqPacket packet) {
311 final String sid;
312 final Element payload;
313 if (packet.hasChild("open", Namespace.IBB)) {
314 payload = packet.findChild("open", Namespace.IBB);
315 sid = payload.getAttribute("sid");
316 } else if (packet.hasChild("data", Namespace.IBB)) {
317 payload = packet.findChild("data", Namespace.IBB);
318 sid = payload.getAttribute("sid");
319 } else if (packet.hasChild("close", Namespace.IBB)) {
320 payload = packet.findChild("close", Namespace.IBB);
321 sid = payload.getAttribute("sid");
322 } else {
323 payload = null;
324 sid = null;
325 }
326 if (sid != null) {
327 for (final AbstractJingleConnection connection : this.connections.values()) {
328 if (connection instanceof JingleFileTransferConnection) {
329 final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
330 final JingleTransport transport = fileTransfer.getTransport();
331 if (transport instanceof JingleInBandTransport) {
332 final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
333 if (inBandTransport.matches(account, sid)) {
334 inBandTransport.deliverPayload(packet, payload);
335 }
336 return;
337 }
338 }
339 }
340 }
341 Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
342 account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
343 }
344
345 public void cancelInTransmission() {
346 for (AbstractJingleConnection connection : this.connections.values()) {
347 /*if (connection.getJingleStatus() == JingleFileTransferConnection.JINGLE_STATUS_TRANSMITTING) {
348 connection.abort("connectivity-error");
349 }*/
350 }
351 }
352
353 public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
354 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, Jid.ofEscaped(with), sessionId);
355 final AbstractJingleConnection connection = connections.get(id);
356 if (connection instanceof JingleRtpConnection) {
357 return new WeakReference<>((JingleRtpConnection) connection);
358 }
359 return null;
360 }
361
362 public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
363 final RtpSessionProposal sessionProposal = new RtpSessionProposal(account, from.asBareJid(), sessionId);
364 synchronized (this.rtpSessionProposals) {
365 final DeviceDiscoveryState currentState = rtpSessionProposals.get(sessionProposal);
366 if (currentState == null) {
367 Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
368 return;
369 }
370 if (currentState == DeviceDiscoveryState.DISCOVERED) {
371 Log.d(Config.LOGTAG, "session proposal already at discovered. not going to fall back");
372 return;
373 }
374 this.rtpSessionProposals.put(sessionProposal, target);
375 mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, sessionProposal.with, sessionProposal.sessionId, target.toEndUserState());
376 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": flagging session " + sessionId + " as " + target);
377 }
378 }
379
380 public void rejectRtpSession(final String sessionId) {
381 for (final AbstractJingleConnection connection : this.connections.values()) {
382 if (connection.getId().sessionId.equals(sessionId)) {
383 if (connection instanceof JingleRtpConnection) {
384 ((JingleRtpConnection) connection).rejectCall();
385 }
386 }
387 }
388 }
389
390 public void endRtpSession(final String sessionId) {
391 for (final AbstractJingleConnection connection : this.connections.values()) {
392 if (connection.getId().sessionId.equals(sessionId)) {
393 if (connection instanceof JingleRtpConnection) {
394 ((JingleRtpConnection) connection).endCall();
395 }
396 }
397 }
398 }
399
400 public void failProceed(Account account, final Jid with, String sessionId) {
401 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
402 final AbstractJingleConnection existingJingleConnection = connections.get(id);
403 if (existingJingleConnection instanceof JingleRtpConnection) {
404 ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed();
405 }
406 }
407
408 public enum DeviceDiscoveryState {
409 SEARCHING, DISCOVERED, FAILED;
410
411 public RtpEndUserState toEndUserState() {
412 switch (this) {
413 case SEARCHING:
414 return RtpEndUserState.FINDING_DEVICE;
415 case DISCOVERED:
416 return RtpEndUserState.RINGING;
417 default:
418 return RtpEndUserState.CONNECTIVITY_ERROR;
419 }
420 }
421 }
422
423 public static class RtpSessionProposal {
424 public final Jid with;
425 public final String sessionId;
426 private final Account account;
427
428 private RtpSessionProposal(Account account, Jid with, String sessionId) {
429 this.account = account;
430 this.with = with;
431 this.sessionId = sessionId;
432 }
433
434 public static RtpSessionProposal of(Account account, Jid with) {
435 return new RtpSessionProposal(account, with, nextRandomId());
436 }
437
438 @Override
439 public boolean equals(Object o) {
440 if (this == o) return true;
441 if (o == null || getClass() != o.getClass()) return false;
442 RtpSessionProposal proposal = (RtpSessionProposal) o;
443 return Objects.equal(account.getJid(), proposal.account.getJid()) &&
444 Objects.equal(with, proposal.with) &&
445 Objects.equal(sessionId, proposal.sessionId);
446 }
447
448 @Override
449 public int hashCode() {
450 return Objects.hashCode(account.getJid(), with, sessionId);
451 }
452 }
453}