Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,16 @@ The timeout bounds the requests as a whole, not each read, so a server that send

`session.close()` deletes the session on the server, which frees what the server holds for it, and closes the peer. Both start at once, so a slow server does not keep the peer open, and the deletion takes at most the session's timeout. The tracks a WHIP session published stay open. `session.peer()` is a regular peer, for stats and anything else. A deletion the server refuses or that fails goes to the runtime's error handler, and also fails the future of `closeAsync()`, which completes once both are done; a peer that did not close fails it too.

`session.extensions()` gives the protocol extensions the endpoint offers for the session (RFC 9725, 4.9): the URL of each by its relation type, such as `urn:ietf:params:whip:ext:example:server-sent-events` (`urn:ietf:params:whep:ext:...` for WHEP), as the endpoint named them in `Link` header fields of its answer, resolved against it. Of a relation type named twice, the first counts. Links of other relation types are ignored, as WHIP and WHEP ask, apart from `ice-server`. The session uses none of the extensions itself; an application uses those it knows, and the map is empty if the endpoint named none.

`Whep.from(url).detect(rtc)` asks a URL with `HEAD` whether it is a WHEP endpoint, as a player may before it plays a URL it was given (draft-ietf-wish-whep-05, 4.2). Its future holds `true` when the endpoint answers 200 with the Content-Type `application/sdp` and a `Link` to the profile `urn:ietf:params:whep`; the Content-Type alone does not count. It holds `false` for any other answer, such as that of an endpoint that takes no `HEAD`, and fails when the request does. The request carries the credentials of the builder, takes its timeout at most, and follows the redirects the offer follows:

```java
if (Whep.from(url).detect(rtc).get(15, TimeUnit.SECONDS)) {
Whep.Session viewer = Whep.from(url).play(rtc).get(15, TimeUnit.SECONDS);
}
```

Endpoints have to be `https` URLs, as WHIP and WHEP ask, except on the machine the application runs on: there plain `http` will do, for a media server beside it, at `localhost`, an address in 127.0.0.0/8 or `::1`. A name that merely resolves to one of them does not count, since it may resolve elsewhere later. The same holds for the session an endpoint names and for where a redirect points.

The credentials of a session, its bearer token or its Basic user and password, go to the endpoint, and along with the deletion to the session the endpoint names in its `Location` header. That session may be on another host, but an `https` endpoint cannot name a plain `http` one. The offer follows redirects with status 307 and 308, as WHIP and WHEP ask of clients, such as those of a load balancer: up to five of them, all within the timeout, and the credentials go along. A redirect from `https` to plain `http` fails the session, and so does one with status 301, 302 or 303, which would turn the offer into a `GET`. The deletion follows no redirect; one fails it with its status.
Expand Down
54 changes: 40 additions & 14 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.UnaryOperator;

