From 25ccb057c971ddcda9ff5b7bfbaa034d05125da4 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 28 Oct 2026 20:23:00 +0100 Subject: [PATCH 1/2] fix: restart ICE after WHEP counter-offers Attach counter-offer sessions to ICE management and preserve the answerer role and rejected media during restarts. Keep the existing session when a restart is refused and document the supported behavior. --- docs/guide/client-api.md | 2 +- .../dev/onvoid/webrtc/client/HttpIce.java | 2 +- .../dev/onvoid/webrtc/client/HttpSession.java | 9 ++- .../dev/onvoid/webrtc/client/PeerImpl.java | 37 ++++++++- .../webrtc/client/HttpSessionTests.java | 75 +++++++++++++++++++ .../webrtc/client/TestHttpEndpoint.java | 2 +- 6 files changed, 117 insertions(+), 10 deletions(-) diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 526a2b115..8c0609b2e 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -602,7 +602,7 @@ The offer goes to the endpoint at once, before any candidate is gathered, and th Only once the endpoint answered does the peer gather its candidates, with the STUN and TURN servers the endpoint names in `Link` headers with `rel="ice-server"`, unless `iceServer(...)` names servers of its own, which take precedence. The candidates follow the offer by `PATCH` to the session, as `application/trickle-ice-sdpfrag`, a few at a time and with the session's `ETag` as `If-Match`, as RFC 9725 describes. An endpoint that takes no such `PATCH`, with status 405, 415, 422 or 501, gets no more; it finds the peer all the same, from the checks the peer sends to its candidates. -When the connection fails, or stays disconnected for two seconds, the session restarts ICE: the peer gathers new candidates, and only the new ICE username fragment and password go to the session, by `PATCH` with `If-Match: *`, while the media go on as negotiated. The session's answer, with status 200, brings its own ICE information and a new `ETag`. Three restarts in a row that do not bring the connection back, or an endpoint that takes no restarts, end the attempts, which the error handler hears of. `session.restartIce()` restarts ICE at once, say after the network changed; a restart that fails leaves the ICE session before as it was. A session that answered a WHEP counter-offer takes no restarts. +When the connection fails, or stays disconnected for two seconds, the session restarts ICE: the peer gathers new candidates, and only the new ICE username fragment and password go to the session, by `PATCH` with `If-Match: *`, while the media go on as negotiated. The session's answer, with status 200, brings its own ICE information and a new `ETag`. Three restarts in a row that do not bring the connection back, or an endpoint that takes no restarts, end the attempts, which the error handler hears of. `session.restartIce()` restarts ICE at once, say after the network changed; a restart that fails leaves the ICE session before as it was. Restarts also work after a WHEP counter-offer; the player keeps its answerer role and updates only the ICE information. The timeout bounds the requests as a whole, not each read, so a server that sends its answer a byte at a time cannot stretch it. A request still out when the session times out or is cancelled is cut off at once; one still waiting for the head of its answer only from Java 16 on, and before that at its timeout. Once the server has named the session, in the head of its answer, it is deleted all the same; a session the server created for an answer that had not come yet is left for the server to time out. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java index 1731788f5..f1f605cc6 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -170,7 +170,7 @@ CompletableFuture restart() { } if (session == null) { return CompletableFuture.failedFuture(new WebRtcException("ICE cannot restart: the endpoint named " - + "no session, or answered with an offer of its own")); + + "no session")); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java index 21533acd2..518e83709 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -166,8 +166,8 @@ public CompletableFuture closeAsync() { * * @return a future that completes once the new ICE information of both * sides is applied, or fails, among others when the session takes no ICE - * restarts or answered the offer with one of its own. The ICE session - * before then goes on. + * restarts. Sessions established with a WHEP counter-offer are supported + * as well. If the restart is refused, the previous ICE session goes on. */ public CompletableFuture restartIce() { CompletableFuture restarted = ice != null @@ -307,7 +307,7 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e Duration left = timeout.minusNanos(System.nanoTime() - started); return answerCounterOffer(rtc, client, peer, reply, bearerToken, - left.isNegative() || left.isZero() ? Duration.ofNanos(1) : left, resource, + left.isNegative() || left.isZero() ? Duration.ofNanos(1) : left, resource, ice, request, finished); })) .thenCompose(applied -> peer.whenConnected()) @@ -381,7 +381,7 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str * @param timeout what is left of the session's timeout. */ private static CompletableFuture answerCounterOffer(WebRtc rtc, HttpClient client, PeerImpl peer, - Reply reply, String bearerToken, Duration timeout, AtomicReference resource, + Reply reply, String bearerToken, Duration timeout, AtomicReference resource, HttpIce ice, AtomicReference request, AtomicBoolean finished) { return peer.answerInstead(new RTCSessionDescription(RTCSdpType.OFFER, reply.sdp), Gathering.COMPLETE) .thenCompose(answer -> { @@ -415,6 +415,7 @@ private static CompletableFuture answerCounterOffer(WebRtc rtc, HttpClient + response.body); } + ice.attach(reply.session, response.header("ETag"), answer.sdp); return null; }); }); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index 4c7d8819f..477398cd6 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -500,7 +500,9 @@ void onLocalCandidates(Consumer candidates, Runnable gathered) /** * Restarts ICE as WHIP and WHEP do, without a renegotiation: only the ICE * information of a new offer goes to the remote peer, and the remote - * answer applied before stays, with the ICE information that comes back. + * description keeps its offer/answer role, with the ICE information that + * comes back. After a server counter-offer, the new local credentials are + * applied in an answer to the updated remote offer. * An exchange that fails takes the new offer back, and the ICE session * before goes on. * @@ -515,13 +517,42 @@ CompletableFuture restartIce( RTCSessionDescription remote = connection.getRemoteDescription(); if (connection.getSignalingState() != RTCSignalingState.STABLE || remote == null - || remote.sdpType != RTCSdpType.ANSWER) { + || (remote.sdpType != RTCSdpType.ANSWER && remote.sdpType != RTCSdpType.OFFER)) { return CompletableFuture.failedFuture(new NegotiationException("The peer " + name - + " has no answer to its own offer to restart ICE with")); + + " has no stable description to restart ICE with")); } connection.restartIce(); + if (remote.sdpType == RTCSdpType.OFFER) { + // Keep the server's offerer role (including its DTLS role and + // media sections). Create an offer only to obtain fresh local + // ICE credentials; do not apply it or change signaling roles. + return createOffer().thenCompose(offer -> onControl(exchange.apply(offer)) + .thenCompose(change -> setRemote(new RTCSessionDescription( + RTCSdpType.OFFER, change.apply(remote.sdp)))) + .thenCompose(ignored -> { + // Reapplying the server's offer can create transceivers + // for media the original answer rejected. + stopTransceivers(midsNotReceived(remote.sdp)); + return createAnswer(); + }) + .thenCompose(answer -> setLocal(new RTCSessionDescription(RTCSdpType.ANSWER, + HttpIce.Fragment.of(offer.sdp).applyTo(answer.sdp))))) + .handle((applied, error) -> { + if (error == null) { + return CompletableFuture.completedFuture(null); + } + CompletableFuture failed = CompletableFuture.failedFuture(unwrap(error)); + if (closed || connection.getSignalingState() != RTCSignalingState.HAVE_REMOTE_OFFER) { + return failed; + } + return setRemote(new RTCSessionDescription(RTCSdpType.ROLLBACK, "")) + .handle((ignored, rollbackError) -> null) + .thenCompose(ignored -> failed); + }).thenCompose(result -> result); + } + return createOffer() .thenCompose(offer -> setLocal(offer).thenApply(ignored -> offer)) .thenCompose(offer -> onControl(exchange.apply(offer))) diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java index ef9caac60..73c5f1425 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java @@ -612,6 +612,62 @@ void counterOfferAnswered() throws Exception { } } + @Test + void counterOfferRestarted() throws Exception { + try (TestHttpEndpoint endpoint = counteringEndpoint("application/sdp", new ArrayList<>(), + video, rtc.media().customAudio("audio"))) { + Whep.Session session = await(Whep.from(endpoint.uri()).bearerToken("secret") + .receive(MediaKind.VIDEO).play(rtc)); + String before = await(session.peer().withNative(c -> c.getLocalDescription().sdp)); + await(session.restartIce()); + String after = await(session.peer().withNative(c -> c.getLocalDescription().sdp)); + assertNotEquals(HttpIce.Fragment.of(before).ufrag, HttpIce.Fragment.of(after).ufrag); + assertTrue(after.contains("\nm=audio 0 "), after); + assertTrue(after.contains("a=recvonly"), after); + assertFalse(after.contains("a=sendrecv"), after); + assertEquals(RTCSdpType.OFFER, await(session.peer().withNative(c -> c.getRemoteDescription().sdpType))); + TestHttpEndpoint.Request restart = endpoint.awaitRequest(r -> "*".equals(r.ifMatch), + "ICE restart", TIMEOUT_SECONDS); + assertEquals("Bearer secret", restart.authorization); + assertEquals(HttpIce.FRAGMENT_TYPE, restart.contentType); + assertEquals(HttpIce.Fragment.parse(restart.body).ufrag, HttpIce.Fragment.of(after).ufrag); + endpoint.awaitRequest(r -> "\"restart-1\"".equals(r.ifMatch), "restart candidates", TIMEOUT_SECONDS); + CompletableFuture width = new CompletableFuture<>(); + session.peer().onTrack(track -> track.asVideo().onFrame(frame -> width.complete(frame.buffer.getWidth()))); + assertEquals(160, (int) await(width)); + // A second restart exercises the descriptions left by the first. + await(session.restartIce()); + await(session.closeAsync()); + } + } + + @Test + void counterOfferRestartsAutomatically() throws Exception { + try (TestHttpEndpoint endpoint = counteringEndpoint("application/sdp", new ArrayList<>())) { + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + session.ice().stateChanged(PeerState.FAILED); + endpoint.awaitRequest(r -> "\"restart-1\"".equals(r.ifMatch), "restart candidates", TIMEOUT_SECONDS); + await(session.closeAsync()); + } + } + + @Test + void counterOfferRestartRefused() throws Exception { + try (TestHttpEndpoint endpoint = counteringEndpoint("application/sdp", new ArrayList<>())) { + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + String before = await(session.peer().withNative(c -> c.getLocalDescription().sdp)); + endpoint.iceRestartStatus = 405; + assertThrows(ExecutionException.class, () -> await(session.restartIce())); + assertEquals(before, await(session.peer().withNative(c -> c.getLocalDescription().sdp))); + CompletableFuture width = new CompletableFuture<>(); + session.peer().onTrack(track -> track.asVideo().onFrame(frame -> width.complete(frame.buffer.getWidth()))); + assertEquals(160, (int) await(width)); + endpoint.iceRestartStatus = 200; + await(session.restartIce()); + await(session.closeAsync()); + } + } + @Test void counterOfferMediaRejected() throws Exception { // The endpoint offers audio and video; the player wants only video, and @@ -1149,6 +1205,25 @@ private TestHttpEndpoint counteringEndpoint(String contentType, List ans } }); + endpoint.iceRestarts = fragment -> { + try { + String previous = await(server[0].withNative(c -> c.getRemoteDescription().sdp)); + await(server[0].withNative(connection -> { + connection.restartIce(); + return null; + })); + String offer = await(server[0].negotiator().createOffer(Gathering.COMPLETE)).sdp; + await(server[0].negotiator().applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, + HttpIce.Fragment.parse(fragment).applyTo(previous)))); + StringBuilder own = new StringBuilder(HttpIce.Fragment.of(offer).text); + HttpIce.Fragment.parse(offer).candidates.forEach(candidate -> own.append(candidate).append("\r\n")); + return own.append("a=end-of-candidates\r\n").toString(); + } + catch (Exception e) { + throw new IllegalStateException(e); + } + }; + return endpoint; } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java index 39e0433d3..32d3ffacd 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java @@ -538,7 +538,7 @@ else if (name.equals("content-type")) { Consumer answered = counterAnswered; int patched = patchStatus; - if (answered != null && patched / 100 == 2) { + if (answered != null && patched / 100 == 2 && "application/sdp".equals(contentType)) { answered.accept(new String(body, StandardCharsets.UTF_8)); } From 2532ed27bc5032e2c6a2f09a828a6904de46c16e Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Wed, 28 Oct 2026 20:32:18 +0100 Subject: [PATCH 2/2] fix: harden WHIP and WHEP ICE and session handling Replace remote candidates on every ICE restart and report current-generation PATCH failures while ignoring obsolete responses. Add initial complete gathering and authenticated TURN configuration without changing the meaning of existing URL lists. Validate session locations and SDP response media types, and document the new options and compatibility requirements. --- docs/guide/client-api.md | 24 ++- .../onvoid/webrtc/examples/WhepExample.java | 2 + .../dev/onvoid/webrtc/client/HttpIce.java | 29 ++-- .../dev/onvoid/webrtc/client/HttpSession.java | 44 +++-- .../dev/onvoid/webrtc/client/PeerImpl.java | 2 +- .../java/dev/onvoid/webrtc/client/Whep.java | 54 ++++-- .../java/dev/onvoid/webrtc/client/Whip.java | 51 ++++-- .../onvoid/webrtc/client/HttpIceTests.java | 17 +- .../webrtc/client/HttpSessionTests.java | 163 ++++++++++++++++++ .../webrtc/client/TestHttpEndpoint.java | 33 +++- 10 files changed, 359 insertions(+), 60 deletions(-) diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 8c0609b2e..de676fc4f 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -598,11 +598,25 @@ Whep.Session viewer = Whep.from(URI.create("https://example.com/live/whep")) viewer.peer().onTrack(track -> System.out.println("Receiving " + track.kind())); ``` -The offer goes to the endpoint at once, before any candidate is gathered, and the future completes once the peer is connected. As RFC 9725 asks, the peer bundles all media on one transport (`max-bundle`), and the descriptions it sends mark each m-line `rtcp-mux-only`. If the endpoint refuses the offer, or the peer does not connect within the timeout (15 seconds by default), the future fails, and the session is deleted on the server again. An endpoint that is busy, with status 503, or a WHEP endpoint whose stream has yet to start, with status 409, gets the offer again after the wait its `Retry-After` names, at least a second, as long as that fits within the timeout; without `Retry-After` the session fails at once. A WHEP endpoint may also reject the offer and counter it with one of its own, with status 406: `Whep` then takes its offer back, answers the endpoint's, receiving only, and sends the answer by `PATCH` to the session the endpoint named, before the counter-offer's `valid-until`, 30 seconds by default. The answer rejects the audio or video of the counter-offer that `receive(...)` leaves out, and the session fails if the counter-offer holds none of what it asks for. Data channels of a counter-offer are accepted. Cancelling the future, say once `get` gave up waiting, ends the session the same way. `onTrack` hands over tracks that already arrived, so a handler added once the future completed misses none. +By default, the offer goes to the endpoint at once, before any candidate is gathered, and the future completes once the peer is connected. As RFC 9725 asks, the peer bundles all media on one transport (`max-bundle`), and the descriptions it sends mark each m-line `rtcp-mux-only`. If the endpoint refuses the offer, or the peer does not connect within the timeout (15 seconds by default), the future fails, and the session is deleted on the server again. An endpoint that is busy, with status 503, or a WHEP endpoint whose stream has yet to start, with status 409, gets the offer again after the wait its `Retry-After` names, at least a second, as long as that fits within the timeout; without `Retry-After` the session fails at once. A WHEP endpoint may also reject the offer and counter it with one of its own, with status 406: `Whep` then takes its offer back, answers the endpoint's, receiving only, and sends the answer by `PATCH` to the session the endpoint named, before the counter-offer's `valid-until`, 30 seconds by default. The answer rejects the audio or video of the counter-offer that `receive(...)` leaves out, and the session fails if the counter-offer holds none of what it asks for. Data channels of a counter-offer are accepted. Cancelling the future, say once `get` gave up waiting, ends the session the same way. `onTrack` hands over tracks that already arrived, so a handler added once the future completed misses none. -Only once the endpoint answered does the peer gather its candidates, with the STUN and TURN servers the endpoint names in `Link` headers with `rel="ice-server"`, unless `iceServer(...)` names servers of its own, which take precedence. The candidates follow the offer by `PATCH` to the session, as `application/trickle-ice-sdpfrag`, a few at a time and with the session's `ETag` as `If-Match`, as RFC 9725 describes. An endpoint that takes no such `PATCH`, with status 405, 415, 422 or 501, gets no more; it finds the peer all the same, from the checks the peer sends to its candidates. +With the default `Gathering.TRICKLE`, only once the endpoint answered does the peer gather its candidates, with the STUN and TURN servers the endpoint names in `Link` headers with `rel="ice-server"`, unless `iceServer(...)` or `turnServer(...)` names servers of its own, which take precedence. The candidates follow the offer by `PATCH` to the session, as `application/trickle-ice-sdpfrag`, a few at a time and with the session's `ETag` as `If-Match`, as RFC 9725 describes. An endpoint that takes no such `PATCH`, with status 405, 415, 422 or 501, gets no more; it may still learn peer-reflexive candidates from incoming connectivity checks, but that does not cover every network topology. A 412 or 428 for the current ICE generation reaches the error handler and stops candidate PATCHes; responses to a generation replaced by a restart are ignored. -When the connection fails, or stays disconnected for two seconds, the session restarts ICE: the peer gathers new candidates, and only the new ICE username fragment and password go to the session, by `PATCH` with `If-Match: *`, while the media go on as negotiated. The session's answer, with status 200, brings its own ICE information and a new `ETag`. Three restarts in a row that do not bring the connection back, or an endpoint that takes no restarts, end the attempts, which the error handler hears of. `session.restartIce()` restarts ICE at once, say after the network changed; a restart that fails leaves the ICE session before as it was. Restarts also work after a WHEP counter-offer; the player keeps its answerer role and updates only the ICE information. +For an endpoint without Trickle ICE, use `.gathering(Gathering.COMPLETE)` to include gathered candidates in the initial POST. It waits at most three seconds for gathering, within the overall session timeout, then sends the candidates available so far; any later candidates may still follow by PATCH. Configure STUN/TURN servers locally in this mode, since the endpoint's Link headers arrive after gathering. For example: + +```java +Whep.Session viewer = Whep.from(endpoint) + .turnServer("turn:turn.example.com:3478", turnUsername, turnPassword) + .gathering(Gathering.COMPLETE) + .play(rtc) + .get(15, TimeUnit.SECONDS); +``` + +Both builders support these methods. `turnServer` is separate from `iceServer(String...)`, so passing three URLs to `iceServer` still means three URLs. The gathering setting controls the initial POST only; ICE restarts continue to use PATCH and trickled candidates. + +A normal SDP answer must have status 201, a nonempty session `Location`, and Content-Type `application/sdp` (parameters are allowed). Invalid responses fail the session; a resource already named by the server is deleted even when its SDP response cannot be used. + +When the connection fails, or stays disconnected for two seconds, the session restarts ICE: the peer gathers new candidates, and only the new ICE username fragment and password go to the session, by `PATCH` with `If-Match: *`, while the media go on as negotiated. The session's answer, with status 200 and Content-Type `application/trickle-ice-sdpfrag`, brings its own ICE information and a new `ETag`. Its candidate set replaces the old one completely, including when it is empty. Three restarts in a row that do not bring the connection back, or an endpoint that takes no restarts, end the attempts, which the error handler hears of. `session.restartIce()` restarts ICE at once, say after the network changed; a restart that fails leaves the ICE session before as it was. Restarts also work after a WHEP counter-offer; the player keeps its answerer role and updates only the ICE information. The timeout bounds the requests as a whole, not each read, so a server that sends its answer a byte at a time cannot stretch it. A request still out when the session times out or is cancelled is cut off at once; one still waiting for the head of its answer only from Java 16 on, and before that at its timeout. Once the server has named the session, in the head of its answer, it is deleted all the same; a session the server created for an answer that had not come yet is left for the server to time out. @@ -617,7 +631,9 @@ Requests go through Java's `HttpClient`, with the default `SSLContext` and the H | Builder method | What it sets | |---|---| | `bearerToken(String)` | The token sent as `Authorization: Bearer`; for many services, the stream key. | -| `iceServer(String...)` | A STUN or TURN server, which replaces those the endpoint names in its answer. | +| `iceServer(String...)` | A STUN or TURN server without credentials, overriding endpoint-provided servers. | +| `turnServer(String, String, String)` | A TURN URL, username and password, overriding endpoint-provided servers. | +| `gathering(Gathering)` | When the initial offer is sent: `TRICKLE` by default, or `COMPLETE` to gather first. | | `track(LocalTrack)` | A track to publish, WHIP only. The tracks share one stream, which holds one audio and one video track at most. | | `receive(MediaKind...)` | What to receive, WHEP only; video and audio by default. | | `timeout(Duration)` | How long the session may take to be connected, and its deletion to be answered. | diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java index 785b8b0b7..0f1e50430 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/WhepExample.java @@ -62,6 +62,8 @@ public static void main(String[] args) throws Exception { System.out.println("Requesting the stream from " + endpoint); // The main thread may wait for the session; a handler must not. + // For endpoints without Trickle ICE, add .gathering(Gathering.COMPLETE). + // Authenticated TURN is configured with .turnServer(url, username, password). Whep.Session session = Whep.from(endpoint) .iceServer("stun:stun.l.google.com:19302") .play(rtc) diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java index f1f605cc6..3d4a8d0fa 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -278,6 +278,7 @@ private UnaryOperator answered(HttpCall request, HttpCall.Response respo + response.status + ": " + response.body); } + HttpSession.requireContentType(response, FRAGMENT_TYPE); Fragment remote = Fragment.parse(response.body); if (remote.ufrag == null || remote.pwd == null) { @@ -326,6 +327,7 @@ private void flush() { HttpCall request; String body; URI target; + Fragment generation; synchronized (this) { if (closed || !trickle || restarting || candidatesRequest != null || (pending.isEmpty() && !gathered)) { @@ -351,6 +353,7 @@ private void flush() { candidatesRequest = request; body = fragment.toString(); target = session; + generation = local; } request.send(FRAGMENT_TYPE, body.getBytes(StandardCharsets.UTF_8), 0, head -> { }) @@ -360,16 +363,15 @@ private void flush() { synchronized (this) { candidatesRequest = null; - if (error == null && UNSUPPORTED.contains(response.status)) { + if (local == generation && error == null && UNSUPPORTED.contains(response.status)) { // The session finds the peer from its checks. trickle = false; } - // A precondition that fails belongs to an ICE session - // a restart replaced. - report = !closed && (error != null || (response.status / 100 != 2 - && !UNSUPPORTED.contains(response.status) && response.status != 412 - && response.status != 428)); + // Only replies to a replaced ICE generation are obsolete. + // A 412 or 428 for the current one is a real failure. + report = !closed && local == generation && (error != null + || (response.status / 100 != 2 && !UNSUPPORTED.contains(response.status))); if (report) { trickle = false; @@ -707,17 +709,24 @@ boolean owns(String candidate) { /** * Puts the ICE information of this fragment, which a session sent, - * into the remote answer applied before. Its candidates replace those - * of the answer; with none, the answer keeps its own, since a session - * that names none has kept them. + * into the remote description. The new candidate set replaces the old + * one even when empty (RFC 9725, 4.3.3). */ String applyTo(String answer) { + return applyTo(answer, true); + } + + /** Changes local credentials without replacing locally gathered candidates. */ + String applyCredentialsTo(String answer) { + return applyTo(answer, false); + } + + private String applyTo(String answer, boolean replace) { List> sections = sections(answer); String group = first(sections.get(0), "a=group:BUNDLE"); String tag = group != null && group.trim().split("\\s+").length > 1 ? group.trim().split("\\s+")[1] : null; - boolean replace = !candidates.isEmpty(); boolean placed = false; StringBuilder sdp = new StringBuilder(); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java index 518e83709..4394b8e0c 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -194,16 +194,17 @@ public void close() { * a server that does not answer holds no connection; what it creates for * an offer it had yet to answer is left for it to time out. * + * @param gathering when the initial offer is sent. * @param protocol what WHIP or WHEP asks beyond the offer and its answer. * @param factory makes the session of the connected peer. * * @return the future handed to the application. */ static CompletableFuture start(WebRtc rtc, PeerImpl peer, URI endpoint, - String bearerToken, Duration timeout, Protocol protocol, Factory factory) { + String bearerToken, Duration timeout, Gathering gathering, Protocol protocol, Factory factory) { CompletableFuture abandoned = new CompletableFuture<>(); HttpIce ice = new HttpIce(rtc, rtc.httpClient(bearerToken != null), peer, bearerToken, timeout); - CompletableFuture session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, protocol, + CompletableFuture session = peer.toPublic(negotiate(rtc, peer, endpoint, bearerToken, timeout, gathering, protocol, ice, abandoned).thenApply(resource -> factory.create(rtc, peer, resource, bearerToken, timeout, ice)), HttpSession::close); @@ -220,7 +221,9 @@ static CompletableFuture start(WebRtc rtc, PeerImpl p * named, and the candidates it gathers go to the session by PATCH. The * answer is applied, and the future completes once the peer is connected. * An endpoint that counters the offer, as WHEP allows, gets the answer to - * its own offer instead, with all candidates. + * its own offer instead, with all candidates. With COMPLETE gathering, + * the initial offer is applied and gathered before POST; endpoint-provided + * ICE servers then arrive too late for this gathering and are ignored. * * @param ice the ICE of the session once the offer is answered. * @param abandoned completes when no one waits for the session anymore, @@ -229,7 +232,7 @@ static CompletableFuture start(WebRtc rtc, PeerImpl p * @return a future with the resource the server named, or null. */ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI endpoint, String bearerToken, - Duration timeout, Protocol protocol, HttpIce ice, CompletableFuture abandoned) { + Duration timeout, Gathering gathering, Protocol protocol, HttpIce ice, CompletableFuture abandoned) { CompletableFuture result = new CompletableFuture<>(); long started = System.nanoTime(); // The resource the server created. Whoever takes it out owns it: the @@ -274,7 +277,9 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e fail.accept(new CancellationException("The session with " + endpoint + " was abandoned")); }); - peer.offer() + CompletableFuture initial = gathering == Gathering.COMPLETE + ? peer.negotiator().createOffer(Gathering.COMPLETE) : peer.offer(); + initial .thenCompose(offer -> post(offerRequest, endpoint, withRtcpMuxOnly(offer.sdp), protocol, resource) .whenComplete((reply, error) -> { if (finished.get()) { @@ -284,7 +289,9 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e discard(rtc, resource.getAndSet(null), bearerToken, timeout); } }) - .thenCompose(reply -> peer.useIceServers(reply.iceServers).handle((used, error) -> { + .thenCompose(reply -> (gathering == Gathering.COMPLETE + ? CompletableFuture.completedFuture(null) + : peer.useIceServers(reply.iceServers)).handle((used, error) -> { if (error != null) { // Gathered without them, as if the endpoint had // named none. @@ -295,11 +302,13 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e })) .thenCompose(reply -> { if (!reply.counterOffer) { - // Before the offer is applied, which starts the - // gathering of the candidates that go there. + // Trickle offers are not applied yet; COMPLETE offers + // already carry the gathered candidates. ice.attach(resource.get(), reply.etag, offer.sdp); - return peer.applyLocal(offer).thenCompose(applied -> peer.negotiator() + return (gathering == Gathering.COMPLETE + ? CompletableFuture.completedFuture(null) : peer.applyLocal(offer)) + .thenCompose(applied -> peer.negotiator() .applyAnswer(new RTCSessionDescription(RTCSdpType.ANSWER, reply.sdp))); } @@ -346,7 +355,11 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str throw new WebRtcException("Sending the offer to " + endpoint + " failed: " + error.getMessage(), error); } - if (response.status == 201 || response.status == 200) { + if (response.status == 201) { + if (resource.get() == null) { + throw new WebRtcException("The endpoint " + endpoint + " answered without a session Location"); + } + requireContentType(response, "application/sdp"); return new Reply(response.body, false, null, 0, response); } if (protocol.counterOffers && isCounterOffer(response)) { @@ -608,7 +621,7 @@ private static WebRtcException leftOnServer(WebRtc rtc, URI resource) { * delete it, so an https endpoint cannot name a plain http resource. */ static URI resourceOf(URI endpoint, String location) { - if (location == null) { + if (location == null || location.trim().isEmpty()) { return null; } @@ -686,6 +699,15 @@ static String withRtcpMuxOnly(String sdp) { return marked.toString(); } + /** Rejects success bodies that are not of the negotiated media type. */ + static void requireContentType(HttpCall.Response response, String expected) { + String type = response.header("Content-Type"); + if (type == null || !type.split(";", 2)[0].trim().equalsIgnoreCase(expected)) { + throw new WebRtcException("The session " + response.uri + " answered with Content-Type " + + type + "; expected " + expected); + } + } + static URI checkEndpoint(URI endpoint) { requireNonNull(endpoint, "endpoint"); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java index 477398cd6..dedc3bd09 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java @@ -538,7 +538,7 @@ CompletableFuture restartIce( return createAnswer(); }) .thenCompose(answer -> setLocal(new RTCSessionDescription(RTCSdpType.ANSWER, - HttpIce.Fragment.of(offer.sdp).applyTo(answer.sdp))))) + HttpIce.Fragment.of(offer.sdp).applyCredentialsTo(answer.sdp))))) .handle((applied, error) -> { if (error == null) { return CompletableFuture.completedFuture(null); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java index 2add060a5..3b5604ce9 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whep.java @@ -20,9 +20,7 @@ import java.net.URI; import java.time.Duration; -import java.util.ArrayList; import java.util.EnumSet; -import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -40,7 +38,7 @@ * ... * session.close(); * } - * The offer goes to the endpoint at once, and the candidates follow it by + * By default the offer goes to the endpoint at once, and candidates follow by * PATCH, gathered with the STUN and TURN servers the endpoint names. The * session's future completes once the peer is connected. The session * restarts ICE when the connection breaks, or by {@link Session#restartIce()}. @@ -91,17 +89,21 @@ public static final class Builder { private final URI endpoint; - private final List iceServers = new ArrayList<>(); + private final PeerOptions.Builder options = PeerOptions.builder() + .negotiation(Negotiation.MANUAL).configure(HttpSession::requireBundle); private final Set receive = EnumSet.of(MediaKind.VIDEO, MediaKind.AUDIO); private String bearerToken; + private Gathering gathering = Gathering.TRICKLE; + private Duration timeout = Duration.ofSeconds(15); private Builder(URI endpoint) { this.endpoint = endpoint; + options.name("whep-" + endpoint.getHost()); } /** @@ -122,7 +124,7 @@ public Builder bearerToken(String token) { * @return this builder. */ public Builder iceServer(String... urls) { - iceServers.add(urls.clone()); + options.iceServer(urls); return this; } @@ -144,6 +146,36 @@ public Builder receive(MediaKind... kinds) { return this; } + /** + * Configures an authenticated TURN server, overriding endpoint-provided + * servers. Uses a distinct name so three URL arguments to iceServer + * keep their original meaning. + * + * @param url the TURN server URL. + * @param username the TURN username. + * @param password the TURN password. + * @return this builder. + */ + public Builder turnServer(String url, String username, String password) { + options.iceServer(url, username, password); + return this; + } + + /** + * Selects when the initial offer is sent. COMPLETE gathers candidates + * before POST, up to the peer's gathering timeout (three seconds). + * Later candidates may still follow by PATCH. Configure STUN/TURN + * servers locally in that mode: links in the answer arrive too late + * for the initial gathering. Subsequent ICE restarts still use PATCH. + * + * @param gathering TRICKLE (the default) or COMPLETE. + * @return this builder. + */ + public Builder gathering(Gathering gathering) { + this.gathering = requireNonNull(gathering, "gathering"); + return this; + } + /** * @param timeout how long the session may take to be connected, and its * deletion to be answered; 15 seconds by default. @@ -169,15 +201,7 @@ public Builder timeout(Duration timeout) { public CompletableFuture play(WebRtc rtc) { requireNonNull(rtc, "rtc"); - PeerOptions.Builder options = PeerOptions.builder() - .name("whep-" + endpoint.getHost()) - .negotiation(Negotiation.MANUAL) - .receive(receive.toArray(new MediaKind[0])) - .configure(HttpSession::requireBundle); - - for (String[] urls : iceServers) { - options.iceServer(urls); - } + options.receive(receive.toArray(new MediaKind[0])); // The builder may change while the session starts; the session keeps // what it started with, so that its DELETE is authorized like its POST. @@ -186,7 +210,7 @@ public CompletableFuture play(WebRtc rtc) { PeerImpl peer = (PeerImpl) rtc.createPeer(options.build()); try { - return HttpSession.start(rtc, peer, endpoint, token, limit, PROTOCOL, Session::new); + return HttpSession.start(rtc, peer, endpoint, token, limit, gathering, PROTOCOL, Session::new); } catch (RuntimeException | Error e) { // Until the session has it, no one else would close the peer. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java index 0e2e8230e..b97ac5cba 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/Whip.java @@ -42,7 +42,7 @@ * ... * session.close(); * } - * The offer goes to the endpoint at once, and the candidates follow it by + * By default the offer goes to the endpoint at once, and candidates follow by * PATCH, gathered with the STUN and TURN servers the endpoint names. The * session's future completes once the peer is connected. The session * restarts ICE when the connection breaks, or by {@link Session#restartIce()}. @@ -91,17 +91,21 @@ public static final class Builder { private final URI endpoint; - private final List iceServers = new ArrayList<>(); + private final PeerOptions.Builder options = PeerOptions.builder() + .negotiation(Negotiation.MANUAL).configure(HttpSession::requireBundle); private final List tracks = new ArrayList<>(); private String bearerToken; + private Gathering gathering = Gathering.TRICKLE; + private Duration timeout = Duration.ofSeconds(15); private Builder(URI endpoint) { this.endpoint = endpoint; + options.name("whip-" + endpoint.getHost()); } /** @@ -135,7 +139,37 @@ public Builder bearerToken(String token) { * @return this builder. */ public Builder iceServer(String... urls) { - iceServers.add(urls.clone()); + options.iceServer(urls); + return this; + } + + /** + * Configures an authenticated TURN server, overriding endpoint-provided + * servers. Uses a distinct name so three URL arguments to iceServer + * keep their original meaning. + * + * @param url the TURN server URL. + * @param username the TURN username. + * @param password the TURN password. + * @return this builder. + */ + public Builder turnServer(String url, String username, String password) { + options.iceServer(url, username, password); + return this; + } + + /** + * Selects when the initial offer is sent. COMPLETE gathers candidates + * before POST, up to the peer's gathering timeout (three seconds). + * Later candidates may still follow by PATCH. Configure STUN/TURN + * servers locally in that mode: links in the answer arrive too late + * for the initial gathering. Subsequent ICE restarts still use PATCH. + * + * @param gathering TRICKLE (the default) or COMPLETE. + * @return this builder. + */ + public Builder gathering(Gathering gathering) { + this.gathering = requireNonNull(gathering, "gathering"); return this; } @@ -187,15 +221,6 @@ public CompletableFuture publish(WebRtc rtc) { } } - PeerOptions.Builder options = PeerOptions.builder() - .name("whip-" + endpoint.getHost()) - .negotiation(Negotiation.MANUAL) - .configure(HttpSession::requireBundle); - - for (String[] urls : iceServers) { - options.iceServer(urls); - } - // The builder may change while the session starts; the session keeps // what it started with, so that its DELETE is authorized like its POST. String token = bearerToken; @@ -207,7 +232,7 @@ public CompletableFuture publish(WebRtc rtc) { peer.addTrack(track); } - return HttpSession.start(rtc, peer, endpoint, token, limit, PROTOCOL, Session::new); + return HttpSession.start(rtc, peer, endpoint, token, limit, gathering, PROTOCOL, Session::new); } catch (RuntimeException | Error e) { // Until the session has it, no one else would close the peer. diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java index 16a0b3af5..d44691960 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpIceTests.java @@ -132,11 +132,24 @@ void restartAppliedToAnswer() { } @Test - void restartWithoutCandidatesKeepsThem() { + void localCredentialsKeepCandidates() { + HttpIce.Fragment restart = HttpIce.Fragment.parse("a=ice-ufrag:cccc\r\na=ice-pwd:cccccccccccccccccccccccc\r\n"); + String answer = restart.applyCredentialsTo(ANSWER); + assertTrue(answer.contains("192.0.2.1"), answer); + assertTrue(answer.contains("a=end-of-candidates"), answer); + assertTrue(answer.contains("a=ice-ufrag:cccc"), answer); + } + + @Test + void restartWithoutCandidatesClearsThem() { HttpIce.Fragment restart = HttpIce.Fragment.parse("a=ice-ufrag:cccc\r\na=ice-pwd:cccccccccccccccccccccccc\r\n"); String answer = restart.applyTo(ANSWER); - assertTrue(answer.contains("192.0.2.1"), answer); + assertFalse(answer.contains("192.0.2.1"), answer); + assertFalse(answer.contains("a=end-of-candidates"), answer); assertTrue(answer.contains("a=ice-ufrag:cccc"), answer); + String ended = HttpIce.Fragment.parse(restart.text + "a=end-of-candidates\r\n").applyTo(ANSWER); + assertFalse(ended.contains("a=candidate:"), ended); + assertTrue(ended.contains("a=end-of-candidates"), ended); } } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java index 73c5f1425..0be9cdfda 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java @@ -135,6 +135,169 @@ void whipPublishes() throws Exception { } } + @Test + void completeOffersNeedNoPatch() throws Exception { + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.patchStatus = 405; + Whep.Session session = await(Whep.from(endpoint.uri()).gathering(Gathering.COMPLETE).play(rtc)); + assertTrue(endpoint.request("POST /live/endpoint").body.contains("a=candidate:")); + CompletableFuture width = new CompletableFuture<>(); + session.peer().onTrack(track -> track.asVideo().onFrame(frame -> width.complete(frame.buffer.getWidth()))); + assertEquals(160, (int) await(width)); + await(session.closeAsync()); + assertEquals(0, endpoint.count("PATCH /live/session/1")); + } + try (TestHttpEndpoint endpoint = receivingEndpoint()) { + endpoint.patchStatus = 405; + Whip.Session session = await(Whip.to(endpoint.uri()).track(video) + .gathering(Gathering.COMPLETE).publish(rtc)); + assertTrue(endpoint.request("POST /live/endpoint").body.contains("a=candidate:")); + await(session.closeAsync()); + assertEquals(0, endpoint.count("PATCH /live/session/1")); + } + } + + @Test + void completeOfferCanBeCountered() throws Exception { + try (TestHttpEndpoint endpoint = counteringEndpoint("application/sdp", new ArrayList<>())) { + Whep.Session session = await(Whep.from(endpoint.uri()).gathering(Gathering.COMPLETE).play(rtc)); + assertTrue(endpoint.request("POST /live/endpoint").body.contains("a=candidate:")); + await(session.restartIce()); + await(session.closeAsync()); + } + } + + @Test + void turnCredentialsConfigured() throws Exception { + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerHeaders = "Link: ; rel=\"ice-server\"\r\n"; + Whep.Session session = await(Whep.from(endpoint.uri()) + .turnServer("turn:127.0.0.1:3478", "user", "password").play(rtc)); + RTCIceServer server = await(session.peer().withNative(c -> c.getConfiguration().iceServers.get(0))); + assertEquals(Arrays.asList("turn:127.0.0.1:3478"), server.urls); + assertEquals("user", server.username); + assertEquals("password", server.password); + await(session.closeAsync()); + } + try (TestHttpEndpoint endpoint = receivingEndpoint()) { + Whip.Session session = await(Whip.to(endpoint.uri()).track(video) + .turnServer("turn:127.0.0.1:3478", "user", "password") + .iceServer("stun:127.0.0.2:3478", "stun:127.0.0.3:3478", "stun:127.0.0.4:3478") + .publish(rtc)); + List servers = await(session.peer().withNative(c -> c.getConfiguration().iceServers)); + assertEquals("password", servers.get(0).password); + assertEquals(3, servers.get(1).urls.size()); + assertNull(servers.get(1).username); + await(session.closeAsync()); + } + } + + @Test + void malformedSuccessDeleted() throws Exception { + // A known resource must still be deleted when its answer is unusable. + for (String type : Arrays.asList("text/plain", null)) { + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerContentType = type; + ExecutionException failed = assertThrows(ExecutionException.class, + () -> await(Whep.from(endpoint.uri()).play(rtc))); + assertTrue(failed.getCause().getMessage().contains("Content-Type")); + endpoint.awaitRequest("DELETE /live/session/1", TIMEOUT_SECONDS); + } + } + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerStatus = 200; + ExecutionException failed = assertThrows(ExecutionException.class, + () -> await(Whep.from(endpoint.uri()).play(rtc))); + assertTrue(failed.getCause().getMessage().contains("status 200")); + endpoint.awaitRequest("DELETE /live/session/1", TIMEOUT_SECONDS); + } + } + + @Test + void contentTypeParametersAccepted() throws Exception { + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerContentType = "Application/SDP; charset=utf-8"; + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + await(session.closeAsync()); + } + } + + @Test + void restartRequiresFragmentType() throws Exception { + try (TestHttpEndpoint endpoint = restartingEndpoint(new ArrayList<>())) { + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + String previous = await(session.peer().withNative(c -> c.getLocalDescription().sdp)); + endpoint.iceRestartContentType = "text/plain"; + ExecutionException failed = assertThrows(ExecutionException.class, () -> await(session.restartIce())); + assertTrue(failed.getCause().getMessage().contains("Content-Type")); + assertEquals(previous, await(session.peer().withNative(c -> c.getLocalDescription().sdp))); + await(session.closeAsync()); + } + } + + @Test + void sessionLocationRequired() throws Exception { + for (String location : Arrays.asList(null, "")) { + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.location = location; + ExecutionException failed = assertThrows(ExecutionException.class, + () -> await(Whep.from(endpoint.uri()).play(rtc))); + assertTrue(failed.getCause().getMessage().contains("Location")); + assertEquals(0, endpoint.count("DELETE /live/session/1")); + } + } + } + + @Test + void currentPreconditionFailureReported() throws Exception { + for (int status : new int[] { 412, 428 }) { + CompletableFuture error = new CompletableFuture<>(); + WebRtc client = clientRuntime(builder -> builder.errorHandler(error::complete)); + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.patchStatus = status; + Whep.Session session = await(Whep.from(endpoint.uri()).play(client)); + assertTrue(await(error).getMessage().contains("status " + status)); + await(session.closeAsync()); + } + finally { + client.close(); + } + } + } + + @Test + void stalePreconditionFailureIgnored() throws Exception { + for (int status : new int[] { 412, 428, 405 }) { + CountDownLatch release = new CountDownLatch(1); + try (TestHttpEndpoint endpoint = restartingEndpoint(new ArrayList<>())) { + // The first candidate PATCH fails only after a restart has + // installed a new generation. Its failure must not stop new candidates. + endpoint.patchStatus = status; + endpoint.candidatePatch = request -> { + if (!"\"restart-1\"".equals(request.ifMatch)) { + try { + assertTrue(release.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + }; + Whep.Session session = await(Whep.from(endpoint.uri()).play(rtc)); + endpoint.awaitRequest("PATCH /live/session/1", TIMEOUT_SECONDS); + await(session.restartIce()); + endpoint.patchStatus = 204; + release.countDown(); + endpoint.awaitRequest(r -> "\"restart-1\"".equals(r.ifMatch), "new candidates", TIMEOUT_SECONDS); + await(session.closeAsync()); + } + finally { + release.countDown(); + } + } + } + @Test void refusedOfferLeavesNothing() throws Exception { try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> "", 403)) { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java index 32d3ffacd..d4c60fbbf 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/TestHttpEndpoint.java @@ -129,6 +129,15 @@ public String toString() { /** Header fields an answer of 201 carries beyond Location, each ended by CRLF. */ volatile String answerHeaders = ""; + /** Overrides the successful POST response for protocol validation tests. */ + volatile String answerContentType = "application/sdp"; + + volatile int answerStatus = 201; + + /** Holds a candidate PATCH response; called only for trickle fragments. */ + volatile Consumer candidatePatch; + + /** * Takes the fragment of an ICE restart, a PATCH with If-Match *, and * returns the endpoint's own, or is null for an endpoint that refuses ICE @@ -139,6 +148,8 @@ public String toString() { /** The status an ICE restart is answered with; with another than 200, the restart fails. */ volatile int iceRestartStatus = 200; + volatile String iceRestartContentType = HttpIce.FRAGMENT_TYPE; + private int restarts; /** Where POSTs are redirected to, or null. */ @@ -412,6 +423,9 @@ private void serve(Socket socket) { private void handle(Socket socket) throws IOException { InputStream in = socket.getInputStream(); String[] requestLine = readLine(in).split(" "); + if (requestLine.length < 2) { + return; // An aborted request can close before sending its head. + } String authorization = null; String ifMatch = null; String contentType = null; @@ -501,7 +515,8 @@ else if (name.equals("content-type")) { answered++; } - respond(out, "201 Created", "Location: " + location + "\r\n" + answerHeaders, answer); + respond(out, answerStatus + " Status", (location == null ? "" : "Location: " + location + "\r\n") + + answerHeaders, answer, answerContentType); return; } @@ -525,7 +540,7 @@ else if (name.equals("content-type")) { restart = ++restarts; } - String head = "HTTP/1.1 200 OK\r\nContent-Type: application/trickle-ice-sdpfrag\r\nETag: \"restart-" + String head = "HTTP/1.1 200 OK\r\nContent-Type: " + iceRestartContentType + "\r\nETag: \"restart-" + restart + "\"\r\nContent-Length: " + fragment.length + "\r\nConnection: close\r\n\r\n"; out.write(head.getBytes(StandardCharsets.US_ASCII)); @@ -537,6 +552,10 @@ else if (name.equals("content-type")) { if (requestLine[0].equals("PATCH")) { Consumer answered = counterAnswered; int patched = patchStatus; + if (HttpIce.FRAGMENT_TYPE.equals(contentType) && candidatePatch != null) { + candidatePatch.accept(new Request(requestLine[0], requestLine[1], authorization, ifMatch, + contentType, new String(body, StandardCharsets.UTF_8))); + } if (answered != null && patched / 100 == 2 && "application/sdp".equals(contentType)) { answered.accept(new String(body, StandardCharsets.UTF_8)); @@ -569,7 +588,7 @@ private void answerInPart(Socket socket, String answer) throws IOException { if (mode == Answer.CHUNKED || mode == Answer.UNTIL_CLOSE) { String body = new String(bytes, StandardCharsets.UTF_8); - String head = "HTTP/1.1 201 Created\r\nLocation: " + location + "\r\nConnection: close\r\n"; + String head = "HTTP/1.1 201 Created\r\nContent-Type: application/sdp\r\nLocation: " + location + "\r\nConnection: close\r\n"; if (mode == Answer.CHUNKED) { int half = body.length() / 2; @@ -651,8 +670,14 @@ private static void pass(CountDownLatch gate) throws IOException { } private static void respond(OutputStream out, String status, String headers, String body) throws IOException { + respond(out, status, headers, body, "application/sdp"); + } + + private static void respond(OutputStream out, String status, String headers, String body, String type) + throws IOException { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); - String head = "HTTP/1.1 " + status + "\r\nContent-Type: application/sdp\r\n" + headers + String head = "HTTP/1.1 " + status + "\r\n" + + (type == null ? "" : "Content-Type: " + type + "\r\n") + headers + "Content-Length: " + bytes.length + "\r\nConnection: close\r\n\r\n"; out.write(head.getBytes(StandardCharsets.US_ASCII));