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