glory-cli 0.8.1

Project-local build and development tools for Glory semantic applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
use std::io::{self, Read, Write};
use std::net::{IpAddr, SocketAddr, TcpListener, TcpStream};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use notify::{RecursiveMode, Watcher};
use serde_json::json;

use crate::args::Args;
use crate::project::{Platform, Project};
use crate::{Result, build};

const RELOAD: &str = "let revision=Number(new URL(import.meta.url).searchParams.get('revision'));let overlay;setInterval(async()=>{try{const r=await fetch('/__glory_dev/state',{cache:'no-store'});const s=await r.json();if(s.error){if(!overlay){overlay=document.createElement('pre');overlay.setAttribute('role','alert');document.body.prepend(overlay);}overlay.textContent=s.error;}else{overlay?.remove();overlay=null;}if(revision!==s.revision){location.reload();}revision=s.revision;}catch{}},750);";

const MAX_CONNECTIONS: usize = 8;
const IO_TICK: Duration = Duration::from_millis(25);
#[derive(Clone, Copy)]
struct Deadlines {
    headers: Duration,
    response: Duration,
}
impl Default for Deadlines {
    fn default() -> Self {
        Self {
            headers: Duration::from_secs(2),
            response: Duration::from_secs(10),
        }
    }
}

/// Only admitted connections own threads. Excess sockets are closed without
/// queuing work; the watch/build loop never waits for a client's socket IO.
struct Connections {
    workers: Vec<std::thread::JoinHandle<()>>,
    stop: Arc<AtomicBool>,
    deadlines: Deadlines,
}
impl Connections {
    fn new(stop: Arc<AtomicBool>, deadlines: Deadlines) -> Self {
        Self {
            workers: Vec::new(),
            stop,
            deadlines,
        }
    }
    fn accept(
        &mut self,
        listener: &TcpListener,
        root: &Path,
        revision: u64,
        error: Option<&str>,
        reload: bool,
    ) -> Result<()> {
        let mut index = 0;
        while index < self.workers.len() {
            if self.workers[index].is_finished() {
                let _ = self.workers.swap_remove(index).join();
            } else {
                index += 1;
            }
        }
        for _ in 0..32 {
            if self.stop.load(Ordering::Acquire) {
                break;
            }
            match listener.accept() {
                Ok((mut stream, _)) => {
                    if self.workers.len() == MAX_CONNECTIONS {
                        continue;
                    }
                    let root = root.to_path_buf();
                    let error = error.map(str::to_owned);
                    let stop = self.stop.clone();
                    let deadlines = self.deadlines;
                    self.workers.push(
                        std::thread::Builder::new()
                            .name("glory-dev-http".into())
                            .spawn(move || {
                                if let Err(error) = respond(
                                    &mut stream,
                                    &root,
                                    revision,
                                    error.as_deref(),
                                    reload,
                                    deadlines,
                                    &stop,
                                ) && !stop.load(Ordering::Acquire)
                                {
                                    eprintln!("HTTP: {error}");
                                }
                            })
                            .map_err(|error| error.to_string())?,
                    );
                }
                Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
                Err(error) => return Err(error.to_string()),
            }
        }
        Ok(())
    }
}
impl Drop for Connections {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Release);
        for worker in self.workers.drain(..) {
            let _ = worker.join();
        }
    }
}

