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