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