|
| 1 | +//! A tiny PAC (proxy auto-config) server for the `pac` proxy mode. It serves one |
| 2 | +//! static PAC over HTTP on loopback that points browsers at the core's local http + |
| 3 | +//! socks inbound, with a DIRECT fallback for loopback/plain hosts. There is only one |
| 4 | +//! server per process, so it is held in a module global rather than on the platform. |
| 5 | +//! Like the rest of the OS-proxy layer it runs in the GUI process, not the helper. |
| 6 | +
|
| 7 | +use std::sync::Mutex; |
| 8 | +use std::time::Duration; |
| 9 | + |
| 10 | +use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 11 | +use tokio::net::TcpListener; |
| 12 | +use tokio::task::JoinHandle; |
| 13 | + |
| 14 | +/// The loopback port the PAC is served on (socks 10808 / http 10809 / pac 10811). |
| 15 | +pub const DEFAULT_PAC_PORT: u16 = 10811; |
| 16 | + |
| 17 | +static SERVER: Mutex<Option<JoinHandle<()>>> = Mutex::new(None); |
| 18 | + |
| 19 | +/// The PAC script pointing at the local proxy, DIRECT for loopback/plain hosts. |
| 20 | +fn build_pac(http_port: u16, socks_port: u16) -> String { |
| 21 | + format!( |
| 22 | + "function FindProxyForURL(url, host) {{\n \ |
| 23 | + if (isPlainHostName(host) || host == \"localhost\" || shExpMatch(host, \"127.*\")) \ |
| 24 | + return \"DIRECT\";\n \ |
| 25 | + return \"PROXY 127.0.0.1:{http_port}; SOCKS5 127.0.0.1:{socks_port}; DIRECT\";\n}}\n" |
| 26 | + ) |
| 27 | +} |
| 28 | + |
| 29 | +/// Start (replacing any prior) the PAC server and return the URL to hand the OS, or |
| 30 | +/// `None` if the port could not be bound. |
| 31 | +pub async fn start(http_port: u16, socks_port: u16) -> Option<String> { |
| 32 | + stop().await; |
| 33 | + let listener = TcpListener::bind(("127.0.0.1", DEFAULT_PAC_PORT)) |
| 34 | + .await |
| 35 | + .ok()?; |
| 36 | + let pac = build_pac(http_port, socks_port); |
| 37 | + let handle = tokio::spawn(serve(listener, pac)); |
| 38 | + *SERVER.lock().unwrap() = Some(handle); |
| 39 | + Some(format!("http://127.0.0.1:{DEFAULT_PAC_PORT}/proxy.pac")) |
| 40 | +} |
| 41 | + |
| 42 | +/// Stop the PAC server if running. Idempotent. Awaits the aborted task so the |
| 43 | +/// listener is truly dropped before a caller re-binds the port (restart with new |
| 44 | +/// ports). |
| 45 | +pub async fn stop() { |
| 46 | + let handle = SERVER.lock().unwrap().take(); |
| 47 | + if let Some(h) = handle { |
| 48 | + h.abort(); |
| 49 | + let _ = h.await; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/// Answer every connection with the same PAC document until the task is aborted. |
| 54 | +async fn serve(listener: TcpListener, pac: String) { |
| 55 | + let body = pac.into_bytes(); |
| 56 | + let response = format!( |
| 57 | + "HTTP/1.0 200 OK\r\nContent-Type: application/x-ns-proxy-autoconfig\r\n\ |
| 58 | + Content-Length: {}\r\nConnection: close\r\n\r\n", |
| 59 | + body.len() |
| 60 | + ); |
| 61 | + loop { |
| 62 | + let Ok((mut sock, _)) = listener.accept().await else { |
| 63 | + // Transient accept errors (EMFILE, …) mustn't spin the loop hot. |
| 64 | + tokio::time::sleep(Duration::from_millis(100)).await; |
| 65 | + continue; |
| 66 | + }; |
| 67 | + let head = response.clone(); |
| 68 | + let body = body.clone(); |
| 69 | + tokio::spawn(async move { |
| 70 | + // Drain the request line so the client doesn't see a reset before the body. |
| 71 | + let mut buf = [0u8; 1024]; |
| 72 | + let _ = sock.read(&mut buf).await; |
| 73 | + let _ = sock.write_all(head.as_bytes()).await; |
| 74 | + let _ = sock.write_all(&body).await; |
| 75 | + let _ = sock.flush().await; |
| 76 | + }); |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +#[cfg(test)] |
| 81 | +mod tests { |
| 82 | + use super::*; |
| 83 | + |
| 84 | + #[tokio::test] |
| 85 | + async fn serves_the_pac_and_stops() { |
| 86 | + let url = start(10809, 10808).await.expect("pac server binds"); |
| 87 | + assert_eq!(url, "http://127.0.0.1:10811/proxy.pac"); |
| 88 | + |
| 89 | + let mut sock = tokio::net::TcpStream::connect(("127.0.0.1", DEFAULT_PAC_PORT)) |
| 90 | + .await |
| 91 | + .unwrap(); |
| 92 | + sock.write_all(b"GET /proxy.pac HTTP/1.0\r\n\r\n") |
| 93 | + .await |
| 94 | + .unwrap(); |
| 95 | + let mut out = String::new(); |
| 96 | + sock.read_to_string(&mut out).await.unwrap(); |
| 97 | + assert!(out.starts_with("HTTP/1.0 200 OK")); |
| 98 | + assert!(out.contains("PROXY 127.0.0.1:10809; SOCKS5 127.0.0.1:10808; DIRECT")); |
| 99 | + |
| 100 | + // Stop frees the port for a re-bind (restart with new ports). |
| 101 | + stop().await; |
| 102 | + let again = start(1081, 1080).await.expect("rebind after stop"); |
| 103 | + assert!(again.ends_with("/proxy.pac")); |
| 104 | + stop().await; |
| 105 | + } |
| 106 | +} |
0 commit comments