@@ -542,9 +542,9 @@ impl DomainFronter {
542542 /// 5. Else: compute the remaining ranges, fetch them with
543543 /// bounded concurrency, stitch, return as 200.
544544 ///
545- /// If any chunk fails after retries , we fall back to the probe's
546- /// single-chunk response as a graceful-degradation — better a
547- /// truncated video than a blank one .
545+ /// If any later chunk fails validation or fetch , we fall back to the
546+ /// probe's single-chunk response as a graceful-degradation, but we do
547+ /// not stitch unchecked bytes into a fake full-success response .
548548 pub async fn relay_parallel_range (
549549 & self ,
550550 method : & str ,
@@ -580,18 +580,26 @@ impl DomainFronter {
580580 return first;
581581 }
582582
583- let total = match parse_content_range_total ( & resp_headers) {
584- Some ( t) => t,
585- None => return rewrite_206_to_200 ( & first) ,
583+ let probe_range = match validate_probe_range ( status, & resp_headers, resp_body, CHUNK - 1 )
584+ {
585+ Some ( r) => r,
586+ None => {
587+ tracing:: warn!(
588+ "range-parallel: probe returned invalid 206 for {}; falling back to single GET" ,
589+ url,
590+ ) ;
591+ return self . relay ( method, url, headers, body) . await ;
592+ }
586593 } ;
594+ let total = probe_range. total ;
587595
588- if total <= CHUNK || ( resp_body . len ( ) as u64 ) >= total {
596+ if total <= CHUNK || ( probe_range . end + 1 ) >= total {
589597 return rewrite_206_to_200 ( & first) ;
590598 }
591599
592600 // Plan remaining ranges after what the probe already returned.
593601 let mut ranges: Vec < ( u64 , u64 ) > = Vec :: new ( ) ;
594- let mut start = resp_body . len ( ) as u64 ;
602+ let mut start = probe_range . end + 1 ;
595603 while start < total {
596604 let end = ( start + CHUNK - 1 ) . min ( total - 1 ) ;
597605 ranges. push ( ( start, end) ) ;
@@ -622,28 +630,36 @@ impl DomainFronter {
622630 h. push ( ( "Range" . into ( ) , format ! ( "bytes={}-{}" , s, e) ) ) ;
623631 async move {
624632 let raw = self . relay ( "GET" , & url, & h, & [ ] ) . await ;
625- split_response ( & raw) . map ( | ( _ , _ , b ) | b . to_vec ( ) ) . unwrap_or_default ( )
633+ ( s , e , extract_exact_range_body ( & raw, s , e , total ) )
626634 }
627635 } )
628636 . buffered ( MAX_PARALLEL )
629- . collect :: < Vec < Vec < u8 > > > ( )
637+ . collect :: < Vec < _ > > ( )
630638 . await ;
631639
632640 // Stitch: probe body first, then the chunks in order.
633641 let mut full = Vec :: with_capacity ( total as usize ) ;
634642 full. extend_from_slice ( resp_body) ;
635- for chunk in & fetches {
636- full. extend_from_slice ( chunk) ;
643+ for ( start, end, chunk) in fetches {
644+ match chunk {
645+ Ok ( chunk) => full. extend_from_slice ( & chunk) ,
646+ Err ( reason) => {
647+ tracing:: warn!(
648+ "range-parallel: invalid chunk {}-{} for {} ({}); falling back to probe response" ,
649+ start,
650+ end,
651+ url,
652+ reason,
653+ ) ;
654+ return rewrite_206_to_200 ( & first) ;
655+ }
656+ }
637657 }
638658
639- // If any chunk came back empty (relay failure) we've now got a
640- // short body. Better to ship the probe-only 200 than a silently
641- // truncated 200 — the player will display a clear error or
642- // retry, vs rendering half the movie and cutting.
643- if ( full. len ( ) as u64 ) < total {
659+ if ( full. len ( ) as u64 ) != total {
644660 tracing:: warn!(
645- "range-parallel: stitched {}/{} bytes, some chunks failed ; falling back to probe response" ,
646- full. len( ) , total,
661+ "range-parallel: stitched {}/{} bytes for {} ; falling back to probe response" ,
662+ full. len( ) , total, url ,
647663 ) ;
648664 return rewrite_206_to_200 ( & first) ;
649665 }
@@ -961,13 +977,77 @@ fn split_response(raw: &[u8]) -> Option<(u16, Vec<(String, String)>, &[u8])> {
961977 Some ( ( code, headers, body) )
962978}
963979
964- /// Pull the total size out of a `Content-Range: bytes 0-NNN/TOTAL` header.
965- fn parse_content_range_total ( headers : & [ ( String , String ) ] ) -> Option < u64 > {
980+ #[ derive( Debug , Clone , Copy , PartialEq , Eq ) ]
981+ struct ContentRange {
982+ start : u64 ,
983+ end : u64 ,
984+ total : u64 ,
985+ }
986+
987+ /// Parse `Content-Range: bytes START-END/TOTAL`.
988+ fn parse_content_range ( headers : & [ ( String , String ) ] ) -> Option < ContentRange > {
966989 let cr = headers
967990 . iter ( )
968991 . find ( |( k, _) | k. eq_ignore_ascii_case ( "content-range" ) ) ?;
969- let slash = cr. 1 . rfind ( '/' ) ?;
970- cr. 1 [ slash + 1 ..] . trim ( ) . parse :: < u64 > ( ) . ok ( )
992+ let value = cr. 1 . trim ( ) ;
993+ let ( unit, rest) = value. split_once ( ' ' ) ?;
994+ if !unit. eq_ignore_ascii_case ( "bytes" ) {
995+ return None ;
996+ }
997+ let ( range, total) = rest. trim_start ( ) . split_once ( '/' ) ?;
998+ let ( start, end) = range. split_once ( '-' ) ?;
999+ let start = start. trim ( ) . parse :: < u64 > ( ) . ok ( ) ?;
1000+ let end = end. trim ( ) . parse :: < u64 > ( ) . ok ( ) ?;
1001+ let total = total. trim ( ) . parse :: < u64 > ( ) . ok ( ) ?;
1002+ if start > end || total == 0 || end >= total {
1003+ return None ;
1004+ }
1005+ Some ( ContentRange { start, end, total } )
1006+ }
1007+
1008+ /// Pull the total size out of a valid `Content-Range: bytes START-END/TOTAL` header.
1009+ fn parse_content_range_total ( headers : & [ ( String , String ) ] ) -> Option < u64 > {
1010+ parse_content_range ( headers) . map ( |r| r. total )
1011+ }
1012+
1013+ fn content_range_matches_body ( range : ContentRange , body_len : usize ) -> bool {
1014+ body_len > 0 && ( range. end - range. start + 1 ) == body_len as u64
1015+ }
1016+
1017+ fn validate_probe_range (
1018+ status : u16 ,
1019+ headers : & [ ( String , String ) ] ,
1020+ body : & [ u8 ] ,
1021+ requested_end : u64 ,
1022+ ) -> Option < ContentRange > {
1023+ if status != 206 {
1024+ return None ;
1025+ }
1026+ let range = parse_content_range ( headers) ?;
1027+ if range. start != 0 || range. end > requested_end || !content_range_matches_body ( range, body. len ( ) ) {
1028+ return None ;
1029+ }
1030+ Some ( range)
1031+ }
1032+
1033+ fn extract_exact_range_body (
1034+ raw : & [ u8 ] ,
1035+ start : u64 ,
1036+ end : u64 ,
1037+ total : u64 ,
1038+ ) -> Result < Vec < u8 > , & ' static str > {
1039+ let ( status, headers, body) = split_response ( raw) . ok_or ( "malformed HTTP response" ) ?;
1040+ if status != 206 {
1041+ return Err ( "expected 206 Partial Content" ) ;
1042+ }
1043+ let range = parse_content_range ( & headers) . ok_or ( "missing or invalid Content-Range" ) ?;
1044+ if range. start != start || range. end != end || range. total != total {
1045+ return Err ( "unexpected Content-Range" ) ;
1046+ }
1047+ if !content_range_matches_body ( range, body. len ( ) ) {
1048+ return Err ( "Content-Range/body length mismatch" ) ;
1049+ }
1050+ Ok ( body. to_vec ( ) )
9711051}
9721052
9731053/// Rewrite a 206 response to a 200 OK, dropping Content-Range and
@@ -1767,6 +1847,40 @@ mod tests {
17671847 assert ! ( s. ends_with( "Hello" ) ) ;
17681848 }
17691849
1850+ #[ test]
1851+ fn parse_content_range_total_accepts_mixed_case_unit ( ) {
1852+ let headers = vec ! [ ( "Content-Range" . to_string( ) , "Bytes 0-4/20" . to_string( ) ) ] ;
1853+ assert_eq ! ( parse_content_range_total( & headers) , Some ( 20 ) ) ;
1854+ }
1855+
1856+ #[ test]
1857+ fn parse_content_range_total_rejects_descending_range ( ) {
1858+ let headers = vec ! [ ( "Content-Range" . to_string( ) , "bytes 10-4/20" . to_string( ) ) ] ;
1859+ assert_eq ! ( parse_content_range_total( & headers) , None ) ;
1860+ }
1861+
1862+ #[ test]
1863+ fn parse_content_range_total_rejects_end_past_total ( ) {
1864+ let headers = vec ! [ ( "Content-Range" . to_string( ) , "bytes 0-20/20" . to_string( ) ) ] ;
1865+ assert_eq ! ( parse_content_range_total( & headers) , None ) ;
1866+ }
1867+
1868+ #[ test]
1869+ fn validate_probe_range_rejects_body_length_mismatch ( ) {
1870+ let headers = vec ! [ ( "Content-Range" . to_string( ) , "bytes 0-4/20" . to_string( ) ) ] ;
1871+ assert ! ( validate_probe_range( 206 , & headers, b"hey" , 4 ) . is_none( ) ) ;
1872+ }
1873+
1874+ #[ test]
1875+ fn extract_exact_range_body_rejects_mismatched_content_range ( ) {
1876+ let raw = b"HTTP/1.1 206 Partial Content\r \n \
1877+ Content-Range: bytes 5-9/20\r \n \
1878+ Content-Length: 5\r \n \r \n \
1879+ hello";
1880+ let err = extract_exact_range_body ( raw, 10 , 14 , 20 ) . unwrap_err ( ) ;
1881+ assert_eq ! ( err, "unexpected Content-Range" ) ;
1882+ }
1883+
17701884 #[ test]
17711885 fn parse_relay_error_field ( ) {
17721886 let body = r#"{"e":"unauthorized"}"# ;
0 commit comments