JingleConnectionManager.java

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