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