/// Socket timeouts are short cancellation checkpoints. The phase deadline is
/// absolute, so receiving or sending another byte never renews it.
struct Connection<'a> {
    socket: &'a mut TcpStream,
    stop: &'a AtomicBool,
    deadline: Instant,
}
impl Connection<'_> {
    fn perform<T>(
        &mut self,
        writing: bool,
        mut operation: impl FnMut(&mut TcpStream) -> io::Result<T>,
    ) -> io::Result<T> {
        loop {
            if self.stop.load(Ordering::Acquire) {
                return Err(io::Error::other("HTTP request cancelled"));
            }
            let remaining = self
                .deadline
                .checked_duration_since(Instant::now())
                .filter(|time| !time.is_zero())
                .ok_or_else(|| io::Error::new(io::ErrorKind::TimedOut, "HTTP phase deadline"))?;
            if writing {
                self.socket
                    .set_write_timeout(Some(remaining.min(IO_TICK)))?;
            } else {
                self.socket.set_read_timeout(Some(remaining.min(IO_TICK)))?;
            }
            match operation(self.socket) {
                Err(error)
                    if matches!(
                        error.kind(),
                        io::ErrorKind::WouldBlock
                            | io::ErrorKind::TimedOut
                            | io::ErrorKind::Interrupted
                    ) => {}
                result => return result,
            }
        }
    }
}
impl Read for Connection<'_> {
    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
        self.perform(false, |socket| socket.read(buffer))
    }
}
impl Write for Connection<'_> {
    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        self.perform(true, |socket| socket.write(buffer))
    }
    fn flush(&mut self) -> io::Result<()> {
        self.perform(true, Write::flush)
    }
}

pub fn serve(mut project: Project, mut args: Args) -> Result<()> {
    if project.platform != Platform::Web {
        return crate::native_dev::serve(project, args);
    }
    let stop = Arc::new(AtomicBool::new(false));
    let signal = stop.clone();
    ctrlc::set_handler(move || signal.store(true, Ordering::Release)).map_err(|e| e.to_string())?;
    args.cancel = Some(stop.clone());
    project.cancel = Some(stop.clone());
    let built = build::build(&project, &args)?;
    let directory = built.directory.ok_or("Web build has no output directory")?;
    let listener =
        TcpListener::bind(("127.0.0.1", args.port.or(project.host.port).unwrap_or(8080)))
            .map_err(|e| e.to_string())?;
    listener.set_nonblocking(true).map_err(|e| e.to_string())?;
    let changed = Arc::new(AtomicBool::new(false));
    let mut watcher = if args.watch {
        Some(watch(&project, changed.clone())?)
    } else {
        None
    };
    let mut revision = 1_u64;
    let mut error = None;
    let mut last_event = None;
    println!(
        "Glory: http://{} (Ctrl+C to stop)",
        listener.local_addr().map_err(|e| e.to_string())?
    );
    let mut connections = Connections::new(stop.clone(), Deadlines::default());
    while !stop.load(Ordering::Acquire) {
        connections.accept(
            &listener,
            &directory,
            revision,
            error.as_deref(),
            args.watch,
        )?;
        if changed.swap(false, Ordering::AcqRel) {
            last_event = Some(Instant::now());
        }
        if last_event.is_some_and(|time| time.elapsed() >= Duration::from_millis(200)) {
            last_event = None;
            println!("Sources changed; rebuilding...");
            match Project::load(&project.manifest, &args).and_then(|current| {
                build::build(&current, &args)?;
                Ok(current)
            }) {
                Ok(current) => {
                    project = current;
                    revision = revision
                        .checked_add(1)
                        .ok_or("development revision exhausted")?;
                    error = None;
                    watcher = Some(watch(&project, changed.clone())?);
                    println!("Rebuild complete (revision {revision})");
                }
                Err(message) => {
                    eprintln!("{message}");
                    error = Some(message.chars().take(32_768).collect::<String>());
                }
            }
        }
        std::thread::sleep(Duration::from_millis(25));
    }
    drop(watcher);
    Ok(())
}

