1use std::fs::{self, OpenOptions};
18use std::io::{self, Write};
19use std::net::SocketAddr;
20use std::path::PathBuf;
21use std::pin::Pin;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Arc, Mutex, OnceLock};
24use std::task::{Poll, Waker};
25use std::time::{Duration, Instant};
26
27use futures_util::{Stream, stream::FuturesUnordered};
28use nagoya::reactor::{Addr, Reactor, TcpListener, TcpStream};
29use serde::Serialize;
30use serde_json::{Value, json};
31
32mod handoff;
33use handoff::{CommandQueue, QueueError, Reply, ResponseWait};
34pub use handoff::{
35 CommandReceiver, IntoValueIter, RecvError, RecvTimeoutError, TryRecvError, TryValueIter,
36 ValueIter, ValueReceiver,
37};
38
39const PROTOCOL_VERSION: u32 = 1;
40const MAX_REQUEST_BYTES: usize = 1024 * 1024;
41const MAX_HEADER_BYTES: usize = 16 * 1024;
42const MAX_SESSION_REQUEST_BYTES: usize = 16 * 1024;
43const COMMAND_TIMEOUT: Duration = Duration::from_secs(5);
44const HEADER_TIMEOUT: Duration = Duration::from_secs(1);
45const SESSION_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
46const MAX_PENDING_COMMANDS: usize = 64;
47const MAX_CONNECTIONS: usize = 64;
48
49struct Session {
50 id: String,
51 last_used: Instant,
52}
53
54#[derive(Default)]
55struct ActiveSession(Mutex<Option<Session>>);
56
57impl ActiveSession {
58 fn create(&self) -> io::Result<Option<String>> {
59 let mut active = self.0.lock().unwrap();
60 let now = Instant::now();
61 let expired = active
62 .as_ref()
63 .is_some_and(|session| now.duration_since(session.last_used) >= SESSION_IDLE_TIMEOUT);
64 if expired {
65 *active = None;
66 }
67 if active.is_some() {
68 return Ok(None);
69 }
70 let id = random_hex(32)?;
71 let session = Session {
72 id,
73 last_used: Instant::now(),
74 };
75 let id = session.id.clone();
76 *active = Some(session);
77 Ok(Some(id))
78 }
79
80 fn matches(&self, supplied: &str) -> bool {
81 let mut active = self.0.lock().unwrap();
82 let now = Instant::now();
83 let expired = active
84 .as_ref()
85 .is_some_and(|session| now.duration_since(session.last_used) >= SESSION_IDLE_TIMEOUT);
86 if expired {
87 *active = None;
88 return false;
89 }
90 if supplied.len() != 64
91 || !supplied
92 .bytes()
93 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
94 {
95 return false;
96 }
97 let Some(session) = active.as_mut() else {
98 return false;
99 };
100 if token_matches(Some(supplied), &session.id) {
101 session.last_used = now;
102 true
103 } else {
104 false
105 }
106 }
107
108 fn clear(&self) {
109 *self.0.lock().unwrap() = None;
110 }
111}
112
113#[derive(Debug, Clone)]
115pub struct ServerConfig {
116 pub bind_address: SocketAddr,
118 pub descriptor_path: PathBuf,
120 pub renderer_revision: String,
122}
123
124#[derive(Clone, Default)]
137pub struct ServiceWaker(Arc<OnceLock<Box<dyn Fn() + Send + Sync>>>);
138
139impl ServiceWaker {
140 pub fn set(&self, wake: impl Fn() + Send + Sync + 'static) {
142 if self.0.set(Box::new(wake)).is_ok() {
143 self.wake();
145 }
146 }
147
148 fn wake(&self) {
149 if let Some(wake) = self.0.get() {
150 wake();
151 }
152 }
153}
154
155impl std::fmt::Debug for ServiceWaker {
156 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 formatter
158 .debug_struct("ServiceWaker")
159 .field("installed", &self.0.get().is_some())
160 .finish()
161 }
162}
163
164#[derive(Debug)]
166pub struct ControlRequest {
167 pub method: String,
168 pub path: String,
169 pub body: Value,
170 reply: Arc<Reply>,
171}
172
173impl ControlRequest {
174 pub fn respond_arc(&self, response: Arc<ControlResponse>) -> Result<(), Arc<ControlResponse>> {
176 self.reply.complete(response)
177 }
178
179 pub fn respond(self, response: ControlResponse) -> Result<(), ControlResponse> {
181 self.respond_arc(Arc::new(response)).map_err(|response| {
182 Arc::try_unwrap(response).expect("failed response is uniquely owned")
183 })
184 }
185}
186
187impl Drop for ControlRequest {
188 fn drop(&mut self) {
189 self.reply.close_sender();
190 }
191}
192
193#[derive(Debug)]
195pub enum ControlResponse {
196 Success(Value),
197 Error {
198 error: String,
199 message: String,
200 stacktrace: String,
201 },
202}
203
204impl ControlResponse {
205 pub fn unsupported(message: impl Into<String>) -> Self {
206 Self::Error {
207 error: "unsupported operation".into(),
208 message: message.into(),
209 stacktrace: String::new(),
210 }
211 }
212}
213
214#[derive(Debug, Serialize)]
215#[serde(rename_all = "camelCase")]
216struct Descriptor<'a> {
217 pid: u32,
218 address: String,
219 protocol_version: u32,
220 renderer: &'static str,
221 renderer_revision: &'a str,
222}
223
224pub struct DebugServer {
226 address: SocketAddr,
227 token: String,
228 descriptor_path: PathBuf,
229 waker: ServiceWaker,
230 state: Option<Arc<ServerState>>,
231 task: Option<nagoya::JoinHandle<()>>,
232 reactor: Option<Reactor>,
233}
234
235struct CommandSink(Arc<CommandQueue>);
236
237impl CommandSink {
238 fn enqueue(&self, request: Arc<ControlRequest>) -> Result<(), &'static str> {
239 self.0.enqueue(request).map_err(|error| match error {
240 QueueError::Full => "renderer command queue is full",
241 QueueError::Closed => "renderer command channel is closed",
242 })
243 }
244
245 fn close(&self) {
246 self.0.close();
247 }
248}
249
250struct ServerState {
251 token: Arc<String>,
252 active_session: ActiveSession,
253 commands: CommandSink,
254 waker: ServiceWaker,
255 shutdown: AtomicBool,
256 stop_waker: Mutex<Option<Waker>>,
257}
258
259impl DebugServer {
260 pub fn start(config: ServerConfig) -> io::Result<(Self, ValueReceiver)> {
262 let (server, receiver) = Self::start_typed(config)?;
263 Ok((server, ValueReceiver(receiver)))
264 }
265
266 pub fn start_typed(config: ServerConfig) -> io::Result<(Self, CommandReceiver)> {
268 let queue = CommandQueue::new(MAX_PENDING_COMMANDS);
269 let server = Self::start_with_sink(config, CommandSink(Arc::clone(&queue)))?;
270 Ok((server, CommandReceiver(queue)))
271 }
272
273 pub fn start_typed_with_token(
275 config: ServerConfig,
276 token: impl Into<String>,
277 ) -> io::Result<(Self, CommandReceiver)> {
278 let queue = CommandQueue::new(MAX_PENDING_COMMANDS);
279 let server =
280 Self::start_with_sink_and_token(config, CommandSink(Arc::clone(&queue)), token.into())?;
281 Ok((server, CommandReceiver(queue)))
282 }
283
284 fn start_with_sink(config: ServerConfig, commands: CommandSink) -> io::Result<Self> {
285 Self::start_with_sink_and_token(config, commands, random_hex(32)?)
286 }
287
288 fn start_with_sink_and_token(
289 config: ServerConfig,
290 commands: CommandSink,
291 token: String,
292 ) -> io::Result<Self> {
293 if token.len() < 32 {
294 return Err(io::Error::new(
295 io::ErrorKind::InvalidInput,
296 "debug-control token must contain at least 32 bytes",
297 ));
298 }
299 if !config.bind_address.ip().is_loopback() {
300 return Err(io::Error::new(
301 io::ErrorKind::InvalidInput,
302 "debug control must bind to a loopback address",
303 ));
304 }
305 let reactor = Reactor::start().map_err(reactor_error)?;
306 let listener = TcpListener::bind(reactor_addr(config.bind_address), &reactor.handle())
307 .map_err(reactor_error)?;
308 let address = socket_addr(listener.local_addr().map_err(reactor_error)?)?;
309 let waker = ServiceWaker::default();
310 let state = Arc::new(ServerState {
311 token: Arc::new(token.clone()),
312 active_session: ActiveSession::default(),
313 commands,
314 waker: waker.clone(),
315 shutdown: AtomicBool::new(false),
316 stop_waker: Mutex::new(None),
317 });
318 write_descriptor(&config, address)?;
319 let task = nagoya::runtime::background().spawn(server_loop(listener, Arc::clone(&state)));
320 Ok(Self {
321 address,
322 token,
323 descriptor_path: config.descriptor_path,
324 waker,
325 state: Some(state),
326 task: Some(task),
327 reactor: Some(reactor),
328 })
329 }
330
331 pub fn waker(&self) -> ServiceWaker {
333 self.waker.clone()
334 }
335
336 pub fn address(&self) -> SocketAddr {
337 self.address
338 }
339
340 pub fn token(&self) -> &str {
341 &self.token
342 }
343
344 pub fn shutdown(mut self) {
345 self.stop();
346 }
347
348 fn stop(&mut self) {
349 if let Some(state) = self.state.take() {
350 state.commands.close();
351 state.shutdown.store(true, Ordering::Release);
352 let wake = state.stop_waker.lock().unwrap().take();
353 if let Some(wake) = wake {
354 wake.wake();
355 }
356 }
357 if let Some(task) = self.task.take() {
358 let _ = nagoya::block_on(task);
359 }
360 if let Some(reactor) = self.reactor.take() {
361 reactor.shutdown();
362 }
363 let _ = fs::remove_file(&self.descriptor_path);
364 }
365}
366
367impl Drop for DebugServer {
368 fn drop(&mut self) {
369 self.stop();
370 }
371}
372
373fn reactor_error(error: nagoya::reactor::Errno) -> io::Error {
374 io::Error::from_raw_os_error(error.0)
375}
376
377fn reactor_addr(address: SocketAddr) -> Addr {
378 match address {
379 SocketAddr::V4(address) => Addr::V4(address.ip().octets(), address.port()),
380 SocketAddr::V6(address) => {
381 Addr::V6Scoped(address.ip().octets(), address.port(), address.scope_id())
382 }
383 }
384}
385
386fn socket_addr(address: Addr) -> io::Result<SocketAddr> {
387 match address {
388 Addr::V4(ip, port) => Ok((std::net::Ipv4Addr::from(ip), port).into()),
389 Addr::V6(ip, port) => Ok((std::net::Ipv6Addr::from(ip), port).into()),
390 Addr::V6Scoped(ip, port, scope) => {
391 Ok(std::net::SocketAddrV6::new(std::net::Ipv6Addr::from(ip), port, 0, scope).into())
392 }
393 Addr::Path(_) => Err(io::Error::new(
394 io::ErrorKind::InvalidInput,
395 "expected a TCP address",
396 )),
397 }
398}
399
400fn random_hex(byte_len: usize) -> io::Result<String> {
401 let mut bytes = vec![0; byte_len];
402 getrandom::fill(&mut bytes).map_err(io::Error::other)?;
403 let mut output = String::with_capacity(byte_len * 2);
404 for byte in bytes {
405 use std::fmt::Write as _;
406 write!(output, "{byte:02x}").unwrap();
407 }
408 Ok(output)
409}
410
411fn write_descriptor(config: &ServerConfig, address: SocketAddr) -> io::Result<()> {
412 let descriptor = Descriptor {
413 pid: std::process::id(),
414 address: address.to_string(),
415 protocol_version: PROTOCOL_VERSION,
416 renderer: "blitz",
417 renderer_revision: &config.renderer_revision,
418 };
419 let bytes = serde_json::to_vec_pretty(&descriptor).map_err(io::Error::other)?;
420 if contains_environment_secret(config.descriptor_path.to_string_lossy().as_bytes())
421 || contains_environment_secret(&bytes)
422 {
423 return Err(io::Error::new(
424 io::ErrorKind::PermissionDenied,
425 "refusing to write a debug-control descriptor containing an environment secret",
426 ));
427 }
428 if let Some(parent) = config.descriptor_path.parent() {
429 fs::create_dir_all(parent)?;
430 }
431 let temporary = config
432 .descriptor_path
433 .with_extension(format!("tmp-{}", random_hex(8)?));
434 let result = (|| {
435 let mut options = OpenOptions::new();
436 options.write(true).create_new(true);
437 #[cfg(unix)]
438 {
439 use std::os::unix::fs::OpenOptionsExt;
440 options.mode(0o600);
441 }
442 let mut file = options.open(&temporary)?;
443 file.write_all(&bytes)?;
444 file.sync_all()?;
445 fs::rename(&temporary, &config.descriptor_path)
446 })();
447 if result.is_err() {
448 let _ = fs::remove_file(&temporary);
449 }
450 result
451}
452
453fn contains_environment_secret(content: &[u8]) -> bool {
454 std::env::vars_os().any(|(name, value)| {
455 let name = name.to_string_lossy().to_ascii_uppercase();
456 if !is_secret_environment_name(&name) {
457 return false;
458 }
459 let value = value.to_string_lossy();
460 if value.is_empty() {
461 return false;
462 }
463 let raw = value.as_bytes();
464 let encoded = serde_json::to_vec(value.as_ref()).unwrap_or_default();
465 content.windows(raw.len()).any(|part| part == raw)
466 || (!encoded.is_empty()
467 && content
468 .windows(encoded.len())
469 .any(|part| part == encoded.as_slice()))
470 })
471}
472
473fn is_secret_environment_name(name: &str) -> bool {
474 [
475 "PASSWORD",
476 "PASSWD",
477 "TOKEN",
478 "SECRET",
479 "SEED",
480 "PRIVATE_KEY",
481 "ACCESS_KEY",
482 "CREDENTIAL",
483 "COOKIE",
484 "JWT",
485 "SESSION",
486 ]
487 .iter()
488 .any(|needle| name.contains(needle))
489 || name.contains("_KEY")
490 || name.ends_with("KEY")
491}
492
493async fn server_loop(listener: TcpListener, state: Arc<ServerState>) {
494 let mut connections = FuturesUnordered::new();
495 std::future::poll_fn(|cx| {
496 {
497 let mut wake = state.stop_waker.lock().unwrap();
498 if state.shutdown.load(Ordering::Acquire) {
499 return Poll::Ready(());
500 }
501 *wake = Some(cx.waker().clone());
502 }
503 while let Poll::Ready(Some(())) = Pin::new(&mut connections).poll_next(cx) {}
504 if connections.len() <= MAX_CONNECTIONS {
507 match listener.poll_accept(cx) {
508 Poll::Ready(Ok((stream, _))) => {
509 let limited = connections.len() == MAX_CONNECTIONS;
510 connections.push(serve_connection(stream, Arc::clone(&state), limited));
511 cx.waker().wake_by_ref();
512 }
513 Poll::Ready(Err(_)) => {
514 state.commands.close();
515 return Poll::Ready(());
516 }
517 Poll::Pending => {}
518 }
519 }
520 Poll::Pending
521 })
522 .await;
523 drop(connections);
525}
526
527async fn serve_connection(mut stream: TcpStream, state: Arc<ServerState>, limited: bool) {
528 let response = if limited {
529 webdriver_error("unknown error", "debug-control connection limit reached")
530 } else {
531 match read_request(&mut stream, &state).await {
532 Ok(request) => route(request, &state).await,
533 Err(error) => webdriver_error("invalid argument", error.to_string()),
534 }
535 };
536 let _ = nagoya::time::timeout(COMMAND_TIMEOUT, write_response(&mut stream, response)).await;
537}
538
539#[derive(Debug)]
540struct HttpRequest {
541 method: String,
542 path: String,
543 body: Value,
544}
545
546async fn read_request(stream: &mut TcpStream, state: &ServerState) -> io::Result<HttpRequest> {
547 read_request_within(stream, state, COMMAND_TIMEOUT).await
548}
549
550async fn read_request_within(
551 stream: &mut TcpStream,
552 state: &ServerState,
553 within: Duration,
554) -> io::Result<HttpRequest> {
555 nagoya::time::timeout(within, read_request_inner(stream, state))
556 .await
557 .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
558}
559
560async fn read_request_inner(
561 stream: &mut TcpStream,
562 state: &ServerState,
563) -> io::Result<HttpRequest> {
564 let mut bytes = bytes::BytesMut::new();
565 let mut scratch = [0_u8; 4096];
566 let header_end = nagoya::time::timeout(
567 HEADER_TIMEOUT,
568 read_headers(stream, &mut bytes, &mut scratch),
569 )
570 .await
571 .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "header timed out"))??;
572 let headers = std::str::from_utf8(&bytes[..header_end - 4])
573 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "headers are not valid UTF-8"))?;
574 let mut lines = headers.split("\r\n");
575 let request_line = lines.next().unwrap_or_default();
576 let (method, path) = parse_request_line(request_line)?;
577
578 let mut header_fields = Vec::new();
579 for line in lines {
580 let Some((name, value)) = line.split_once(':') else {
581 return Err(io::Error::new(
582 io::ErrorKind::InvalidData,
583 "invalid header line",
584 ));
585 };
586 if !is_http_token(name)
587 || value
588 .bytes()
589 .any(|byte| byte == 0x7f || (byte < 0x20 && byte != b'\t'))
590 {
591 return Err(io::Error::new(
592 io::ErrorKind::InvalidData,
593 "invalid header line",
594 ));
595 }
596 let value = value.trim_matches(|character| character == ' ' || character == '\t');
597 header_fields.push((name, value));
598 }
599
600 let mut host: Option<&str> = None;
601 for (name, value) in &header_fields {
602 if name.eq_ignore_ascii_case("host") && host.replace(*value).is_some() {
603 return Err(io::Error::new(
604 io::ErrorKind::InvalidData,
605 "exactly one Host header is required",
606 ));
607 }
608 }
609 let Some(host) = host else {
610 return Err(io::Error::new(
611 io::ErrorKind::InvalidData,
612 "exactly one Host header is required",
613 ));
614 };
615 if !valid_loopback_host(host) {
616 return Err(io::Error::new(
617 io::ErrorKind::InvalidData,
618 "Host must be a loopback address",
619 ));
620 }
621
622 let mut content_length = None;
623 for (name, value) in &header_fields {
624 if name.eq_ignore_ascii_case("origin") {
625 return Err(io::Error::new(
626 io::ErrorKind::InvalidData,
627 "Origin headers are not supported",
628 ));
629 }
630 if name.eq_ignore_ascii_case("transfer-encoding") {
631 return Err(io::Error::new(
632 io::ErrorKind::InvalidData,
633 "Transfer-Encoding is not supported",
634 ));
635 }
636 if name.eq_ignore_ascii_case("content-length") {
637 if content_length.is_some() {
638 return Err(io::Error::new(
639 io::ErrorKind::InvalidData,
640 "duplicate Content-Length header",
641 ));
642 }
643 if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
644 return Err(io::Error::new(
645 io::ErrorKind::InvalidData,
646 "invalid Content-Length header",
647 ));
648 }
649 content_length = Some(value.parse::<usize>().map_err(|_| {
650 io::Error::new(io::ErrorKind::InvalidData, "invalid Content-Length header")
651 })?);
652 }
653 }
654 let content_length = content_length.unwrap_or(0);
655
656 let authorized_session = if let Some((session_id, _)) = session_path(&path) {
657 if !state.active_session.matches(session_id) {
658 return Ok(HttpRequest {
659 method,
660 path,
661 body: Value::Null,
662 });
663 }
664 true
665 } else {
666 false
667 };
668
669 let body_end = header_end
670 .checked_add(content_length)
671 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "request size overflow"))?;
672 let max_request_bytes = if authorized_session {
673 MAX_REQUEST_BYTES
674 } else {
675 MAX_SESSION_REQUEST_BYTES
676 };
677 if body_end > max_request_bytes {
678 return Err(io::Error::new(
679 io::ErrorKind::InvalidData,
680 "request is too large",
681 ));
682 }
683 if bytes.len() > body_end {
684 return Err(io::Error::new(
685 io::ErrorKind::InvalidData,
686 "request contains bytes after body",
687 ));
688 }
689 while bytes.len() < body_end {
690 let chunk_limit = scratch.len();
691 read_more(
692 stream,
693 &mut bytes,
694 &mut scratch,
695 body_end,
696 chunk_limit,
697 "connection closed before body",
698 )
699 .await?;
700 }
701 let body = if content_length == 0 {
702 Value::Null
703 } else {
704 serde_json::from_slice(&bytes[header_end..body_end]).map_err(|_| {
705 io::Error::new(io::ErrorKind::InvalidData, "request body is not valid JSON")
706 })?
707 };
708 Ok(HttpRequest { method, path, body })
709}
710
711async fn read_headers(
712 stream: &mut TcpStream,
713 bytes: &mut bytes::BytesMut,
714 scratch: &mut [u8; 4096],
715) -> io::Result<usize> {
716 loop {
717 if bytes.ends_with(b"\r\n\r\n") {
718 let header_end = bytes.len();
719 if header_end > MAX_HEADER_BYTES {
720 return Err(io::Error::new(
721 io::ErrorKind::InvalidData,
722 "request headers are too large",
723 ));
724 }
725 return Ok(header_end);
726 }
727 if bytes.len() >= MAX_HEADER_BYTES {
728 return Err(io::Error::new(
729 io::ErrorKind::InvalidData,
730 "request headers are too large",
731 ));
732 }
733 read_more(
734 stream,
735 bytes,
736 scratch,
737 MAX_HEADER_BYTES,
738 1,
739 "connection closed before headers",
740 )
741 .await?;
742 }
743}
744
745async fn read_more(
746 stream: &mut TcpStream,
747 bytes: &mut bytes::BytesMut,
748 scratch: &mut [u8; 4096],
749 stage_limit: usize,
750 chunk_limit: usize,
751 eof_message: &'static str,
752) -> io::Result<usize> {
753 let remaining = stage_limit
754 .checked_sub(bytes.len())
755 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "request is too large"))?;
756 if remaining == 0 || chunk_limit == 0 {
757 return Err(io::Error::new(
758 io::ErrorKind::InvalidData,
759 "request is too large",
760 ));
761 }
762 let allowed = remaining.min(chunk_limit).min(scratch.len());
763 let count = std::future::poll_fn(|cx| stream.poll_read(cx, &mut scratch[..allowed]))
764 .await
765 .map_err(reactor_error)?;
766 if count == 0 {
767 return Err(io::Error::new(io::ErrorKind::UnexpectedEof, eof_message));
768 }
769 bytes.extend_from_slice(&scratch[..count]);
770 Ok(count)
771}
772
773fn parse_request_line(line: &str) -> io::Result<(String, String)> {
774 let mut parts = line.split(' ');
775 let method = parts.next().unwrap_or_default();
776 let path = parts.next().unwrap_or_default();
777 let version = parts.next().unwrap_or_default();
778 if parts.next().is_some()
779 || !is_http_token(method)
780 || !valid_origin_target(path)
781 || (version != "HTTP/1.0" && version != "HTTP/1.1")
782 {
783 return Err(io::Error::new(
784 io::ErrorKind::InvalidData,
785 "invalid request line",
786 ));
787 }
788 Ok((method.to_string(), path.to_string()))
789}
790
791fn is_http_token(value: &str) -> bool {
792 !value.is_empty()
793 && value.bytes().all(|byte| {
794 byte.is_ascii_alphanumeric()
795 || matches!(
796 byte,
797 b'!' | b'#'
798 | b'$'
799 | b'%'
800 | b'&'
801 | b'\''
802 | b'*'
803 | b'+'
804 | b'-'
805 | b'.'
806 | b'^'
807 | b'_'
808 | b'`'
809 | b'|'
810 | b'~'
811 )
812 })
813}
814
815fn valid_origin_target(target: &str) -> bool {
816 if !target.starts_with('/') || !target.is_ascii() {
817 return false;
818 }
819 let bytes = target.as_bytes();
820 let mut index = 0;
821 while index < bytes.len() {
822 let byte = bytes[index];
823 if byte == b'%' {
824 if index + 2 >= bytes.len()
825 || !bytes[index + 1].is_ascii_hexdigit()
826 || !bytes[index + 2].is_ascii_hexdigit()
827 {
828 return false;
829 }
830 index += 3;
831 continue;
832 }
833 if !(byte.is_ascii_alphanumeric()
834 || matches!(
835 byte,
836 b'-' | b'.'
837 | b'_'
838 | b'~'
839 | b'!'
840 | b'$'
841 | b'&'
842 | b'\''
843 | b'('
844 | b')'
845 | b'*'
846 | b'+'
847 | b','
848 | b';'
849 | b'='
850 | b':'
851 | b'@'
852 | b'/'
853 | b'?'
854 ))
855 {
856 return false;
857 }
858 index += 1;
859 }
860 true
861}
862
863fn valid_loopback_host(value: &str) -> bool {
864 if value.is_empty()
865 || !value.is_ascii()
866 || value.bytes().any(|byte| {
867 byte.is_ascii_whitespace() || matches!(byte, b',' | b'/' | b'\\' | b'@' | b'?' | b'#')
868 })
869 {
870 return false;
871 }
872 if let Some(bracketed) = value.strip_prefix('[') {
873 let Some((address, suffix)) = bracketed.split_once(']') else {
874 return false;
875 };
876 if address.contains('[') || suffix.contains(']') {
877 return false;
878 }
879 let valid_port = if suffix.is_empty() {
880 true
881 } else {
882 suffix.strip_prefix(':').is_some_and(valid_decimal_port)
883 };
884 return valid_port
885 && address
886 .parse::<std::net::Ipv6Addr>()
887 .is_ok_and(|address| address.is_loopback());
888 }
889 if value.contains('[') || value.contains(']') {
890 return false;
891 }
892 let (host, port) = match value.split_once(':') {
893 Some((host, port)) => {
894 if host.contains(':') || port.contains(':') {
895 return false;
896 }
897 (host, Some(port))
898 }
899 None => (value, None),
900 };
901 if port.is_some_and(|port| !valid_decimal_port(port)) {
902 return false;
903 }
904 host.eq_ignore_ascii_case("localhost")
905 || host
906 .parse::<std::net::Ipv4Addr>()
907 .is_ok_and(|address| address.is_loopback())
908}
909
910fn valid_decimal_port(value: &str) -> bool {
911 !value.is_empty()
912 && value.bytes().all(|byte| byte.is_ascii_digit())
913 && value.parse::<u16>().is_ok()
914}
915
916async fn route(request: HttpRequest, state: &ServerState) -> Value {
917 let token = state.token.as_str();
918 let active_session = &state.active_session;
919 if request.method == "GET" && request.path == "/status" {
920 return json!({"value": {
921 "ready": true,
922 "message": "Blitz debug control is ready",
923 "protocolVersion": PROTOCOL_VERSION,
924 }});
925 }
926
927 if request.method == "POST" && request.path == "/session" {
928 let supplied_token = request
929 .body
930 .pointer("/capabilities/alwaysMatch/blitz:token")
931 .and_then(Value::as_str);
932 if !token_matches(supplied_token, token) {
933 return webdriver_error("invalid argument", "invalid blitz:token capability");
934 }
935 let session_id = match active_session.create() {
936 Ok(Some(value)) => value,
937 Ok(None) => {
938 return webdriver_error("session not created", "only one session is supported");
939 }
940 Err(error) => return webdriver_error("unknown error", error.to_string()),
941 };
942 return json!({"value": {
943 "sessionId": session_id,
944 "capabilities": {
945 "browserName": "blitz",
946 "blitz:protocolVersion": PROTOCOL_VERSION,
947 }
948 }});
949 }
950
951 let Some((session_id, command_path)) = session_path(&request.path) else {
952 return webdriver_error("unknown command", "unknown debug-control route");
953 };
954 if !active_session.matches(session_id) {
955 return webdriver_error("invalid session id", "session is not active");
956 }
957 if request.method == "DELETE" && command_path.is_empty() {
958 active_session.clear();
959 return json!({"value": null});
960 }
961
962 let reply = Reply::new();
963 let response = ResponseWait::new(&reply);
964 let control_request = Arc::new(ControlRequest {
965 method: request.method,
966 path: command_path.to_string(),
967 body: request.body,
968 reply,
969 });
970 if let Err(message) = state.commands.enqueue(control_request) {
971 return webdriver_error("unknown error", message);
972 }
973 state.waker.wake();
974 match nagoya::time::timeout(COMMAND_TIMEOUT, response).await {
975 Ok(Ok(response)) => match response.as_ref() {
976 ControlResponse::Success(value) => json!({"value": value}),
977 ControlResponse::Error {
978 error,
979 message,
980 stacktrace,
981 } => json!({"value": {
982 "error": error,
983 "message": message,
984 "stacktrace": stacktrace,
985 }}),
986 },
987 Err(_) => webdriver_error("timeout", "renderer command timed out"),
988 Ok(Err(())) => webdriver_error("unknown error", "renderer response channel is closed"),
989 }
990}
991
992fn token_matches(supplied: Option<&str>, expected: &str) -> bool {
995 let supplied = supplied.unwrap_or_default().as_bytes();
996 let expected = expected.as_bytes();
997 let mut difference = supplied.len() ^ expected.len();
998 for (index, expected_byte) in expected.iter().enumerate() {
999 difference |= usize::from(*expected_byte ^ supplied.get(index).copied().unwrap_or(0));
1000 }
1001 difference == 0
1002}
1003
1004fn session_path(path: &str) -> Option<(&str, &str)> {
1005 let remainder = path.strip_prefix("/session/")?;
1006 let (session_id, command) = remainder.split_once('/').unwrap_or((remainder, ""));
1007 Some((session_id, command))
1008}
1009
1010fn webdriver_error(error: &str, message: impl Into<String>) -> Value {
1011 json!({"value": {
1012 "error": error,
1013 "message": message.into(),
1014 "stacktrace": "",
1015 }})
1016}
1017
1018async fn write_response(stream: &mut TcpStream, body: Value) -> io::Result<()> {
1019 let bytes = serde_json::to_vec(&body).map_err(io::Error::other)?;
1020 let status = match body.pointer("/value/error").and_then(Value::as_str) {
1021 None => "200 OK",
1022 Some("unknown command" | "invalid session id") => "404 Not Found",
1023 Some("timeout" | "unknown error") => "500 Internal Server Error",
1024 Some(_) => "400 Bad Request",
1025 };
1026 let header = format!(
1027 "HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1028 bytes.len()
1029 );
1030 stream
1031 .write_all_vectored(header.as_bytes(), &bytes)
1032 .await
1033 .map_err(reactor_error)
1034}