import dev.onvoid.webrtc.RTCIceCandidate;
Expand Down Expand Up @@ -492,6 +493,34 @@ private void restartByItself() {
static List<RTCIceServer> iceServers(List<String> fields) {
List<RTCIceServer> servers = new ArrayList<>();

forEachLink(fields, (target, parameters) -> {
boolean iceServer = false;

for (String relation : relations(parameters)) {
iceServer |= relation.equalsIgnoreCase("ice-server");
}

if (iceServer) {
RTCIceServer server = new RTCIceServer();
server.urls.add(target);
server.username = parameters.get("username");
server.password = parameters.get("credential");
servers.add(server);
}
});

return servers;
}

/**
* Hands over each link of Link header fields (RFC 8288) with a target,
* in order.
*
* @param fields the values of the Link header fields.
* @param link gets the target of a link, as written, and its
* parameters, by their names in lower case.
*/
static void forEachLink(List<String> fields, BiConsumer<String, Map<String, String>> link) {
for (String field : fields) {
int i = 0;

Expand All @@ -507,24 +536,21 @@ static List<RTCIceServer> iceServers(List<String> fields) {
Map<String, String> parameters = new HashMap<>();
i = parameters(field, close + 1, parameters);

String rel = parameters.getOrDefault("rel", "");
boolean iceServer = false;

for (String relation : rel.trim().split("\\s+")) {
iceServer |= relation.equalsIgnoreCase("ice-server");
}

if (iceServer && !target.isEmpty()) {
RTCIceServer server = new RTCIceServer();
server.urls.add(target);
server.username = parameters.get("username");
server.password = parameters.get("credential");
servers.add(server);
if (!target.isEmpty()) {
link.accept(target, parameters);
}
}
}
}

return servers;
/**
* @return the relation types of a link, which its "rel" parameter
* separates by spaces.
*/
static List<String> relations(Map<String, String> parameters) {
String rel = parameters.getOrDefault("rel", "").trim();

return rel.isEmpty() ? List.of() : List.of(rel.split("\\s+"));
}

/**
Expand Down
138 changes: 128 additions & 10 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -72,6 +74,8 @@ abstract class HttpSession implements AutoCloseable {

private final URI resource;

private final Map<String, URI> extensions;

private final String authorization;

private final Duration timeout;
Expand All @@ -86,10 +90,12 @@ abstract class HttpSession implements AutoCloseable {
private final CompletableFuture<Void> closed = new CompletableFuture<>();


HttpSession(WebRtc rtc, Peer peer, URI resource, String authorization, Duration timeout, HttpIce ice) {
HttpSession(WebRtc rtc, Peer peer, URI resource, Map<String, URI> extensions, String authorization,
Duration timeout, HttpIce ice) {
this.rtc = rtc;
this.peer = peer;
this.resource = resource;
this.extensions = extensions;
this.authorization = authorization;
this.timeout = timeout;
this.ice = ice;
Expand All @@ -114,6 +120,18 @@ public URI resource() {
return resource;
}

/**
* @return the protocol extensions the endpoint offers for the session
* (RFC 9725, 4.9): the URL of each by its relation type, such as {@code
* urn:ietf:params:whip:ext:example:server-sent-events}, as the endpoint
* named them in Link header fields of its answer, resolved against it.
* Empty if it named none. This API uses none of them itself; an
* application uses those it knows.
*/
public Map<String, URI> extensions() {
return extensions;
}

/**
* @return the ICE of the session, or null.
*/
Expand Down Expand Up @@ -208,10 +226,12 @@ static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl p
String authorization, Duration timeout, CompletableFuture<?> prepared, Gathering gathering,
Protocol protocol, Factory<S> factory) {
CompletableFuture<Void> abandoned = new CompletableFuture<>();
AtomicReference<Map<String, URI>> extensions = new AtomicReference<>(Map.of());
HttpIce ice = new HttpIce(rtc, rtc.httpClient(authorization != null), peer, authorization, timeout);
CompletableFuture<S> session = peer.toPublic(negotiate(rtc, peer, endpoint, authorization, timeout, prepared,
gathering, protocol, ice, abandoned)
.thenApply(resource -> factory.create(rtc, peer, resource, authorization, timeout, ice)),
gathering, protocol, ice, extensions, abandoned)
.thenApply(resource -> factory.create(rtc, peer, resource, extensions.get(), authorization, timeout,
ice)),
HttpSession::close);

// Once the session was handed out, this finds the negotiation finished.
Expand All @@ -232,15 +252,16 @@ static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl p
* ICE servers then arrive too late for this gathering and are ignored.
*
* @param prepared completes once the peer is set up for the offer.
* @param ice the ICE of the session once the offer is answered.
* @param ice the ICE of the session once the offer is answered.
* @param extensions gets the protocol extensions the endpoint named.
* @param abandoned completes when no one waits for the session anymore,
* which then ends as if it had failed.
*
* @return a future with the resource the server named, or null.
*/
private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI endpoint, String authorization,
Duration timeout, CompletableFuture<?> prepared, Gathering gathering, Protocol protocol, HttpIce ice,
CompletableFuture<?> abandoned) {
AtomicReference<Map<String, URI>> extensions, CompletableFuture<?> abandoned) {
CompletableFuture<URI> result = new CompletableFuture<>();
long started = System.nanoTime();
// The resource the server created. Whoever takes it out owns it: the
Expand Down Expand Up @@ -297,6 +318,10 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, PeerImpl peer, URI e
discard(rtc, resource.getAndSet(null), authorization, timeout);
}
})
.thenApply(reply -> {
extensions.set(reply.extensions);
return reply;
})
.thenCompose(reply -> (gathering == Gathering.COMPLETE
? CompletableFuture.<Void>completedFuture(null)
: peer.useIceServers(reply.iceServers)).handle((used, error) -> {
Expand Down Expand Up @@ -368,7 +393,7 @@ private static CompletableFuture<Reply> post(HttpCall request, URI endpoint, Str
throw new WebRtcException("The endpoint " + endpoint + " answered without a session Location");
}
requireContentType(response, "application/sdp");
return new Reply(response.body, false, null, 0, response);
return new Reply(response.body, false, null, 0, response, protocol);
}
if (protocol.counterOffers && isCounterOffer(response)) {
URI session = resourceOf(response.uri, response.header("Location"));
Expand All @@ -379,7 +404,8 @@ private static CompletableFuture<Reply> post(HttpCall request, URI endpoint, Str
}

return new Reply(response.body, true, session,
counterOfferExpiry(response.header("Content-Type"), System.currentTimeMillis()), response);
counterOfferExpiry(response.header("Content-Type"), System.currentTimeMillis()), response,
protocol);
}

throw new WebRtcException("The endpoint " + endpoint + " answered the offer with "
Expand Down Expand Up @@ -493,10 +519,14 @@ static final class Protocol {
/** Whether the endpoint may counter the offer with one of its own. */
final boolean counterOffers;

/** What the relation types of protocol extensions start with. */
final String extensions;

Protocol(Set<Integer> retried, boolean counterOffers) {

Protocol(Set<Integer> retried, boolean counterOffers, String extensions) {
this.retried = retried;
this.counterOffers = counterOffers;
this.extensions = extensions;
}
}

Expand Down Expand Up @@ -525,14 +555,19 @@ private static final class Reply {
/** The STUN and TURN servers the endpoint named. */
final List<RTCIceServer> iceServers;

/** The protocol extensions the endpoint named. */
final Map<String, URI> extensions;


Reply(String sdp, boolean counterOffer, URI session, long validUntil, HttpCall.Response response) {
Reply(String sdp, boolean counterOffer, URI session, long validUntil, HttpCall.Response response,
Protocol protocol) {
this.sdp = sdp;
this.counterOffer = counterOffer;
this.session = session;
this.validUntil = validUntil;
this.etag = response.header("ETag");
this.iceServers = HttpIce.iceServers(response.headers.allValues("Link"));
this.extensions = extensions(response.headers.allValues("Link"), response.uri, protocol.extensions);
}
}

Expand All @@ -545,7 +580,8 @@ private static final class Reply {
*/
interface Factory<S extends HttpSession> {

S create(WebRtc rtc, Peer peer, URI resource, String authorization, Duration timeout, HttpIce ice);
S create(WebRtc rtc, Peer peer, URI resource, Map<String, URI> extensions, String authorization,
Duration timeout, HttpIce ice);
}

/**
Expand Down Expand Up @@ -602,6 +638,49 @@ private static CompletableFuture<WebRtcException> discard(WebRtc rtc, URI resour
return deleted;
}

/**
* Sends a HEAD request to an endpoint, which follows the redirects the
* offer follows. It takes at most the timeout from now on.
*
* @return a future with the response, whatever its status, which fails
* with a {@link WebRtcException} if the request does.
*/
static CompletableFuture<HttpCall.Response> head(WebRtc rtc, URI endpoint, String authorization,
Duration timeout) {
HttpCall request;

try {
request = new HttpCall(rtc.httpClient(authorization != null), endpoint, "HEAD", authorization, timeout)
.followRedirects();
}
catch (RejectedExecutionException e) {
return CompletableFuture.failedFuture(new WebRtcException("The runtime is closed", e));
}

CompletableFuture<HttpCall.Response> response = request.send(null, null, 0, head -> { })
.handle((value, error) -> {
if (error != null) {
throw new WebRtcException("Asking " + endpoint + " with HEAD failed: " + error.getMessage(),
error);
}

return value;
});

try {
// The request's own timeout bounds the head of the answer; this ends
// the body of an error that does not come.
ScheduledFuture<?> deadline = rtc.timer.schedule(request::abort, Timeouts.toMillis(timeout),
TimeUnit.MILLISECONDS);
response.whenComplete((value, error) -> deadline.cancel(false));
}
catch (RejectedExecutionException e) {
// The runtime is closing, and the request's own timeout bounds it.
}

return response;
}

/**
* @return the failure reported, or null if there was no resource.
*/
Expand Down Expand Up @@ -709,6 +788,45 @@ static void requireContentType(HttpCall.Response response, String expected) {
}
}

/**
* Reads the protocol extensions an endpoint names in Link header fields
* (RFC 9725, 4.9): the links with a relation type that starts with the
* prefix of the protocol. Links of other relation types, which a client
* has to ignore, are left out.
*
* @param fields the values of the Link header fields.
* @param base the URL that answered, which relative targets resolve
* against.
* @param prefix what the relation types of extensions start with, case
* aside.
*
* @return the target of each extension by its relation type, in order;
* of one named twice, the first. A target that is no URL is left out.
*/
static Map<String, URI> extensions(List<String> fields, URI base, String prefix) {
Map<String, URI> extensions = new LinkedHashMap<>();

HttpIce.forEachLink(fields, (target, parameters) -> {
URI resolved;

try {
resolved = base.resolve(target);
}
catch (IllegalArgumentException e) {
return;
}

for (String relation : HttpIce.relations(parameters)) {
if (relation.length() > prefix.length()
&& relation.regionMatches(true, 0, prefix, 0, prefix.length())) {
extensions.putIfAbsent(relation, resolved);
}
}
});

return Collections.unmodifiableMap(extensions);
}

/**
* @return the value of an Authorization header with a bearer token (RFC
* 6750), as WHIP and WHEP ask clients to support.
Expand Down
Loading
Loading