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.util.HashMap;
  9import java.util.HashSet;
 10import java.util.Map;
 11import java.util.Set;
 12import java.util.UUID;
 13import java.util.concurrent.ConcurrentHashMap;
 14
 15import eu.siacs.conversations.Config;
 16import eu.siacs.conversations.entities.Account;
 17import eu.siacs.conversations.entities.Contact;
 18import eu.siacs.conversations.entities.Message;
 19import eu.siacs.conversations.entities.Transferable;
 20import eu.siacs.conversations.services.AbstractConnectionManager;
 21import eu.siacs.conversations.services.XmppConnectionService;
 22import eu.siacs.conversations.xml.Element;
 23import eu.siacs.conversations.xml.Namespace;
 24import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 25import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
 26import eu.siacs.conversations.xmpp.jingle.stanzas.FileTransferDescription;
 27import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 28import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 29import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 30import rocks.xmpp.addr.Jid;
 31
 32public class JingleConnectionManager extends AbstractConnectionManager {
 33    private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals = new HashMap<>();
 34    private final Map<AbstractJingleConnection.Id, AbstractJingleConnection> connections = new ConcurrentHashMap<>();
 35
 36    private HashMap<Jid, JingleCandidate> primaryCandidates = new HashMap<>();
 37
 38    public JingleConnectionManager(XmppConnectionService service) {
 39        super(service);
 40    }
 41
 42    public void deliverPacket(final Account account, final JinglePacket packet) {
 43        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, packet);
 44        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 45        if (existingJingleConnection != null) {
 46            existingJingleConnection.deliverPacket(packet);
 47        } else if (packet.getAction() == JinglePacket.Action.SESSION_INITIATE) {
 48            final Jid from = packet.getFrom();
 49            final Content content = packet.getJingleContent();
 50            final String descriptionNamespace = content == null ? null : content.getDescriptionNamespace();
 51            final AbstractJingleConnection connection;
 52            if (FileTransferDescription.NAMESPACES.contains(descriptionNamespace)) {
 53                connection = new JingleFileTransferConnection(this, id, from);
 54            } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace)) {
 55                connection = new JingleRtpConnection(this, id, from);
 56            } else {
 57                //TODO return feature-not-implemented
 58                return;
 59            }
 60            connections.put(id, connection);
 61            connection.deliverPacket(packet);
 62        } else {
 63            Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
 64            final IqPacket response = packet.generateResponse(IqPacket.TYPE.ERROR);
 65            final Element error = response.addChild("error");
 66            error.setAttribute("type", "cancel");
 67            error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
 68            error.addChild("unknown-session", "urn:xmpp:jingle:errors:1");
 69            account.getXmppConnection().sendIqPacket(response, null);
 70        }
 71    }
 72
 73    public void deliverMessage(final Account account, final Jid to, final Jid from, final Element message) {
 74        Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
 75        final String sessionId = message.getAttribute("id");
 76        if (sessionId == null) {
 77            return;
 78        }
 79        final Jid with;
 80        if (account.getJid().asBareJid().equals(from.asBareJid())) {
 81            with = to;
 82        } else {
 83            with = from;
 84        }
 85        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received jingle message from " + from + " with=" + with + " " + message);
 86        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
 87        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 88        if (existingJingleConnection != null) {
 89            if (existingJingleConnection instanceof JingleRtpConnection) {
 90                ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message);
 91            } else {
 92                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
 93            }
 94        } else if ("propose".equals(message.getName())) {
 95            final Element description = message.findChild("description");
 96            final String namespace = description == null ? null : description.getNamespace();
 97            if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
 98                final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, with);
 99                this.connections.put(id, rtpConnection);