pub(crate) fn watch(
    project: &Project,
    changed: Arc<AtomicBool>,
) -> Result<notify::RecommendedWatcher> {
    let build_root = project.paths.root.clone();
    let mut watcher =
        notify::recommended_watcher(move |result: notify::Result<notify::Event>| match result {
            Ok(event) if !matches!(event.kind, notify::EventKind::Access(_)) => {
                if event.paths.iter().any(|path| {
                    !path.starts_with(&build_root)
                        && !path.components().any(|part| {
                            matches!(
                                part.as_os_str().to_str(),
                                Some(".git" | "target" | "node_modules")
                            )
                        })
                }) {
                    changed.store(true, Ordering::Release);
                }
            }
            Err(error) => eprintln!("watch: {error}"),
            _ => {}
        })
        .map_err(|e| e.to_string())?;
    let mut roots = project.watch_roots.clone();
    roots.sort();
    roots.dedup();
    let mut installed = Vec::<PathBuf>::new();
    for root in roots {
        if installed.iter().any(|parent| root.starts_with(parent)) {
            continue;
        }
        watcher
            .watch(&root, RecursiveMode::Recursive)
            .map_err(|e| format!("watch {}: {e}", root.display()))?;
        installed.push(root);
    }
    Ok(watcher)
}

fn respond(
    stream: &mut TcpStream,
    root: &Path,
    revision: u64,
    error: Option<&str>,
    reload: bool,
    deadlines: Deadlines,
    stop: &AtomicBool,
) -> Result<()> {
    // Windows accepts can inherit the listener's nonblocking mode.
    stream.set_nonblocking(false).map_err(|e| e.to_string())?;
    let mut connection = Connection {
        socket: stream,
        stop,
        deadline: Instant::now() + deadlines.headers,
    };
    let stream = &mut connection;
    let mut request = Vec::new();
    let mut chunk = [0_u8; 1024];
    while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") {
        let count = stream.read(&mut chunk).map_err(|e| e.to_string())?;
        if count == 0 {
            return Ok(());
        }
        request.extend_from_slice(&chunk[..count]);
        if request.len() > 16_384 {
            return reply(
                stream,
                "431 Request Header Fields Too Large",
                "text/plain",
                b"header too large",
                false,
            );
        }
    }
    stream.deadline = Instant::now() + deadlines.response;
    let request = match std::str::from_utf8(&request) {
        Ok(request) => request,
        Err(_) => {
            return reply(
                stream,
                "400 Bad Request",
                "text/plain",
                b"invalid request",
                false,
            );
        }
    };
    let Some((method, url)) = local_request(
        request,
        stream.socket.local_addr().map_err(|e| e.to_string())?,
    ) else {
        return reply(
            stream,
            "400 Bad Request",
            "text/plain",
            b"invalid request authority",
            false,
        );
    };
    let head = method == "HEAD";
    if !matches!(method, "GET" | "HEAD") {
        return reply(
            stream,
            "405 Method Not Allowed",
            "text/plain",
            b"GET or HEAD required",
            false,
        );
    }
    let path = url.split('?').next().unwrap_or("");
    if path == "/__glory_dev/state" {
        let body = serde_json::to_vec(&json!({ "revision": revision, "error": error }))
            .map_err(|e| e.to_string())?;
        return reply(stream, "200 OK", "application/json", &body, head);
    }
    if path == "/__glory_dev/reload.js" {
        return reply(stream, "200 OK", "text/javascript", RELOAD.as_bytes(), head);
    }
    let relative = match decode_path(path) {
        Ok(path) => path,
        Err(_) => {
            return reply(
                stream,
                "400 Bad Request",
                "text/plain",
                b"invalid path",
                head,
            );
        }
    };
    let canonical_root = root.canonicalize().map_err(|e| e.to_string())?;
    let file = match root.join(&relative).canonicalize() {
        Ok(file) if file.starts_with(&canonical_root) && file.is_file() => file,
        _ => return reply(stream, "404 Not Found", "text/plain", b"not found", head),
    };
    let accept_encoding = request
        .lines()
        .skip(1)
        .take_while(|line| !line.is_empty())
        .filter_map(|line| line.split_once(':'))
        .filter(|(name, _)| name.eq_ignore_ascii_case("accept-encoding"))
        .map(|(_, value)| value.trim())
        .collect::<Vec<_>>()
        .join(",");
    let mut compressed_name = file.as_os_str().to_owned();
    compressed_name.push(".gz");
    let compressed = Path::new(&compressed_name)
        .canonicalize()
        .ok()
        .filter(|path| !reload && path.starts_with(&canonical_root) && path.is_file());
    let gzip = match crate::compression::negotiate(&accept_encoding, compressed.is_some()) {
        Ok(gzip) => gzip,
        Err(_) => {
            return reply(
                stream,
                "406 Not Acceptable",
                "text/plain",
                b"no acceptable content encoding",
                head,
            );
        }
    };
    let selected = if gzip {
        compressed.as_ref().unwrap()
    } else {
        &file
    };
    let mut body = std::fs::read(selected).map_err(|e| e.to_string())?;
    let kind = match file
        .extension()
        .and_then(|extension| extension.to_str())
        .unwrap_or("")
    {
        "html" => "text/html; charset=utf-8",
        "js" | "mjs" => "text/javascript",
        "wasm" => "application/wasm",
        "css" => "text/css",
        "json" => "application/json",
        "svg" => "image/svg+xml",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "webp" => "image/webp",
        "ico" => "image/x-icon",
        "woff2" => "font/woff2",
        _ => "application/octet-stream",
    };
    if reload
        && file
            .extension()
            .is_some_and(|extension| extension == "html")
        && let Ok(html) = std::str::from_utf8(&body)
    {
        let script = format!(
            "<script type=\"module\" src=\"/__glory_dev/reload.js?revision={revision}\"></script>"
        );
        let position = html.rfind("</body>").unwrap_or(html.len());
        body = format!("{}{script}{}", &html[..position], &html[position..]).into_bytes();
    }
    reply_encoded(stream, "200 OK", kind, &body, head, gzip)
}

