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    private Set<String> getCombinedIceOptions() {
214        final Collection<List<String>> combinedIceOptions =
215                Collections2.transform(contents.values(), dt -> dt.transport.getIceOptions());
216        return ImmutableSet.copyOf(Iterables.concat(combinedIceOptions));
217    }
218
219    public Set<IceUdpTransportInfo.Credentials> getCredentials() {
220        final Set<IceUdpTransportInfo.Credentials> credentials =
221                ImmutableSet.copyOf(
222                        Collections2.transform(
223                                contents.values(), dt -> dt.transport.getCredentials()));
224        if (credentials.isEmpty()) {
225            throw new IllegalStateException("Content map does not have any credentials");
226        }
227        return credentials;
228    }
229
230    public IceUdpTransportInfo.Credentials getCredentials(final String contentName) {
231        final DescriptionTransport descriptionTransport = this.contents.get(contentName);
232        if (descriptionTransport == null) {
233            throw new IllegalArgumentException(
234                    String.format(
235                            "Unable to find transport info for content name %s", contentName));
236        }
237        return descriptionTransport.transport.getCredentials();
238    }
239
240    public IceUdpTransportInfo.Setup getDtlsSetup() {
241        final Set<IceUdpTransportInfo.Setup> setups =
242                ImmutableSet.copyOf(
243                        Collections2.transform(
244                                contents.values(), dt -> dt.transport.getFingerprint().getSetup()));
245        final IceUdpTransportInfo.Setup setup = Iterables.getFirst(setups, null);
246        if (setups.size() == 1 && setup != null) {
247            return setup;
248        }
249        throw new IllegalStateException("Content map doesn't have distinct DTLS setup");
250    }
251
252    private DTLS getDistinctDtls() {
253        final Set<DTLS> dtlsSet =
254                ImmutableSet.copyOf(
255                        Collections2.transform(
256                                contents.values(),
257                                dt -> {
258                                    final IceUdpTransportInfo.Fingerprint fp =
259                                            dt.transport.getFingerprint();
260                                    return new DTLS(fp.getHash(), fp.getSetup(), fp.getContent());
261                                }));
262        final DTLS dtls = Iterables.getFirst(dtlsSet, null);
263        if (dtlsSet.size() == 1 && dtls != null) {
264            return dtls;
265        }
266        throw new IllegalStateException("Content map doesn't have distinct DTLS setup");
267    }
268
269    public boolean emptyCandidates() {
270        int count = 0;
271        for (DescriptionTransport descriptionTransport : contents.values()) {
272            count += descriptionTransport.transport.getCandidates().size();
273        }
274        return count == 0;
275    }
276
277    public RtpContentMap modifiedCredentials(
278            IceUdpTransportInfo.Credentials credentials, final IceUdpTransportInfo.Setup setup) {
279        final ImmutableMap.Builder<String, DescriptionTransport> contentMapBuilder =
280                new ImmutableMap.Builder<>();
281        for (final Map.Entry<String, DescriptionTransport> content : contents.entrySet()) {
282            final DescriptionTransport descriptionTransport = content.getValue();
283            final RtpDescription rtpDescription = descriptionTransport.description;
284            final IceUdpTransportInfo transportInfo = descriptionTransport.transport;
285            final IceUdpTransportInfo modifiedTransportInfo =
286                    transportInfo.modifyCredentials(credentials, setup);
287            contentMapBuilder.put(
288                    content.getKey(),
289                    new DescriptionTransport(
290                            descriptionTransport.senders, rtpDescription, modifiedTransportInfo));
291        }
292        return new RtpContentMap(this.group, contentMapBuilder.build());
293    }
294
295    public RtpContentMap modifiedSenders(final Content.Senders senders) {
296        return new RtpContentMap(
297                this.group,
298                Maps.transformValues(
299                        contents,
300                        dt -> new DescriptionTransport(senders, dt.description, dt.transport)));
301    }
302
303    public RtpContentMap toContentModification(final Collection<String> modifications) {
304        return new RtpContentMap(
305                this.group,
306                Maps.transformValues(
307                        Maps.filterKeys(contents, Predicates.in(modifications)),
308                        dt ->
309                                new DescriptionTransport(
310                                        dt.senders, dt.description, IceUdpTransportInfo.STUB)));
311    }
312
313    public RtpContentMap toStub() {
314        return new RtpContentMap(
315                null,
316                Maps.transformValues(
317                        this.contents,
318                        dt ->
319                                new DescriptionTransport(
320                                        dt.senders,
321                                        RtpDescription.stub(dt.description.getMedia()),
322                                        IceUdpTransportInfo.STUB)));
323    }
324
325    public RtpContentMap activeContents() {
326        return new RtpContentMap(group, Maps.filterValues(this.contents, dt -> dt.senders != Content.Senders.NONE));
327    }
328
329    public Diff diff(final RtpContentMap rtpContentMap) {
330        final Set<String> existingContentIds = this.contents.keySet();
331        final Set<String> newContentIds = rtpContentMap.contents.keySet();
332        return new Diff(
333                ImmutableSet.copyOf(Sets.difference(newContentIds, existingContentIds)),
334                ImmutableSet.copyOf(Sets.difference(existingContentIds, newContentIds)));
335    }
336
337    public boolean iceRestart(final RtpContentMap rtpContentMap) {
338        try {
339            return !getDistinctCredentials().equals(rtpContentMap.getDistinctCredentials());
340        } catch (final IllegalStateException e) {
341            return false;
342        }
343    }
344
345    public RtpContentMap addContent(
346            final RtpContentMap modification, final IceUdpTransportInfo.Setup setup) {
347        final IceUdpTransportInfo.Credentials credentials = getDistinctCredentials();
348        final Collection<String> iceOptions = getCombinedIceOptions();
349        final DTLS dtls = getDistinctDtls();
350        final IceUdpTransportInfo iceUdpTransportInfo =
351                IceUdpTransportInfo.of(credentials, iceOptions, setup, dtls.hash, dtls.fingerprint);
352        final Map<String, DescriptionTransport> combined = merge(contents, modification.contents);
353        final Map<String, DescriptionTransport> combinedFixedTransport =
354                Maps.transformValues(
355                        combined,
356                        dt ->
357                                new DescriptionTransport(
358                                        dt.senders, dt.description, iceUdpTransportInfo));
359        return new RtpContentMap(modification.group, combinedFixedTransport);
360    }
361
362    private static Map<String, DescriptionTransport> merge(
363            final Map<String, DescriptionTransport> a, final Map<String, DescriptionTransport> b) {
364        final Map<String, DescriptionTransport> combined = new HashMap<>();
365        combined.putAll(a);
366        combined.putAll(b);
367        return ImmutableMap.copyOf(combined);
368    }
369
370    public static class DescriptionTransport {
371        public final Content.Senders senders;
372        public final RtpDescription description;
373        public final IceUdpTransportInfo transport;
374
375        public DescriptionTransport(
376                final Content.Senders senders,
377                final RtpDescription description,
378                final IceUdpTransportInfo transport) {
379            this.senders = senders;
380            this.description = description;
381            this.transport = transport;
382        }
383
384        public static DescriptionTransport of(final Content content) {
385            final GenericDescription description = content.getDescription();
386            final GenericTransportInfo transportInfo = content.getTransport();
387            final Content.Senders senders = content.getSenders();
388            final RtpDescription rtpDescription;
389            final IceUdpTransportInfo iceUdpTransportInfo;
390            if (description == null) {
391                rtpDescription = null;
392            } else if (description instanceof RtpDescription) {
393                rtpDescription = (RtpDescription) description;
394            } else {
395                throw new UnsupportedApplicationException(
396                        "Content does not contain rtp description");
397            }
398            if (transportInfo instanceof IceUdpTransportInfo) {
399                iceUdpTransportInfo = (IceUdpTransportInfo) transportInfo;
400            } else {
401                throw new UnsupportedTransportException(
402                        "Content does not contain ICE-UDP transport");
403            }
404            return new DescriptionTransport(
405                    senders,
406                    rtpDescription,
407                    OmemoVerifiedIceUdpTransportInfo.upgrade(iceUdpTransportInfo));
408        }
409
410        private static DescriptionTransport of(
411                final SessionDescription sessionDescription,
412                final boolean isInitiator,
413                final SessionDescription.Media media) {
414            final Content.Senders senders = Content.Senders.of(media, isInitiator);
415            final RtpDescription rtpDescription = RtpDescription.of(sessionDescription, media);
416            final IceUdpTransportInfo transportInfo =
417                    IceUdpTransportInfo.of(sessionDescription, media);
418            return new DescriptionTransport(senders, rtpDescription, transportInfo);
419        }
420
421        public static Map<String, DescriptionTransport> of(final Map<String, Content> contents) {
422            return ImmutableMap.copyOf(
423                    Maps.transformValues(
424                            contents, content -> content == null ? null : of(content)));
425        }
426    }
427
428    public static class UnsupportedApplicationException extends IllegalArgumentException {
429        UnsupportedApplicationException(String message) {
430            super(message);
431        }
432    }
433
434    public static class UnsupportedTransportException extends IllegalArgumentException {
435        UnsupportedTransportException(String message) {
436            super(message);
437        }
438    }
439
440    public static final class Diff {
441        public final Set<String> added;
442        public final Set<String> removed;
443
444        private Diff(final Set<String> added, final Set<String> removed) {
445            this.added = added;
446            this.removed = removed;
447        }
448
449        public boolean hasModifications() {
450            return !this.added.isEmpty() || !this.removed.isEmpty();
451        }
452
453        public boolean isEmpty() {
454            return this.added.isEmpty() && this.removed.isEmpty();
455        }
456
457        @Override
458        @Nonnull
459        public String toString() {
460            return MoreObjects.toStringHelper(this)
461                    .add("added", added)
462                    .add("removed", removed)
463                    .toString();
464        }
465    }
466
467    public static final class DTLS {
468        public final String hash;
469        public final IceUdpTransportInfo.Setup setup;
470        public final String fingerprint;
471
472        private DTLS(String hash, IceUdpTransportInfo.Setup setup, String fingerprint) {
473            this.hash = hash;
474            this.setup = setup;
475            this.fingerprint = fingerprint;
476        }
477
478        @Override
479        public boolean equals(Object o) {
480            if (this == o) return true;
481            if (o == null || getClass() != o.getClass()) return false;
482            DTLS dtls = (DTLS) o;
483            return Objects.equal(hash, dtls.hash)
484                    && setup == dtls.setup
485                    && Objects.equal(fingerprint, dtls.fingerprint);
486        }
487
488        @Override
489        public int hashCode() {
490            return Objects.hashCode(hash, setup, fingerprint);
491        }
492    }
493}