1919import static java .util .Objects .requireNonNull ;
2020
2121import java .net .URI ;
22+ import java .net .http .HttpClient ;
2223import java .nio .charset .StandardCharsets ;
2324import java .time .Duration ;
25+ import java .time .ZonedDateTime ;
26+ import java .time .format .DateTimeFormatter ;
27+ import java .time .format .DateTimeParseException ;
28+ import java .util .Collections ;
2429import java .util .Set ;
2530import java .util .concurrent .CancellationException ;
2631import java .util .concurrent .CompletableFuture ;
3035import java .util .concurrent .atomic .AtomicBoolean ;
3136import java .util .concurrent .atomic .AtomicReference ;
3237import java .util .function .Consumer ;
38+ import java .util .regex .Matcher ;
39+ import java .util .regex .Pattern ;
3340
3441import dev .onvoid .webrtc .RTCSdpType ;
3542import dev .onvoid .webrtc .RTCSessionDescription ;
@@ -45,6 +52,16 @@ abstract class HttpSession implements AutoCloseable {
4552 /** The largest answer read; an SDP answer is a few kilobytes. */
4653 private static final int MAX_BODY = 1 << 20 ;
4754
55+ /** The status of a counter-offer, whose body is an offer to answer. */
56+ private static final Set <Integer > COUNTER_OFFER = Set .of (406 );
57+
58+ /** How long a counter-offer can be answered if it does not say. */
59+ private static final long COUNTER_OFFER_VALIDITY_MILLIS = 30_000 ;
60+
61+ /** The "valid-until" parameter of a counter-offer's Content-Type. */
62+ private static final Pattern VALID_UNTIL = Pattern .compile (";\\ s*valid-until\\ s*=\\ s*\" ?([^\" ;]+)\" ?" ,
63+ Pattern .CASE_INSENSITIVE );
64+
4865 private final Peer peer ;
4966
5067 private final URI resource ;
@@ -130,21 +147,19 @@ public void close() {
130147 * connected. A caller that stops waiting, by cancelling the future or
131148 * completing it itself, ends the negotiation, and a session made too late
132149 * for the future is closed: either way the peer is closed and what the
133- * server named is deleted. An offer still out is cut off then, so that
134- * a server that does not answer holds no thread ; what it creates for an
135- * offer it had yet to answer is left for it to time out.
150+ * server named is deleted. A request still out is cut off then, so that
151+ * a server that does not answer holds no connection ; what it creates for
152+ * an offer it had yet to answer is left for it to time out.
136153 *
137- * @param retried the statuses of an answer to the offer, together with a
138- * Retry-After header field, after which the offer is sent
139- * again, as long as the wait fits within the timeout.
140- * @param factory makes the session of the connected peer.
154+ * @param protocol what WHIP or WHEP asks beyond the offer and its answer.
155+ * @param factory makes the session of the connected peer.
141156 *
142157 * @return the future handed to the application.
143158 */
144159 static <S extends HttpSession > CompletableFuture <S > start (WebRtc rtc , PeerImpl peer , URI endpoint ,
145- String bearerToken , Duration timeout , Set < Integer > retried , Factory <S > factory ) {
160+ String bearerToken , Duration timeout , Protocol protocol , Factory <S > factory ) {
146161 CompletableFuture <Void > abandoned = new CompletableFuture <>();
147- CompletableFuture <S > session = peer .toPublic (negotiate (rtc , peer , endpoint , bearerToken , timeout , retried ,
162+ CompletableFuture <S > session = peer .toPublic (negotiate (rtc , peer , endpoint , bearerToken , timeout , protocol ,
148163 abandoned ).thenApply (resource -> factory .create (rtc , peer , resource , bearerToken , timeout )),
149164 HttpSession ::close );
150165
@@ -156,34 +171,42 @@ static <S extends HttpSession> CompletableFuture<S> start(WebRtc rtc, PeerImpl p
156171
157172 /**
158173 * Negotiates a manual peer over HTTP: creates the offer with all candidates,
159- * posts it, applies the answer and waits until the peer is connected.
174+ * posts it, applies the answer and waits until the peer is connected. An
175+ * endpoint that counters the offer, as WHEP allows, gets the answer to its
176+ * own offer instead.
160177 *
161178 * @param abandoned completes when no one waits for the session anymore,
162179 * which then ends as if it had failed.
163180 *
164181 * @return a future with the resource the server named, or null.
165182 */
166- private static CompletableFuture <URI > negotiate (WebRtc rtc , Peer peer , URI endpoint , String bearerToken ,
167- Duration timeout , Set < Integer > retried , CompletableFuture <?> abandoned ) {
183+ private static CompletableFuture <URI > negotiate (WebRtc rtc , PeerImpl peer , URI endpoint , String bearerToken ,
184+ Duration timeout , Protocol protocol , CompletableFuture <?> abandoned ) {
168185 CompletableFuture <URI > result = new CompletableFuture <>();
186+ long started = System .nanoTime ();
169187 // The resource the server created. Whoever takes it out owns it: the
170188 // session that connected, or whoever deletes it.
171189 AtomicReference <URI > resource = new AtomicReference <>();
172190 AtomicBoolean finished = new AtomicBoolean ();
191+ HttpClient client = rtc .httpClient (bearerToken != null );
173192 // Made now, so that it ends with the session's deadline at the latest,
174193 // however long the offer takes.
175- HttpCall offerRequest = new HttpCall (rtc .httpClient (bearerToken != null ), endpoint , "POST" , bearerToken ,
176- timeout ).followRedirects ().retry (rtc .timer , retried );
194+ HttpCall offerRequest = new HttpCall (client , endpoint , "POST" , bearerToken , timeout )
195+ .followRedirects ()
196+ .retry (rtc .timer , protocol .retried )
197+ .readBodies (protocol .counterOffers ? COUNTER_OFFER : Collections .emptySet ());
198+ // The request under way, which the end of the session cuts off.
199+ AtomicReference <HttpCall > request = new AtomicReference <>(offerRequest );
177200
178201 // Either way the session ends, once: connected, failed or timed out.
179202 Consumer <Throwable > fail = error -> {
180203 if (!finished .compareAndSet (false , true )) {
181204 return ;
182205 }
183206
184- // Ends an offer still out, whose answer would only meet a closed
207+ // Ends a request still out, whose answer would only meet a closed
185208 // peer.
186- offerRequest .abort ();
209+ request . get () .abort ();
187210 // Reported before the resource is deleted, which may take as long
188211 // as the timeout again.
189212 peer .close ();
@@ -203,17 +226,27 @@ private static CompletableFuture<URI> negotiate(WebRtc rtc, Peer peer, URI endpo
203226 });
204227
205228 peer .negotiator ().createOffer (Gathering .COMPLETE )
206- .thenCompose (offer -> post (offerRequest , endpoint , offer .sdp , resource )
207- .whenComplete ((answer , error ) -> {
229+ .thenCompose (offer -> post (offerRequest , endpoint , offer .sdp , protocol , resource )
230+ .whenComplete ((reply , error ) -> {
208231 if (finished .get ()) {
209232 // The session ended while the offer was out,
210233 // after the server named what it created, which
211234 // then has no one else to delete it.
212235 discard (rtc , resource .getAndSet (null ), bearerToken , timeout );
213236 }
214237 }))
215- .thenCompose (answer -> peer .negotiator ()
216- .applyAnswer (new RTCSessionDescription (RTCSdpType .ANSWER , answer )))
238+ .thenCompose (reply -> {
239+ if (!reply .counterOffer ) {
240+ return peer .negotiator ().applyAnswer (new RTCSessionDescription (RTCSdpType .ANSWER , reply .sdp ));
241+ }
242+
243+ // The rest of the session's time, which the answer has.
244+ Duration left = timeout .minusNanos (System .nanoTime () - started );
245+
246+ return answerCounterOffer (rtc , client , peer , reply , bearerToken ,
247+ left .isNegative () || left .isZero () ? Duration .ofNanos (1 ) : left , resource , request ,
248+ finished );
249+ })
217250 .thenCompose (applied -> peer .whenConnected ())
218251 .whenComplete ((connected , error ) -> {
219252 deadline .cancel (false );
@@ -230,12 +263,13 @@ else if (finished.compareAndSet(false, true)) {
230263 }
231264
232265 /**
233- * Posts the offer and returns the answer. The resource the server names is
234- * set as soon as it is known, so that it is deleted even if reading the
235- * answer fails. The request follows the redirects WHIP and WHEP allow, and
236- * the resource is resolved against the endpoint that answered.
266+ * Posts the offer and returns what the endpoint answered with. The
267+ * resource the server names with an answer is set as soon as it is known,
268+ * so that it is deleted even if reading the answer fails. The request
269+ * follows the redirects WHIP and WHEP allow, and the resource is resolved
270+ * against the endpoint that answered.
237271 */
238- private static CompletableFuture <String > post (HttpCall request , URI endpoint , String sdp ,
272+ private static CompletableFuture <Reply > post (HttpCall request , URI endpoint , String sdp , Protocol protocol ,
239273 AtomicReference <URI > resource ) {
240274 return request .send ("application/sdp" , sdp .getBytes (StandardCharsets .UTF_8 ), MAX_BODY , head -> {
241275 if (head .status == 201 || head .status == 200 ) {
@@ -249,15 +283,174 @@ private static CompletableFuture<String> post(HttpCall request, URI endpoint, St
249283 throw new WebRtcException ("Sending the offer to " + endpoint + " failed: " + error .getMessage (),
250284 error );
251285 }
252- if (response .status != 201 && response .status != 200 ) {
253- throw new WebRtcException ("The endpoint " + endpoint + " answered the offer with status "
254- + response .status + ": " + response .body );
286+ if (response .status == 201 || response .status == 200 ) {
287+ return new Reply (response .body , false , null , 0 );
255288 }
289+ if (protocol .counterOffers && isCounterOffer (response )) {
290+ URI session = resourceOf (response .uri , response .header ("Location" ));
291+
292+ if (session == null ) {
293+ throw new WebRtcException ("The endpoint " + endpoint
294+ + " countered the offer without naming the session" );
295+ }
256296
257- return response .body ;
297+ return new Reply (response .body , true , session ,
298+ counterOfferExpiry (response .header ("Content-Type" ), System .currentTimeMillis ()));
299+ }
300+
301+ String body = response .body ;
302+
303+ if (body .length () > HttpCall .MAX_ERROR_BODY ) {
304+ body = body .substring (0 , HttpCall .MAX_ERROR_BODY );
305+ }
306+
307+ throw new WebRtcException ("The endpoint " + endpoint + " answered the offer with status "
308+ + response .status + ": " + body );
258309 });
259310 }
260311
312+ /**
313+ * Answers the endpoint's own offer, which replaces the peer's, and sends
314+ * the answer to the session the endpoint named. The session is the
315+ * peer's to delete from the moment the answer goes out, since the server
316+ * creates it only then.
317+ *
318+ * @param timeout what is left of the session's timeout.
319+ */
320+ private static CompletableFuture <Void > answerCounterOffer (WebRtc rtc , HttpClient client , PeerImpl peer ,
321+ Reply reply , String bearerToken , Duration timeout , AtomicReference <URI > resource ,
322+ AtomicReference <HttpCall > request , AtomicBoolean finished ) {
323+ return peer .answerInstead (new RTCSessionDescription (RTCSdpType .OFFER , reply .sdp ), Gathering .COMPLETE )
324+ .thenCompose (answer -> {
325+ if (System .currentTimeMillis () > reply .validUntil ) {
326+ throw new WebRtcException ("The counter-offer for " + reply .session
327+ + " expired before it was answered" );
328+ }
329+
330+ HttpCall answerRequest = new HttpCall (client , reply .session , "PATCH" , bearerToken , timeout );
331+ request .set (answerRequest );
332+
333+ if (finished .get ()) {
334+ // Ended meanwhile, by what may have aborted the request
335+ // before.
336+ answerRequest .abort ();
337+ }
338+ else {
339+ resource .set (reply .session );
340+ }
341+
342+ return answerRequest .send ("application/sdp" , answer .sdp .getBytes (StandardCharsets .UTF_8 ), 0 ,
343+ head -> { }).handle ((response , error ) -> {
344+ if (error != null ) {
345+ throw new WebRtcException ("Sending the answer to " + reply .session + " failed: "
346+ + error .getMessage (), error );
347+ }
348+ if (response .status / 100 != 2 ) {
349+ throw new WebRtcException ("The endpoint answered the answer for "
350+ + reply .session + " with status " + response .status + ": "
351+ + response .body );
352+ }
353+
354+ return null ;
355+ });
356+ });
357+ }
358+
359+ /**
360+ * Tells a counter-offer from any other 406 answer, which WHEP asks to be
361+ * taken as an error: one has an SDP offer as its body.
362+ */
363+ private static boolean isCounterOffer (HttpCall .Response response ) {
364+ String type = response .header ("Content-Type" );
365+
366+ if (response .status != 406 || type == null ) {
367+ return false ;
368+ }
369+
370+ String mediaType = type .split (";" , 2 )[0 ].trim ();
371+
372+ return mediaType .equalsIgnoreCase ("application/sdp" ) && response .body .startsWith ("v=0" )
373+ && response .body .contains ("\n m=" );
374+ }
375+
376+ /**
377+ * Reads until when a counter-offer can be answered: the "valid-until"
378+ * parameter of its Content-Type, an HTTP date, or else 30 seconds after
379+ * it came, as WHEP says.
380+ *
381+ * @param contentType the Content-Type of the counter-offer.
382+ * @param nowMillis the time it came, as {@link System#currentTimeMillis()}.
383+ *
384+ * @return the time, as {@link System#currentTimeMillis()}.
385+ */
386+ static long counterOfferExpiry (String contentType , long nowMillis ) {
387+ Matcher validUntil = VALID_UNTIL .matcher (contentType != null ? contentType : "" );
388+
389+ if (validUntil .find ()) {
390+ try {
391+ return ZonedDateTime .parse (validUntil .group (1 ).trim (), DateTimeFormatter .RFC_1123_DATE_TIME )
392+ .toInstant ().toEpochMilli ();
393+ }
394+ catch (DateTimeParseException e ) {
395+ // Not an HTTP date; as if there were none.
396+ }
397+ }
398+
399+ return nowMillis + COUNTER_OFFER_VALIDITY_MILLIS ;
400+ }
401+
402+ /**
403+ * What WHIP or WHEP asks of a session beyond the offer and its answer.
404+ */
405+ static final class Protocol {
406+
407+ /**
408+ * The statuses of an answer to the offer, together with a Retry-After
409+ * header field, after which the offer is sent again, as long as the
410+ * wait fits within the timeout.
411+ */
412+ final Set <Integer > retried ;
413+
414+ /** Whether the endpoint may counter the offer with one of its own. */
415+ final boolean counterOffers ;
416+
417+
418+ Protocol (Set <Integer > retried , boolean counterOffers ) {
419+ this .retried = retried ;
420+ this .counterOffers = counterOffers ;
421+ }
422+ }
423+
424+
425+
426+ /**
427+ * What the endpoint answered the offer with: an answer, or an offer of its
428+ * own.
429+ */
430+ private static final class Reply {
431+
432+ final String sdp ;
433+
434+ /** Whether the SDP is the endpoint's offer, which replaces the peer's. */
435+ final boolean counterOffer ;
436+
437+ /** Where the session is once a counter-offer is answered. */
438+ final URI session ;
439+
440+ /** Until when a counter-offer can be answered. */
441+ final long validUntil ;
442+
443+
444+ Reply (String sdp , boolean counterOffer , URI session , long validUntil ) {
445+ this .sdp = sdp ;
446+ this .counterOffer = counterOffer ;
447+ this .session = session ;
448+ this .validUntil = validUntil ;
449+ }
450+ }
451+
452+
453+
261454 /**
262455 * Makes the session of a peer that connected.
263456 *
0 commit comments