// Loopback binding alone does not prevent a browser using an attacker-controlled
// DNS name. Check the HTTP authority before serving files or development state.
fn local_request(request: &str, address: SocketAddr) -> Option<(&str, &str)> {
    if !address.ip().is_loopback() {
        return None;
    }
    let (headers, _) = request.split_once("\r\n\r\n")?;
    let mut lines = headers.split("\r\n");
    let mut words = lines.next()?.split(' ');
    let (method, target, version) = (words.next()?, words.next()?, words.next()?);
    if method.is_empty()
        || !method
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
        || !target.starts_with('/')
        || target
            .bytes()
            .any(|byte| byte.is_ascii_control() || byte == b' ')
        || !matches!(version, "HTTP/1.0" | "HTTP/1.1")
        || words.next().is_some()
    {
        return None;
    }
    let mut host = None;
    for line in lines {
        let (name, value) = line.split_once(':')?;
        if name.is_empty()
            || !name
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
            || value
                .bytes()
                .any(|byte| byte.is_ascii_control() && byte != b'\t')
        {
            return None;
        }
        if name.eq_ignore_ascii_case("host") {
            if host.is_some() {
                return None;
            }
            host = Some(value.trim_matches([' ', '\t']));
        }
    }
    match host {
        Some(host) if local_authority(host, address) => Some((method, target)),
        None if version == "HTTP/1.0" => Some((method, target)),
        _ => None,
    }
}

fn local_authority(authority: &str, address: SocketAddr) -> bool {
    let (host, port) = if let Some(rest) = authority.strip_prefix('[') {
        let Some((host, suffix)) = rest.split_once(']') else {
            return false;
        };
        let port = if suffix.is_empty() {
            None
        } else {
            suffix.strip_prefix(':')
        };
        if !suffix.is_empty() && port.is_none() {
            return false;
        }
        // Brackets are only valid around an IPv6 literal.
        if host.parse::<std::net::Ipv6Addr>().is_err() {
            return false;
        }
        (host, port)
    } else {
        match authority.split_once(':') {
            Some((host, port)) => (host, Some(port)),
            None => (authority, None),
        }
    };
    let port = match port {
        Some(value) if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) => {
            match value.parse::<u16>() {
                Ok(port) => port,
                Err(_) => return false,
            }
        }
        None => 80,
        _ => return false,
    };
    port == address.port()
        && (host.eq_ignore_ascii_case("localhost")
            || host.parse::<IpAddr>().is_ok_and(|ip| ip == address.ip()))
}

