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