RtpContentMap.java

  1package eu.siacs.conversations.xmpp.jingle;
  2
  3import com.google.common.base.MoreObjects;
  4import com.google.common.base.Objects;
  5import com.google.common.base.Preconditions;
  6import com.google.common.base.Predicates;
  7import com.google.common.base.Strings;
  8import com.google.common.collect.Collections2;
  9import com.google.common.collect.ImmutableList;
 10import com.google.common.collect.ImmutableMap;
 11import com.google.common.collect.ImmutableSet;
 12import com.google.common.collect.Iterables;
 13import com.google.common.collect.Maps;
 14import com.google.common.collect.Sets;
 15
 16import java.util.Collection;
 17import java.util.HashMap;
 18import java.util.List;
 19import java.util.Map;
 20import java.util.Set;
 21
 22import javax.annotation.Nonnull;
 23
 24import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
 25import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
 26import eu.siacs.conversations.xmpp.jingle.stanzas.GenericTransportInfo;
 27import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
 28import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
 29import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 30import eu.siacs.conversations.xmpp.jingle.stanzas.OmemoVerifiedIceUdpTransportInfo;
 31import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
 32
 33public class RtpContentMap {
 34
 35    public final Group group;
 36    public final Map<String, DescriptionTransport> contents;
 37
 38    public RtpContentMap(Group group, Map<String, DescriptionTransport> contents) {
 39        this.group = group;
 40        this.contents = contents;
 41    }
 42
 43    public static RtpContentMap of(final JinglePacket jinglePacket) {
 44        final Map<String, DescriptionTransport> contents =
 45                DescriptionTransport.of(jinglePacket.getJingleContents());
 46        if (isOmemoVerified(contents)) {
 47            return new OmemoVerifiedRtpContentMap(jinglePacket.getGroup(), contents);
 48        } else {
 49            return new RtpContentMap(jinglePacket.getGroup(), contents);
 50        }
 51    }
 52
 53    private static boolean isOmemoVerified(Map<String, DescriptionTransport> contents) {
 54        final Collection<DescriptionTransport> values = contents.values();
 55        if (values.size() == 0) {
 56            return false;
 57        }
 58        for (final DescriptionTransport descriptionTransport : values) {
 59            if (descriptionTransport.transport instanceof OmemoVerifiedIceUdpTransportInfo) {
 60                continue;
 61            }
 62            return false;
 63        }
 64        return true;
 65    }
 66
 67    public static RtpContentMap of(
 68            final SessionDescription sessionDescription, final boolean isInitiator) {
 69        final ImmutableMap.Builder<String, DescriptionTransport> contentMapBuilder =
 70                new ImmutableMap.Builder<>();
 71        for (SessionDescription.Media media : sessionDescription.media) {
 72            final String id = Iterables.getFirst(media.attributes.get("mid"), null);
 73            Preconditions.checkNotNull(id, "media has no mid");
 74            contentMapBuilder.put(
 75                    id, DescriptionTransport.of(sessionDescription, isInitiator, media));
 76        }
 77        final String groupAttribute =
 78                Iterables.getFirst(sessionDescription.attributes.get("group"), null);
 79        final Group group = groupAttribute == null ? null : Group.ofSdpString(groupAttribute);
 80        return new RtpContentMap(group, contentMapBuilder.build());
 81    }
 82
 83    public Set<Media> getMedia() {
 84        return Sets.newHashSet(
 85                Collections2.transform(
 86                        contents.values(),
 87                        input -> {
 88                            final RtpDescription rtpDescription =
 89                                    input == null ? null : input.description;
 90                            return rtpDescription == null
 91                                    ? Media.UNKNOWN
 92                                    : input.description.getMedia();
 93                        }));
 94    }
 95
 96    public Set<Content.Senders> getSenders() {
 97        return ImmutableSet.copyOf(Collections2.transform(contents.values(),dt -> dt.senders));
 98    }
 99
100    public List<String> getNames() {
101        return ImmutableList.copyOf(contents.keySet());
102    }
103
104    void requireContentDescriptions() {
105        if (this.contents.size() == 0) {
106            throw new IllegalStateException("No contents available");
107        }
108        for (Map.Entry<String, DescriptionTransport> entry : this.contents.entrySet()) {
109            if (entry.getValue().description == null) {
110                throw new IllegalStateException(
111                        String.format("%s is lacking content description", entry.getKey()));
112            }
113        }
114    }
115
116    void requireDTLSFingerprint() {
117        requireDTLSFingerprint(false);
118    }
119
120    void requireDTLSFingerprint(final boolean requireActPass) {
121        if (this.contents.size() == 0) {
122            throw new IllegalStateException("No contents available");
123        }
124        for (Map.Entry<String, DescriptionTransport> entry : this.contents.entrySet()) {
125            final IceUdpTransportInfo transport = entry.getValue().transport;
126            final IceUdpTransportInfo.Fingerprint fingerprint = transport.getFingerprint();
127            if (fingerprint == null
128                    || Strings.isNullOrEmpty(fingerprint.getContent())
129                    || Strings.isNullOrEmpty(fingerprint.getHash())) {
130                throw new SecurityException(
131                        String.format(
132                                "Use of DTLS-SRTP (XEP-0320) is required for content %s",
133                                entry.getKey()));
134            }
135            final IceUdpTransportInfo.Setup setup = fingerprint.getSetup();
136            if (setup == null) {
137                throw new SecurityException(
138                        String.format(
139                                "Use of DTLS-SRTP (XEP-0320) is required for content %s but missing setup attribute",
140                                entry.getKey()));
141            }
142            if (requireActPass && setup != IceUdpTransportInfo.Setup.ACTPASS) {
143                throw new SecurityException(
144                        "Initiator needs to offer ACTPASS as setup for DTLS-SRTP (XEP-0320)");
145            }
146        }
147    }
148
149    JinglePacket toJinglePacket(final JinglePacket.Action action, final String sessionId) {
150        final JinglePacket jinglePacket = new JinglePacket(action, sessionId);
151        if (this.group != null) {
152            jinglePacket.addGroup(this.group);
153        }
154        for (Map.Entry<String, DescriptionTransport> entry : this.contents.entrySet()) {
155            final DescriptionTransport descriptionTransport = entry.getValue();
156            final Content content =
157                    new Content(
158                            Content.Creator.INITIATOR,
159                            descriptionTransport.senders,
160                            entry.getKey());
161            if (descriptionTransport.description != null) {
162                content.addChild(descriptionTransport.description);
163            }
164            content.addChild(descriptionTransport.transport);
165            jinglePacket.addJingleContent(content);
166        }
167        return jinglePacket;
168    }
169
170    RtpContentMap transportInfo(
171            final String contentName, final IceUdpTransportInfo.Candidate candidate) {
172        final RtpContentMap.DescriptionTransport descriptionTransport = contents.get(contentName);
173        final IceUdpTransportInfo transportInfo =
174                descriptionTransport == null ? null : descriptionTransport.transport;
175        if (transportInfo == null) {
176            throw new IllegalArgumentException(
177                    "Unable to find transport info for content name " + contentName);
178        }
179        final IceUdpTransportInfo newTransportInfo = transportInfo.cloneWrapper();
180        newTransportInfo.addChild(candidate);
181        return new RtpContentMap(
182                null,
183                ImmutableMap.of(
184                        contentName,
185                        new DescriptionTransport(
186                                descriptionTransport.senders, null, newTransportInfo)));
187    }
188
189    RtpContentMap transportInfo() {
190        return new RtpContentMap(
191                null,
192                Maps.transformValues(
193                        contents,
194                        dt ->
195                                new DescriptionTransport(
196                                        dt.senders, null, dt.transport.cloneWrapper())));
197    }
198
199    public IceUdpTransportInfo.Credentials getDistinctCredentials() {
200        final Set<IceUdpTransportInfo.Credentials> allCredentials = getCredentials();
201        final IceUdpTransportInfo.Credentials credentials =
202                Iterables.getFirst(allCredentials, null);
203        if (allCredentials.size() == 1 && credentials != null) {
204            if (Strings.isNullOrEmpty(credentials.password)
205                    || Strings.isNullOrEmpty(credentials.ufrag)) {
206                throw new IllegalStateException("Credentials are missing password or ufrag");
207            }
208            return credentials;
209        }
210        throw new IllegalStateException("Content map does not have distinct credentials");
211    }
212
213    public Set<IceUdpTransportInfo.Credentials> getCredentials() {
214        final Set<IceUdpTransportInfo.Credentials> credentials =
215                ImmutableSet.copyOf(
216                        Collections2.transform(
217                                contents.values(), dt -> dt.transport.getCredentials()));
218        if (credentials.isEmpty()) {
219            throw new IllegalStateException("Content map does not have any credentials");
220        }
221        return credentials;
222    }
223
224    public IceUdpTransportInfo.Credentials getCredentials(final String contentName) {
225        final DescriptionTransport descriptionTransport = this.contents.get(contentName);
226        if (descriptionTransport == null) {
227            throw new IllegalArgumentException(
228                    String.format(
229                            "Unable to find transport info for content name %s", contentName));
230        }
231        return descriptionTransport.transport.getCredentials();
232    }
233
234    public IceUdpTransportInfo.Setup getDtlsSetup() {
235        final Set<IceUdpTransportInfo.Setup> setups =
236                ImmutableSet.copyOf(
237                        Collections2.transform(
238                                contents.values(), dt -> dt.transport.getFingerprint().getSetup()));
239        final IceUdpTransportInfo.Setup setup = Iterables.getFirst(setups, null);
240        if (setups.size() == 1 && setup != null) {
241            return setup;
242        }
243        throw new IllegalStateException("Content map doesn't have distinct DTLS setup");
244    }
245
246    private DTLS getDistinctDtls() {
247        final Set<DTLS> dtlsSet =
248                ImmutableSet.copyOf(
249                        Collections2.transform(
250                                contents.values(),
251                                dt -> {
252                                    final IceUdpTransportInfo.Fingerprint fp =
253                                            dt.transport.getFingerprint();
254                                    return new DTLS(fp.getHash(), fp.getSetup(), fp.getContent());
255                                }));
256        final DTLS dtls = Iterables.getFirst(dtlsSet, null);
257        if (dtlsSet.size() == 1 && dtls != null) {
258            return dtls;
259        }
260        throw new IllegalStateException("Content map doesn't have distinct DTLS setup");
261    }
262
263    public boolean emptyCandidates() {
264        int count = 0;
265        for (DescriptionTransport descriptionTransport : contents.values()) {
266            count += descriptionTransport.transport.getCandidates().size();
267        }
268        return count == 0;
269    }
270
271    public RtpContentMap modifiedCredentials(
272            IceUdpTransportInfo.Credentials credentials, final IceUdpTransportInfo.Setup setup) {
273        final ImmutableMap.Builder<String, DescriptionTransport> contentMapBuilder =
274                new ImmutableMap.Builder<>();
275        for (final Map.Entry<String, DescriptionTransport> content : contents.entrySet()) {
276            final DescriptionTransport descriptionTransport = content.getValue();
277            final RtpDescription rtpDescription = descriptionTransport.description;
278            final IceUdpTransportInfo transportInfo = descriptionTransport.transport;
279            final IceUdpTransportInfo modifiedTransportInfo =
280                    transportInfo.modifyCredentials(credentials, setup);
281            contentMapBuilder.put(
282                    content.getKey(),
283                    new DescriptionTransport(
284                            descriptionTransport.senders, rtpDescription, modifiedTransportInfo));
285        }
286        return new RtpContentMap(this.group, contentMapBuilder.build());
287    }
288
289    public RtpContentMap modifiedSenders(final Content.Senders senders) {
290        return new RtpContentMap(
291                this.group,
292                Maps.transformValues(
293                        contents,
294                        dt -> new DescriptionTransport(senders, dt.description, dt.transport)));
295    }
296
297    public RtpContentMap toContentModification(final Collection<String> modifications) {
298        return new RtpContentMap(
299                this.group,
300                Maps.transformValues(
301                        Maps.filterKeys(contents, Predicates.in(modifications)),
302                        dt ->
303                                new DescriptionTransport(
304                                        dt.senders, dt.description, IceUdpTransportInfo.STUB)));
305    }
306
307    public RtpContentMap toStub() {
308        return new RtpContentMap(
309                null,
310                Maps.transformValues(
311                        this.contents,
312                        dt ->
313                                new DescriptionTransport(
314                                        dt.senders,
315                                        RtpDescription.stub(dt.description.getMedia()),
316                                        IceUdpTransportInfo.STUB)));
317    }
318
319    public RtpContentMap activeContents() {
320        return new RtpContentMap(group, Maps.filterValues(this.contents, dt -> dt.senders != Content.Senders.NONE));
321    }
322
323    public Diff diff(final RtpContentMap rtpContentMap) {
324        final Set<String> existingContentIds = this.contents.keySet();
325        final Set<String> newContentIds = rtpContentMap.contents.keySet();
326        return new Diff(
327                ImmutableSet.copyOf(Sets.difference(newContentIds, existingContentIds)),
328                ImmutableSet.copyOf(Sets.difference(existingContentIds, newContentIds)));
329    }
330
331    public boolean iceRestart(final RtpContentMap rtpContentMap) {
332        try {
333            return !getDistinctCredentials().equals(rtpContentMap.getDistinctCredentials());
334        } catch (final IllegalStateException e) {
335            return false;
336        }
337    }
338
339    public RtpContentMap addContent(
340            final RtpContentMap modification, final IceUdpTransportInfo.Setup setup) {
341        final IceUdpTransportInfo.Credentials credentials = getDistinctCredentials();
342        final DTLS dtls = getDistinctDtls();
343        final IceUdpTransportInfo iceUdpTransportInfo =
344                IceUdpTransportInfo.of(credentials, setup, dtls.hash, dtls.fingerprint);
345        final Map<String, DescriptionTransport> combined = merge(contents, modification.contents);
346                /*new ImmutableMap.Builder<String, DescriptionTransport>()
347                        .putAll(contents)
348                        .putAll(modification.contents)
349                        .build();*/
350        final Map<String, DescriptionTransport> combinedFixedTransport =
351                Maps.transformValues(
352                        combined,
353                        dt ->
354                                new DescriptionTransport(
355                                        dt.senders, dt.description, iceUdpTransportInfo));
356        return new RtpContentMap(modification.group, combinedFixedTransport);
357    }
358
359    private static Map<String, DescriptionTransport> merge(
360            final Map<String, DescriptionTransport> a, final Map<String, DescriptionTransport> b) {
361        final Map<String, DescriptionTransport> combined = new HashMap<>();
362        combined.putAll(a);
363        combined.putAll(b);
364        return ImmutableMap.copyOf(combined);
365    }
366
367    public static class DescriptionTransport {
368        public final Content.Senders senders;
369        public final RtpDescription description;
370        public final IceUdpTransportInfo transport;
371
372        public DescriptionTransport(
373                final Content.Senders senders,
374                final RtpDescription description,
375                final IceUdpTransportInfo transport) {
376            this.senders = senders;
377            this.description = description;
378            this.transport = transport;
379        }
380
381        public static DescriptionTransport of(final Content content) {
382            final GenericDescription description = content.getDescription();
383            final GenericTransportInfo transportInfo = content.getTransport();
384            final Content.Senders senders = content.getSenders();
385            final RtpDescription rtpDescription;
386            final IceUdpTransportInfo iceUdpTransportInfo;
387            if (description == null) {
388                rtpDescription = null;
389            } else if (description instanceof RtpDescription) {
390                rtpDescription = (RtpDescription) description;
391            } else {
392                throw new UnsupportedApplicationException(
393                        "Content does not contain rtp description");
394            }
395            if (transportInfo instanceof IceUdpTransportInfo) {
396                iceUdpTransportInfo = (IceUdpTransportInfo) transportInfo;
397            } else {
398                throw new UnsupportedTransportException(
399                        "Content does not contain ICE-UDP transport");
400            }
401            return new DescriptionTransport(
402                    senders,
403                    rtpDescription,
404                    OmemoVerifiedIceUdpTransportInfo.upgrade(iceUdpTransportInfo));
405        }
406
407        private static DescriptionTransport of(
408                final SessionDescription sessionDescription,
409                final boolean isInitiator,
410                final SessionDescription.Media media) {
411            final Content.Senders senders = Content.Senders.of(media, isInitiator);
412            final RtpDescription rtpDescription = RtpDescription.of(sessionDescription, media);
413            final IceUdpTransportInfo transportInfo =
414                    IceUdpTransportInfo.of(sessionDescription, media);
415            return new DescriptionTransport(senders, rtpDescription, transportInfo);
416        }
417
418        public static Map<String, DescriptionTransport> of(final Map<String, Content> contents) {
419            return ImmutableMap.copyOf(
420                    Maps.transformValues(
421                            contents, content -> content == null ? null : of(content)));
422        }
423    }
424
425    public static class UnsupportedApplicationException extends IllegalArgumentException {
426        UnsupportedApplicationException(String message) {
427            super(message);
428        }
429    }
430
431    public static class UnsupportedTransportException extends IllegalArgumentException {
432        UnsupportedTransportException(String message) {
433            super(message);
434        }
435    }
436
437    public static final class Diff {
438        public final Set<String> added;
439        public final Set<String> removed;
440
441        private Diff(final Set<String> added, final Set<String> removed) {
442            this.added = added;
443            this.removed = removed;
444        }
445
446        public boolean hasModifications() {
447            return !this.added.isEmpty() || !this.removed.isEmpty();
448        }
449
450        public boolean isEmpty() {
451            return this.added.isEmpty() && this.removed.isEmpty();
452        }
453
454        @Override
455        @Nonnull
456        public String toString() {
457            return MoreObjects.toStringHelper(this)
458                    .add("added", added)
459                    .add("removed", removed)
460                    .toString();
461        }
462    }
463
464    public static final class DTLS {
465        public final String hash;
466        public final IceUdpTransportInfo.Setup setup;
467        public final String fingerprint;
468
469        private DTLS(String hash, IceUdpTransportInfo.Setup setup, String fingerprint) {
470            this.hash = hash;
471            this.setup = setup;
472            this.fingerprint = fingerprint;
473        }
474
475        @Override
476        public boolean equals(Object o) {
477            if (this == o) return true;
478            if (o == null || getClass() != o.getClass()) return false;
479            DTLS dtls = (DTLS) o;
480            return Objects.equal(hash, dtls.hash)
481                    && setup == dtls.setup
482                    && Objects.equal(fingerprint, dtls.fingerprint);
483        }
484
485        @Override
486        public int hashCode() {
487            return Objects.hashCode(hash, setup, fingerprint);
488        }
489    }
490}