100                rtpConnection.deliveryMessage(from, message);
101            } else {
102                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed " + namespace + " session");
103            }
104        } else if ("proceed".equals(message.getName())) {
105            if (!with.equals(from)) {
106                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore carbon copied proceed");
107                return;
108            }
109            final RtpSessionProposal proposal = new RtpSessionProposal(account, with.asBareJid(), sessionId);
110            synchronized (rtpSessionProposals) {
111                if (rtpSessionProposals.remove(proposal) != null) {
112                    final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
113                    this.connections.put(id, rtpConnection);
114                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
115                    rtpConnection.deliveryMessage(from, message);
116                } else {
117                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + with);
118                }
119            }
120        } else {
121            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message");
122        }
123
124    }
125
126    public void startJingleFileTransfer(final Message message) {
127        Preconditions.checkArgument(message.isFileOrImage(), "Message is not of type file or image");
128        final Transferable old = message.getTransferable();
129        if (old != null) {
130            old.cancel();
131        }
132        final Account account = message.getConversation().getAccount();
133        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
134        final JingleFileTransferConnection connection = new JingleFileTransferConnection(this, id, account.getJid());
135        mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
136        this.connections.put(id, connection);
137        connection.init(message);
138    }
139
140    void finishConnection(final AbstractJingleConnection connection) {
141        this.connections.remove(connection.getId());
142    }
143
144    void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
145        if (Config.DISABLE_PROXY_LOOKUP) {
146            listener.onPrimaryCandidateFound(false, null);
147            return;
148        }
149        if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
150            final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
151            if (proxy != null) {
152                IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
153                iq.setTo(proxy);
154                iq.query(Namespace.BYTE_STREAMS);
155                account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
156
157                    @Override
158                    public void onIqPacketReceived(Account account, IqPacket packet) {
159                        final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
160                        final String host = streamhost == null ? null : streamhost.getAttribute("host");
161                        final String port = streamhost == null ? null : streamhost.getAttribute("port");
162                        if (host != null && port != null) {
163                            try {
164                                JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
165                                candidate.setHost(host);
166                                candidate.setPort(Integer.parseInt(port));
167                                candidate.setType(JingleCandidate.TYPE_PROXY);
168                                candidate.setJid(proxy);
169                                candidate.setPriority(655360 + (initiator ? 30 : 0));
170                                primaryCandidates.put(account.getJid().asBareJid(), candidate);
171                                listener.onPrimaryCandidateFound(true, candidate);
172                            } catch (final NumberFormatException e) {
173                                listener.onPrimaryCandidateFound(false, null);
174                            }
175                        } else {
176                            listener.onPrimaryCandidateFound(false, null);
177                        }
178                    }
179                });
180            } else {
181                listener.onPrimaryCandidateFound(false, null);
182            }
183
184        } else {
185            listener.onPrimaryCandidateFound(true,
186                    this.primaryCandidates.get(account.getJid().asBareJid()));
187        }
188    }
189
190    public void proposeJingleRtpSession(final Account account, final Contact contact) {
191        final RtpSessionProposal proposal = RtpSessionProposal.of(account, contact.getJid().asBareJid());
192        synchronized (this.rtpSessionProposals) {
193            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
194            final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
195            Log.d(Config.LOGTAG,messagePacket.toString());
196            mXmppConnectionService.sendMessagePacket(account, messagePacket);
197        }
198    }
199
200    static String nextRandomId() {
201        return UUID.randomUUID().toString();
202    }
203
204    public void deliverIbbPacket(Account account, IqPacket packet) {
205        final String sid;
206        final Element payload;
207        if (packet.hasChild("open", Namespace.IBB)) {
208            payload = packet.findChild("open", Namespace.IBB);
209            sid = payload.getAttribute("sid");
210        } else if (packet.hasChild("data", Namespace.IBB)) {
211            payload = packet.findChild("data", Namespace.IBB);
212            sid = payload.getAttribute("sid");
213        } else if (packet.hasChild("close", Namespace.IBB)) {
214            payload = packet.findChild("close", Namespace.IBB);
215            sid = payload.getAttribute("sid");
216        } else {
217            payload = null;
218            sid = null;
219        }
220        if (sid != null) {
221            for (final AbstractJingleConnection connection : this.connections.values()) {
222                if (connection instanceof JingleFileTransferConnection) {
223                    final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
224                    final JingleTransport transport = fileTransfer.getTransport();
225                    if (transport instanceof JingleInBandTransport) {
226                        final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
227                        if (inBandTransport.matches(account, sid)) {
228                            inBandTransport.deliverPayload(packet, payload);
229                        }
230                        return;
231                    }
232                }
233            }
234        }
235        Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
236        account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
237    }
238
239    public void cancelInTransmission() {
240        for (AbstractJingleConnection connection : this.connections.values()) {
241            /*if (connection.getJingleStatus() == JingleFileTransferConnection.JINGLE_STATUS_TRANSMITTING) {
242                connection.abort("connectivity-error");
243            }*/
244        }
245    }
246
247    public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
248        final RtpSessionProposal sessionProposal = new RtpSessionProposal(account,from.asBareJid(),sessionId);
249        synchronized (this.rtpSessionProposals) {
250            final DeviceDiscoveryState currentState = rtpSessionProposals.get(sessionProposal);
251            if (currentState == null) {
252                Log.d(Config.LOGTAG,"unable to find session proposal for session id "+sessionId);
253                return;
254            }
255            if (currentState == DeviceDiscoveryState.DISCOVERED) {
256                Log.d(Config.LOGTAG,"session proposal already at discovered. not going to fall back");
257                return;
258            }
259            this.rtpSessionProposals.put(sessionProposal, target);
260            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": flagging session "+sessionId+" as "+target);
261        }
262    }
263
264    public static class RtpSessionProposal {
265        private final Account account;
266        public final Jid with;
267        public final String sessionId;
268
269        private RtpSessionProposal(Account account, Jid with, String sessionId) {
270            this.account = account;
271            this.with = with;
272            this.sessionId = sessionId;
273        }
274
275        public static RtpSessionProposal of(Account account, Jid with) {
276            return new RtpSessionProposal(account, with, UUID.randomUUID().toString());
277        }
278
279        @Override
280        public boolean equals(Object o) {
281            if (this == o) return true;
282            if (o == null || getClass() != o.getClass()) return false;
283            RtpSessionProposal proposal = (RtpSessionProposal) o;
284            return Objects.equal(account.getJid(), proposal.account.getJid()) &&
285                    Objects.equal(with, proposal.with) &&
286                    Objects.equal(sessionId, proposal.sessionId);
287        }
288
289        @Override
290        public int hashCode() {
291            return Objects.hashCode(account.getJid(), with, sessionId);
292        }
293    }
294
295    public enum DeviceDiscoveryState {
296        SEARCHING, DISCOVERED, FAILED
297    }
298}