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 proposeJingleRtpSession(final Account account, final Contact contact) {
192        final RtpSessionProposal proposal = RtpSessionProposal.of(account, contact.getJid().asBareJid());
193        synchronized (this.rtpSessionProposals) {
194            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
195            final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
196            Log.d(Config.LOGTAG,messagePacket.toString());
197            mXmppConnectionService.sendMessagePacket(account, messagePacket);
198        }
199    }
200
201    static String nextRandomId() {
202        return UUID.randomUUID().toString();
203    }
204
205    public void deliverIbbPacket(Account account, IqPacket packet) {
206        final String sid;
207        final Element payload;
208        if (packet.hasChild("open", Namespace.IBB)) {
209            payload = packet.findChild("open", Namespace.IBB);
210            sid = payload.getAttribute("sid");
211        } else if (packet.hasChild("data", Namespace.IBB)) {
212            payload = packet.findChild("data", Namespace.IBB);
213            sid = payload.getAttribute("sid");
214        } else if (packet.hasChild("close", Namespace.IBB)) {
215            payload = packet.findChild("close", Namespace.IBB);
216            sid = payload.getAttribute("sid");
217        } else {
218            payload = null;
219            sid = null;
220        }
221        if (sid != null) {
222            for (final AbstractJingleConnection connection : this.connections.values()) {
223                if (connection instanceof JingleFileTransferConnection) {
224                    final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
225                    final JingleTransport transport = fileTransfer.getTransport();
226                    if (transport instanceof JingleInBandTransport) {
227                        final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
228                        if (inBandTransport.matches(account, sid)) {
229                            inBandTransport.deliverPayload(packet, payload);
230                        }
231                        return;
232                    }
233                }
234            }
235        }
236        Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
237        account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
238    }
239
240    public void cancelInTransmission() {
241        for (AbstractJingleConnection connection : this.connections.values()) {
242            /*if (connection.getJingleStatus() == JingleFileTransferConnection.JINGLE_STATUS_TRANSMITTING) {
243                connection.abort("connectivity-error");
244            }*/
245        }
246    }
247
248    public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
249        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, Jid.ofEscaped(with), sessionId);
250        final AbstractJingleConnection connection = connections.get(id);
251        if (connection instanceof JingleRtpConnection) {
252            return new WeakReference<>((JingleRtpConnection) connection);
253        }
254        return null;
255    }
256
257    public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
258        final RtpSessionProposal sessionProposal = new RtpSessionProposal(account,from.asBareJid(),sessionId);
259        synchronized (this.rtpSessionProposals) {
260            final DeviceDiscoveryState currentState = rtpSessionProposals.get(sessionProposal);
261            if (currentState == null) {
262                Log.d(Config.LOGTAG,"unable to find session proposal for session id "+sessionId);
263                return;
264            }
265            if (currentState == DeviceDiscoveryState.DISCOVERED) {
266                Log.d(Config.LOGTAG,"session proposal already at discovered. not going to fall back");
267                return;
268            }
269            this.rtpSessionProposals.put(sessionProposal, target);
270            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": flagging session "+sessionId+" as "+target);
271        }
272    }
273
274    public static class RtpSessionProposal {
275        private final Account account;
276        public final Jid with;
277        public final String sessionId;
278
279        private RtpSessionProposal(Account account, Jid with, String sessionId) {
280            this.account = account;
281            this.with = with;
282            this.sessionId = sessionId;
283        }
284
285        public static RtpSessionProposal of(Account account, Jid with) {
286            return new RtpSessionProposal(account, with, UUID.randomUUID().toString());
287        }
288
289        @Override
290        public boolean equals(Object o) {
291            if (this == o) return true;
292            if (o == null || getClass() != o.getClass()) return false;
293            RtpSessionProposal proposal = (RtpSessionProposal) o;
294            return Objects.equal(account.getJid(), proposal.account.getJid()) &&
295                    Objects.equal(with, proposal.with) &&
296                    Objects.equal(sessionId, proposal.sessionId);
297        }
298
299        @Override
300        public int hashCode() {
301            return Objects.hashCode(account.getJid(), with, sessionId);
302        }
303    }
304
305    public enum DeviceDiscoveryState {
306        SEARCHING, DISCOVERED, FAILED
307    }
308}