fn reply(stream: &mut impl Write, status: &str, kind: &str, body: &[u8], head: bool) -> Result<()> {
    reply_encoded(stream, status, kind, body, head, false)
}

fn reply_encoded(
    stream: &mut impl Write,
    status: &str,
    kind: &str,
    body: &[u8],
    head: bool,
    gzip: bool,
) -> Result<()> {
    let encoding = if gzip {
        "Content-Encoding: gzip\r\n"
    } else {
        ""
    };
    write!(stream, "HTTP/1.1 {status}\r\nContent-Type: {kind}\r\nContent-Length: {}\r\n{encoding}Vary: Accept-Encoding\r\nCache-Control: no-store\r\nConnection: close\r\nX-Content-Type-Options: nosniff\r\n\r\n", body.len()).map_err(|e| e.to_string())?;
    if !head {
        stream.write_all(body).map_err(|e| e.to_string())?;
    }
    Ok(())
}

fn decode_path(path: &str) -> Result<PathBuf> {
    if !path.starts_with('/') {
        return Err("expected origin-relative path".into());
    }
    let mut decoded = Vec::new();
    let mut bytes = path.as_bytes().iter().copied();
    while let Some(byte) = bytes.next() {
        if byte == b'%' {
            let high = bytes
                .next()
                .and_then(|byte| (byte as char).to_digit(16))
                .ok_or("invalid percent escape")?;
            let low = bytes
                .next()
                .and_then(|byte| (byte as char).to_digit(16))
                .ok_or("invalid percent escape")?;
            decoded.push((high * 16 + low) as u8);
        } else {
            decoded.push(byte);
        }
    }
    let decoded = String::from_utf8(decoded).map_err(|e| e.to_string())?;
    if decoded.contains(['\\', ':', '\0']) {
        return Err("invalid path character".into());
    }
    let relative = PathBuf::from(decoded.trim_start_matches('/'));
    if relative
        .components()
        .any(|part| !matches!(part, Component::Normal(_) | Component::CurDir))
    {
        return Err("path escaped the site".into());
    }
    Ok(if relative.as_os_str().is_empty() {
        PathBuf::from("index.html")
    } else {
        relative
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn encoded_traversal_and_windows_paths_cannot_escape_the_site() {
        for path in [
            "/../secret",
            "/%2e%2e/secret",
            "/a/%2E%2E/secret",
            "/D:/secret",
            "/a%5csecret",
            "/%00",
            "/%",
        ] {
            assert!(decode_path(path).is_err(), "{path}");
        }
        assert_eq!(
            decode_path("/some%20file.js").unwrap(),
            PathBuf::from("some file.js")
        );
    }

    fn request(root: &Path, request: &[u8], reload: bool) -> Vec<u8> {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let request = String::from_utf8(request.to_vec())
            .unwrap()
            .replace("{port}", &address.port().to_string());
        let root = root.to_path_buf();
        let worker = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream.set_nonblocking(true).unwrap();
            respond(
                &mut stream,
                &root,
                7,
                Some("<compiler error>"),
                reload,
                Deadlines::default(),
                &AtomicBool::new(false),
            )
            .unwrap();
        });
        let mut client = TcpStream::connect(address).unwrap();
        std::thread::sleep(Duration::from_millis(20));
        client.write_all(request.as_bytes()).unwrap();
        let mut bytes = Vec::new();
        client.read_to_end(&mut bytes).unwrap();
        worker.join().unwrap();
        bytes
    }

    #[test]
    fn real_http_serves_wasm_head_and_development_state_without_mutating_release_files() {
        let root = crate::test_support::Scratch::new();
        let html = "<html><body>app</body></html>";
        root.write("index.html", html);
        root.write("app.wasm", "wasm-bytes");
        let response = request(
            &root.0,
            b"GET / HTTP/1.1\r\nHost: localhost:{port}\r\n\r\n",
            true,
        );
        assert!(
            String::from_utf8(response)
                .unwrap()
                .contains("/__glory_dev/reload.js")
        );
        assert_eq!(
            std::fs::read_to_string(root.0.join("index.html")).unwrap(),
            html
        );
        let response = request(
            &root.0,
            b"HEAD /app.wasm HTTP/1.1\r\nHost: localhost:{port}\r\n\r\n",
            false,
        );
        let response = String::from_utf8(response).unwrap();
        assert!(response.contains("Content-Type: application/wasm"));
        assert!(response.ends_with("\r\n\r\n"));
        let response = request(
            &root.0,
            b"GET /__glory_dev/state HTTP/1.1\r\nHost: localhost:{port}\r\n\r\n",
            true,
        );
        let response = String::from_utf8(response).unwrap();
        let json: serde_json::Value =
            serde_json::from_str(response.split("\r\n\r\n").nth(1).unwrap()).unwrap();
        assert_eq!(json["revision"], 7);
        assert_eq!(json["error"], "<compiler error>");
    }

    #[test]
    fn real_http_negotiates_release_gzip_and_head_but_keeps_reload_editable() {
        let root = crate::test_support::Scratch::new();
        let source = format!("<html><body>{}</body></html>", "中文 app ".repeat(100));
        root.write("index.html", &source);
        root.write("app.wasm", &"wasm-bytes".repeat(200));
        crate::compression::compress(&root.0).unwrap();
        let compressed = std::fs::read(root.0.join("index.html.gz")).unwrap();
        let response = request(
            &root.0,
            b"GET / HTTP/1.1\r\nHost: localhost:{port}\r\nAccept-Encoding: br, gzip\r\n\r\n",
            false,
        );
        let split = response.windows(4).position(|p| p == b"\r\n\r\n").unwrap() + 4;
        let headers = std::str::from_utf8(&response[..split]).unwrap();
        assert!(headers.contains("Content-Encoding: gzip\r\n"));
        assert!(headers.contains("Vary: Accept-Encoding\r\n"));
        assert!(headers.contains(&format!("Content-Length: {}\r\n", compressed.len())));
        assert_eq!(&response[split..], compressed);
        let response = request(
            &root.0,
            b"HEAD / HTTP/1.1\r\nHost: localhost:{port}\r\nAccept-Encoding: gzip\r\n\r\n",
            false,
        );
        let response = String::from_utf8(response).unwrap();
        assert!(response.contains("Content-Encoding: gzip\r\n"));
        assert!(response.contains(&format!("Content-Length: {}\r\n", compressed.len())));
        assert!(response.ends_with("\r\n\r\n"));
        for (headers, reload) in [
            ("", false),
            ("Accept-Encoding: gzip;q=0\r\n", false),
            ("Accept-Encoding: gzip\r\n", true),
        ] {
            let response = request(
                &root.0,
                format!("GET / HTTP/1.1\r\nHost: localhost:{{port}}\r\n{headers}\r\n").as_bytes(),
                reload,
            );
            let response = String::from_utf8(response).unwrap();
            assert!(!response.contains("Content-Encoding:"));
            let body = response.split_once("\r\n\r\n").unwrap().1;
            if reload {
                let script =
                    "<script type=\"module\" src=\"/__glory_dev/reload.js?revision=7\"></script>";
                assert_eq!(body.replace(script, ""), source);
            } else {
                assert_eq!(body, source);
            }
            assert_eq!(response.contains("/__glory_dev/reload.js"), reload);
        }
        let response = request(
            &root.0,
            b"GET /app.wasm HTTP/1.1\r\nHost: localhost:{port}\r\nAccept-Encoding: *;q=0\r\n\r\n",
            false,
        );
        assert!(response.starts_with(b"HTTP/1.1 406 Not Acceptable\r\n"));
    }

    #[test]
    fn http_authority_requires_the_listening_loopback_and_port() {
        let address = "127.0.0.1:8080".parse().unwrap();
        for host in ["localhost:8080", "LOCALHOST:8080", "127.0.0.1:8080"] {
            assert!(
                local_request(&format!("GET / HTTP/1.1\r\nHost: {host}\r\n\r\n"), address)
                    .is_some(),
                "{host}"
            );
        }
        for headers in [
            "",
            "Host: attacker.test:8080\r\n",
            "Host: localhost\r\n",
            "Host: localhost:80\r\n",
            "Host: 127.0.0.2:8080\r\n",
            "Host: [::1]:8080\r\n",
            "Host: localhost:8080@evil.test\r\n",
            "Host: localhost:8080/path\r\n",
            "Host: localhost:+8080\r\n",
            "Host: localhost:8080,evil.test\r\n",
            "Host: localhost.:8080\r\n",
            "Host: localhost:8080\r\nhOsT: localhost:8080\r\n",
            "Host : localhost:8080\r\n",
            " Host: localhost:8080\r\n",
            "Host: localhost:8080\r\n folded\r\n",
        ] {
            assert!(
                local_request(&format!("GET / HTTP/1.1\r\n{headers}\r\n"), address).is_none(),
                "{headers:?}"
            );
        }
        assert!(local_request("GET / HTTP/1.0\r\n\r\n", address).is_some());
        assert!(
            local_request(
                "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n",
                "127.0.0.1:80".parse().unwrap()
            )
            .is_some()
        );
        assert!(
            local_request(
                "GET / HTTP/1.1\r\nHost: [::1]:8080\r\n\r\n",
                "[::1]:8080".parse().unwrap()
            )
            .is_some()
        );
        for line in [
            "GET http://localhost:8080/ HTTP/1.1",
            "GET / HTTP/2",
            "GET / HTTP/1.1 extra",
            "GET  / HTTP/1.1",
        ] {
            assert!(
                local_request(&format!("{line}\r\nHost: localhost:8080\r\n\r\n"), address)
                    .is_none()
            );
        }
    }

    #[test]
    fn foreign_or_missing_host_cannot_read_files_or_compiler_state() {
        let root = crate::test_support::Scratch::new();
        root.write("index.html", "private application source");
        for path in ["/", "/__glory_dev/state", "/__glory_dev/reload.js"] {
            for host in [
                "",
                "Host: attacker.test:{port}\r\n",
                "Host: localhost:{port}\r\nHost: localhost:{port}\r\n",
            ] {
                let response = request(
                    &root.0,
                    format!("GET {path} HTTP/1.1\r\n{host}\r\n").as_bytes(),
                    true,
                );
                assert!(response.starts_with(b"HTTP/1.1 400 Bad Request\r\n"));
                let response = String::from_utf8(response).unwrap();
                assert!(
                    !response.contains("compiler error")
                        && !response.contains("private application source")
                );
            }
        }
    }

    #[test]
    fn continuously_dripping_headers_cannot_renew_the_absolute_deadline() {
        let root = crate::test_support::Scratch::new();
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
        let (done, result) = std::sync::mpsc::channel();
        let worker = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            done.send(respond(
                &mut stream,
                &root.0,
                1,
                None,
                false,
                Deadlines {
                    headers: Duration::from_millis(100),
                    response: Duration::from_secs(1),
                },
                &AtomicBool::new(false),
            ))
            .unwrap();
        });
        client.write_all(b"GET / HTTP/1.1\r\nX-Drip: ").unwrap();
        let watchdog = Instant::now() + Duration::from_secs(2);
        let outcome = loop {
            match result.recv_timeout(Duration::from_millis(10)) {
                Ok(outcome) => break outcome,
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) if Instant::now() < watchdog => {
                    let _ = client.write_all(b"x");
                }
                other => {
                    drop(client);
                    worker.join().unwrap();
                    panic!("dripping request did not expire: {other:?}");
                }
            }
        };
        assert!(outcome.unwrap_err().contains("HTTP phase deadline"));
        worker.join().unwrap();
    }

    #[test]
    fn stalled_clients_do_not_block_new_state_requests_or_shutdown_and_admission_is_bounded() {
        let root = crate::test_support::Scratch::new();
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let address = listener.local_addr().unwrap();
        let stop = Arc::new(AtomicBool::new(false));
        let mut connections = Connections::new(
            stop.clone(),
            Deadlines {
                headers: Duration::from_secs(30),
                response: Duration::from_secs(30),
            },
        );
        let mut stalled = TcpStream::connect(address).unwrap();
        stalled.write_all(b"GET / HTTP/1.1\r\n").unwrap();
        connections
            .accept(&listener, &root.0, 1, None, true)
            .unwrap();
        assert_eq!(connections.workers.len(), 1);

        // The watch loop can publish a later revision while the first header
        // is still incomplete, and a normal request receives that new state.
        let mut normal = TcpStream::connect(address).unwrap();
        normal
            .set_read_timeout(Some(Duration::from_secs(2)))
            .unwrap();
        write!(
            normal,
            "GET /__glory_dev/state HTTP/1.1\r\nHost: localhost:{}\r\n\r\n",
            address.port()
        )
        .unwrap();
        connections
            .accept(&listener, &root.0, 12, Some("rebuilt"), true)
            .unwrap();
        let mut response = String::new();
        normal.read_to_string(&mut response).unwrap();
        assert!(response.starts_with("HTTP/1.1 200 OK"));
        let state: serde_json::Value =
            serde_json::from_str(response.split_once("\r\n\r\n").unwrap().1).unwrap();
        assert_eq!(state, json!({"revision":12,"error":"rebuilt"}));

        let clients = (0..MAX_CONNECTIONS + 2)
            .map(|_| TcpStream::connect(address).unwrap())
            .collect::<Vec<_>>();
        connections
            .accept(&listener, &root.0, 12, None, true)
            .unwrap();
        assert_eq!(connections.workers.len(), MAX_CONNECTIONS);
        let (done, result) = std::sync::mpsc::channel();
        stop.store(true, Ordering::Release);
        let shutdown = std::thread::spawn(move || {
            drop(connections);
            done.send(()).unwrap();
        });
        result
            .recv_timeout(Duration::from_secs(2))
            .expect("stop must cancel pending socket reads");
        shutdown.join().unwrap();
        drop((clients, stalled));
    }

    #[test]
    fn a_nonreading_client_cannot_renew_the_response_deadline() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let client = TcpStream::connect(address).unwrap();
        let (done, result) = std::sync::mpsc::channel();
        let worker = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut connection = Connection {
                socket: &mut stream,
                stop: &AtomicBool::new(false),
                deadline: Instant::now() + Duration::from_millis(100),
            };
            // Do not assume an OS-specific socket buffer size. Continuous
            // successful partial writes must not renew this response budget.
            let bytes = [b'x'; 65_536];
            loop {
                if let Err(error) = connection.write_all(&bytes) {
                    done.send(error.to_string()).unwrap();
                    break;
                }
            }
        });
        let outcome = result.recv_timeout(Duration::from_secs(2));
        drop(client);
        worker.join().unwrap();
        assert!(
            outcome
                .expect("response must expire")
                .contains("HTTP phase deadline")
        );
    }
}