1use std::collections::HashMap;
26use std::io::{Read, Write};
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, Mutex};
29use std::time::Duration;
30
31use crate::application::Application;
32use crate::core::New;
33use crate::header::Header;
34use crate::range::Range;
35use crate::request::Request;
36use crate::response::Response;
37use crate::server::ConnectionInfo;
38
39pub(crate) const VERSION: u8 = 1;
42pub(crate) const BEGIN_REQUEST: u8 = 1;
43pub(crate) const END_REQUEST: u8 = 3;
44pub(crate) const PARAMS: u8 = 4;
45pub(crate) const STDIN: u8 = 5;
46pub(crate) const STDOUT: u8 = 6;
47pub(crate) const STDERR: u8 = 7;
48const RESPONDER: u16 = 1;
49const KEEP_CONN: u8 = 1;
50const MAX_CONTENT: usize = 65535;
51
52#[derive(Debug, Clone, PartialEq)]
54pub struct Record {
55 pub kind: u8,
56 pub request_id: u16,
57 pub content: Vec<u8>,
58}
59
60pub fn encode_record(out: &mut Vec<u8>, kind: u8, request_id: u16, content: &[u8]) {
62 debug_assert!(content.len() <= MAX_CONTENT);
63 let padding = (8 - content.len() % 8) % 8;
64 out.extend_from_slice(&[VERSION, kind]);
65 out.extend_from_slice(&request_id.to_be_bytes());
66 out.extend_from_slice(&(content.len() as u16).to_be_bytes());
67 out.extend_from_slice(&[padding as u8, 0]);
68 out.extend_from_slice(content);
69 out.extend(std::iter::repeat_n(0u8, padding));
70}
71
72pub fn encode_stream(out: &mut Vec<u8>, kind: u8, request_id: u16, data: &[u8]) {
74 for chunk in data.chunks(MAX_CONTENT) {
75 encode_record(out, kind, request_id, chunk);
76 }
77 encode_record(out, kind, request_id, &[]);
78}
79
80pub fn encode_params(params: &[(String, String)]) -> Vec<u8> {
83 let mut out = Vec::new();
84 let length = |out: &mut Vec<u8>, n: usize| {
85 if n < 128 {
86 out.push(n as u8);
87 } else {
88 out.extend_from_slice(&((n as u32) | 0x8000_0000).to_be_bytes());
89 }
90 };
91 for (name, value) in params {
92 length(&mut out, name.len());
93 length(&mut out, value.len());
94 out.extend_from_slice(name.as_bytes());
95 out.extend_from_slice(value.as_bytes());
96 }
97 out
98}
99
100pub fn decode_params(mut data: &[u8]) -> Option<Vec<(String, String)>> {
102 fn length(data: &mut &[u8]) -> Option<usize> {
103 let first = *data.first()?;
104 if first < 128 {
105 *data = &data[1..];
106 return Some(first as usize);
107 }
108 let bytes: [u8; 4] = data.get(..4)?.try_into().ok()?;
109 *data = &data[4..];
110 Some((u32::from_be_bytes(bytes) & 0x7fff_ffff) as usize)
111 }
112 let mut out = Vec::new();
113 while !data.is_empty() {
114 let (n, v) = (length(&mut data)?, length(&mut data)?);
115 if data.len() < n.checked_add(v)? {
116 return None;
117 }
118 out.push((String::from_utf8_lossy(&data[..n]).into_owned(), String::from_utf8_lossy(&data[n..n + v]).into_owned()));
119 data = &data[n + v..];
120 }
121 Some(out)
122}
123
124pub fn read_record(reader: &mut impl Read) -> std::io::Result<Option<Record>> {
126 let mut header = [0u8; 8];
127 match reader.read(&mut header[..1])? {
128 0 => return Ok(None),
129 _ => reader.read_exact(&mut header[1..])?,
130 }
131 if header[0] != VERSION {
132 return Err(std::io::Error::other(format!("FastCGI: unsupported record version {}", header[0])));
133 }
134 let length = u16::from_be_bytes([header[4], header[5]]) as usize;
135 let mut content = vec![0u8; length + header[6] as usize];
136 reader.read_exact(&mut content)?;
137 content.truncate(length);
138 Ok(Some(Record { kind: header[1], request_id: u16::from_be_bytes([header[2], header[3]]), content }))
139}
140
141pub fn parse_records(mut data: &[u8]) -> Option<Vec<Record>> {
144 let mut out = Vec::new();
145 while !data.is_empty() {
146 out.push(read_record(&mut data).ok()??);
147 }
148 Some(out)
149}
150
151fn header_end(data: &[u8]) -> Option<usize> {
155 let crlf = data.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4);
156 let lf = data.windows(2).position(|w| w == b"\n\n").map(|i| i + 2);
157 match (crlf, lf) {
158 (Some(a), Some(b)) => Some(a.min(b)),
159 (a, b) => a.or(b),
160 }
161}
162
163pub fn parse_cgi_headers(block: &[u8]) -> Result<(u16, String, Vec<(String, String)>), String> {
166 let text = String::from_utf8_lossy(block);
167 let mut status: Option<(u16, String)> = None;
168 let mut headers = Vec::new();
169 for line in text.lines() {
170 let line = line.trim_end_matches('\r');
171 if line.is_empty() {
172 continue;
173 }
174 let Some((name, value)) = line.split_once(':') else {
175 return Err(format!("FastCGI: bad header line {line:?}"));
176 };
177 let (name, value) = (name.trim(), value.trim());
178 if name.is_empty() || name.bytes().any(|b| !(b.is_ascii_graphic()) || b == b':') || value.contains(['\r', '\n']) {
179 return Err(format!("FastCGI: bad header line {line:?}"));
180 }
181 if name.eq_ignore_ascii_case("status") {
182 let (code, reason) = value.split_once(' ').unwrap_or((value, ""));
183 let code: u16 = code.parse().ok().filter(|c| (100..1000).contains(c)).ok_or_else(|| format!("FastCGI: bad Status {value:?}"))?;
184 status = Some((code, reason.trim().to_string()));
185 } else {
186 headers.push((name.to_string(), value.to_string()));
187 }
188 }
189 let (code, reason) = match status {
190 Some(s) => s,
191 None if headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("location")) => (302, String::new()),
192 None => (200, String::new()),
193 };
194 Ok((code, reason, headers))
195}
196
197fn reason_for(code: u16) -> String {
198 Response::status_code_reason_phrase_list()
199 .iter()
200 .find(|s| *s.status_code == code as i16)
201 .map(|s| s.reason_phrase.to_string())
202 .unwrap_or_else(|| if code < 400 { "OK".to_string() } else { "Error".to_string() })
203}
204
205#[derive(Debug, Clone, PartialEq)]
209pub enum Address {
210 Tcp(String),
211 #[cfg(unix)]
212 Unix(PathBuf),
213}
214
215impl Address {
216 pub fn parse(address: &str) -> Result<Address, String> {
219 let address = address.trim();
220 if let Some(path) = address.strip_prefix("unix:").or_else(|| address.starts_with('/').then_some(address)) {
221 #[cfg(unix)]
222 return Ok(Address::Unix(PathBuf::from(path)));
223 #[cfg(not(unix))]
224 return Err(format!("FastCGI: Unix sockets aren't available here ({path})"));
225 }
226 let hostport = address.strip_prefix("tcp://").unwrap_or(address);
227 if hostport.rsplit_once(':').is_some_and(|(h, p)| !h.is_empty() && p.parse::<u16>().is_ok()) {
228 Ok(Address::Tcp(hostport.to_string()))
229 } else {
230 Err(format!("FastCGI: address {address:?}: expected unix:/path or host:port"))
231 }
232 }
233}
234
235trait Stream: Read + Write + Send {}
236impl<T: Read + Write + Send> Stream for T {}
237
238struct Conn {
239 stream: Box<dyn Stream>,
240}
241
242impl Conn {
243 fn open(address: &Address, connect: Duration, io: Duration) -> std::io::Result<Conn> {
244 match address {
245 Address::Tcp(hostport) => {
246 let mut last = std::io::Error::other(format!("no address for {hostport}"));
247 for addr in std::net::ToSocketAddrs::to_socket_addrs(hostport.as_str())? {
248 match std::net::TcpStream::connect_timeout(&addr, connect) {
249 Ok(s) => {
250 s.set_read_timeout(Some(io))?;
251 s.set_write_timeout(Some(io))?;
252 let _ = s.set_nodelay(true);
253 return Ok(Conn { stream: Box::new(s) });
254 }
255 Err(e) => last = e,
256 }
257 }
258 Err(last)
259 }
260 #[cfg(unix)]
261 Address::Unix(path) => {
262 let s = std::os::unix::net::UnixStream::connect(path)?;
263 s.set_read_timeout(Some(io))?;
264 s.set_write_timeout(Some(io))?;
265 Ok(Conn { stream: Box::new(s) })
266 }
267 }
268 }
269}
270
271struct Pool {
273 idle: Mutex<Vec<Conn>>,
274 max: usize,
275}
276
277#[derive(Debug, Clone)]
281pub struct FastCgiConfig {
282 pub address: String,
284 pub root: PathBuf,
286 pub index: Vec<String>,
288 pub split_path: String,
290 pub front_controller: String,
292 pub params: Vec<(String, String)>,
294 pub connect_timeout: Duration,
295 pub read_timeout: Duration,
297 pub max_idle: usize,
299}
300
301impl FastCgiConfig {
302 pub fn new(address: impl Into<String>, root: impl Into<PathBuf>) -> FastCgiConfig {
303 FastCgiConfig {
304 address: address.into(),
305 root: root.into(),
306 index: vec!["index.php".to_string()],
307 split_path: ".php".to_string(),
308 front_controller: "index.php".to_string(),
309 params: Vec::new(),
310 connect_timeout: Duration::from_secs(5),
311 read_timeout: Duration::from_secs(60),
312 max_idle: 16,
313 }
314 }
315}
316
317#[derive(Clone)]
319pub struct FastCgi {
320 inner: Arc<Inner>,
321}
322
323struct Inner {
324 config: FastCgiConfig,
325 address: Address,
326 root: PathBuf,
327 pool: Pool,
328 statics: Option<Arc<dyn Application + Send + Sync>>,
329}
330
331#[derive(Debug, PartialEq)]
333pub(crate) enum Target {
334 Script { script_name: String, filename: PathBuf, path_info: String },
336 Static,
338 Redirect(String),
340 NotFound,
341}
342
343impl FastCgi {
344 pub fn new(config: FastCgiConfig) -> Result<FastCgi, String> {
346 let address = Address::parse(&config.address)?;
347 let root = config.root.canonicalize().map_err(|e| format!("FastCGI root {}: {e}", config.root.display()))?;
348 let max = config.max_idle;
349 Ok(FastCgi { inner: Arc::new(Inner { config, address, root, pool: Pool { idle: Mutex::new(Vec::new()), max }, statics: None }) })
350 }
351
352 pub fn with_static(self, app: Arc<dyn Application + Send + Sync>) -> FastCgi {
354 let inner = &self.inner;
355 FastCgi {
356 inner: Arc::new(Inner {
357 config: inner.config.clone(),
358 address: inner.address.clone(),
359 root: inner.root.clone(),
360 pool: Pool { idle: Mutex::new(Vec::new()), max: inner.pool.max },
361 statics: Some(app),
362 }),
363 }
364 }
365
366 fn is_script(&self, name: &str) -> bool {
367 !self.inner.config.split_path.is_empty() && name.ends_with(&self.inner.config.split_path)
368 }
369
370 fn file_under_root(&self, relative: &str) -> Option<PathBuf> {
372 let path = self.inner.root.join(relative.trim_start_matches('/'));
373 let real = path.canonicalize().ok()?;
374 (real.starts_with(&self.inner.root) && real.is_file()).then_some(real)
375 }
376
377 pub(crate) fn resolve(&self, uri_path: &str) -> Target {
378 let decoded = crate::url::URL::percent_decode(uri_path);
379 let segments: Vec<&str> = decoded.split('/').collect();
380 if segments.iter().any(|s| *s == ".." || (s.starts_with('.') && *s != ".well-known")) || decoded.contains('\0') {
383 return Target::NotFound;
384 }
385 let path = if decoded.starts_with('/') { decoded.clone() } else { format!("/{decoded}") };
386 let full = self.inner.root.join(path.trim_start_matches('/'));
387 if let Some(file) = self.file_under_root(&path) {
389 if self.is_script(&path) {
390 return Target::Script { script_name: path, filename: file, path_info: String::new() };
391 }
392 return Target::Static;
393 }
394 if full.is_dir() && full.canonicalize().is_ok_and(|r| r.starts_with(&self.inner.root)) {
396 for index in &self.inner.config.index {
397 let script = format!("{}/{}", path.trim_end_matches('/'), index);
398 if let Some(file) = self.file_under_root(&script) {
399 if !path.ends_with('/') {
400 return Target::Redirect(format!("{path}/"));
401 }
402 if self.is_script(&script) {
403 return Target::Script { script_name: script, filename: file, path_info: String::new() };
404 }
405 return Target::Static;
406 }
407 }
408 }
409 let split = &self.inner.config.split_path;
411 if !split.is_empty() {
412 let mut from = 0;
413 while let Some(found) = path[from..].find(split.as_str()) {
414 let end = from + found + split.len();
415 if path[end..].starts_with('/') {
416 let script = &path[..end];
417 if let Some(file) = self.file_under_root(script) {
418 return Target::Script { script_name: script.to_string(), filename: file, path_info: path[end..].to_string() };
419 }
420 }
421 from = end;
422 }
423 }
424 let front = &self.inner.config.front_controller;
426 if !front.is_empty() {
427 let script = format!("/{}", front.trim_start_matches('/'));
428 if let Some(file) = self.file_under_root(&script) {
429 return Target::Script { script_name: script, filename: file, path_info: String::new() };
430 }
431 }
432 Target::NotFound
433 }
434
435 pub(crate) fn params(&self, request: &Request, connection: &ConnectionInfo, script_name: &str, filename: &Path, path_info: &str) -> Vec<(String, String)> {
437 let (_, query) = request.request_uri.split_once('?').unwrap_or((&request.request_uri, ""));
438 let host = request.header("Host").map(|h| h.value.to_string()).unwrap_or_default();
439 let server_name = match host.rsplit_once(':') {
440 Some((h, p)) if p.bytes().all(|b| b.is_ascii_digit()) && !h.ends_with(':') => h.to_string(),
441 _ => host.clone(),
442 };
443 let root = self.inner.root.to_string_lossy().to_string();
444 let mut params: Vec<(String, String)> = vec![
445 ("GATEWAY_INTERFACE".into(), "CGI/1.1".into()),
446 ("SERVER_SOFTWARE".into(), format!("rws/{}", env!("CARGO_PKG_VERSION"))),
447 ("SERVER_PROTOCOL".into(), "HTTP/1.1".into()),
448 ("REQUEST_METHOD".into(), request.method.clone()),
449 ("REQUEST_URI".into(), request.request_uri.clone()),
450 ("QUERY_STRING".into(), query.to_string()),
451 ("SCRIPT_NAME".into(), script_name.to_string()),
452 ("SCRIPT_FILENAME".into(), filename.to_string_lossy().to_string()),
453 ("DOCUMENT_ROOT".into(), root.clone()),
454 ("DOCUMENT_URI".into(), format!("{script_name}{path_info}")),
455 ("PATH_INFO".into(), path_info.to_string()),
456 ("REMOTE_ADDR".into(), connection.client.ip.clone()),
457 ("REMOTE_PORT".into(), connection.client.port.to_string()),
458 ("SERVER_ADDR".into(), connection.server.ip.clone()),
459 ("SERVER_PORT".into(), connection.server.port.to_string()),
460 ("SERVER_NAME".into(), server_name),
461 ("REQUEST_SCHEME".into(), if connection.tls { "https" } else { "http" }.into()),
462 ("REDIRECT_STATUS".into(), "200".into()),
464 ];
465 if !path_info.is_empty() {
466 params.push(("PATH_TRANSLATED".into(), format!("{root}{path_info}")));
467 }
468 if connection.tls {
469 params.push(("HTTPS".into(), "on".into()));
470 }
471 params.push(("CONTENT_LENGTH".into(), if request.body.is_empty() { String::new() } else { request.body.len().to_string() }));
472 params.push(("CONTENT_TYPE".into(), request.header("Content-Type").map(|h| h.value.to_string()).unwrap_or_default()));
473 for header in &request.headers {
474 let name = header.name.to_ascii_uppercase().replace('-', "_");
475 if name == "PROXY" || name == "CONTENT_TYPE" || name == "CONTENT_LENGTH" || name.bytes().any(|b| !(b.is_ascii_alphanumeric() || b == b'_')) {
477 continue;
478 }
479 let key = format!("HTTP_{name}");
480 match params.iter_mut().find(|(k, _)| *k == key) {
481 Some((_, v)) => {
482 v.push_str(if name == "COOKIE" { "; " } else { ", " });
483 v.push_str(&header.value);
484 }
485 None => params.push((key, header.value.to_string())),
486 }
487 }
488 for (k, v) in &self.inner.config.params {
489 match params.iter_mut().find(|(name, _)| name == k) {
490 Some((_, value)) => *value = v.clone(),
491 None => params.push((k.clone(), v.clone())),
492 }
493 }
494 params
495 }
496
497 fn take_conn(&self) -> Option<Conn> {
498 self.inner.pool.idle.lock().unwrap_or_else(|e| e.into_inner()).pop()
499 }
500
501 fn put_conn(&self, conn: Conn) {
502 let mut idle = self.inner.pool.idle.lock().unwrap_or_else(|e| e.into_inner());
503 if idle.len() < self.inner.pool.max {
504 idle.push(conn);
505 }
506 }
507
508 fn exchange(&self, params: &[(String, String)], body: &[u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
510 let mut message = Vec::with_capacity(body.len() + 1024);
511 let mut begin = Vec::with_capacity(8);
512 begin.extend_from_slice(&RESPONDER.to_be_bytes());
513 begin.extend_from_slice(&[KEEP_CONN, 0, 0, 0, 0, 0]);
514 encode_record(&mut message, BEGIN_REQUEST, 1, &begin);
515 encode_stream(&mut message, PARAMS, 1, &encode_params(params));
516 encode_stream(&mut message, STDIN, 1, body);
517 let cfg = &self.inner.config;
518 let mut tried_fresh = false;
521 loop {
522 let (mut conn, pooled) = match self.take_conn() {
523 Some(c) if !tried_fresh => (c, true),
524 _ => (Conn::open(&self.inner.address, cfg.connect_timeout, cfg.read_timeout).map_err(|e| format!("FastCGI server {}: {e}", cfg.address))?, false),
525 };
526 match self.round_trip(&mut conn, &message) {
527 Ok((out, keep)) => {
528 if keep {
529 self.put_conn(conn);
530 }
531 let end = header_end(&out).ok_or_else(|| "FastCGI: the response has no header block".to_string())?;
532 let mut out = out;
533 let body = out.split_off(end);
534 return Ok((out, body));
535 }
536 Err((e, nothing_read)) if pooled && nothing_read => {
537 let _ = e;
538 tried_fresh = true;
539 }
540 Err((e, _)) => return Err(format!("FastCGI server {}: {e}", cfg.address)),
541 }
542 }
543 }
544
545 fn round_trip(&self, conn: &mut Conn, message: &[u8]) -> Result<(Vec<u8>, bool), (String, bool)> {
548 conn.stream.write_all(message).and_then(|_| conn.stream.flush()).map_err(|e| (e.to_string(), true))?;
549 let mut stdout = Vec::new();
550 let mut stderr = Vec::new();
551 let mut read_any = false;
552 loop {
553 let record = match read_record(&mut conn.stream) {
554 Ok(Some(r)) => r,
555 Ok(None) => return Err(("the connection closed before the response ended".to_string(), !read_any)),
556 Err(e) => return Err((e.to_string(), !read_any)),
557 };
558 read_any = true;
559 if record.request_id != 1 {
560 continue;
561 }
562 match record.kind {
563 STDOUT => stdout.extend_from_slice(&record.content),
564 STDERR => stderr.extend_from_slice(&record.content),
565 END_REQUEST => {
566 let text = String::from_utf8_lossy(&stderr);
567 for line in text.lines().filter(|l| !l.trim().is_empty()) {
568 eprintln!("[fastcgi] {line}");
569 }
570 let complete = record.content.get(4).is_none_or(|s| *s == 0);
572 if !complete {
573 return Err((format!("the server refused the request (protocol status {})", record.content[4]), false));
574 }
575 return Ok((stdout, true));
576 }
577 _ => {}
578 }
579 }
580 }
581}
582
583fn simple(status: u16, headers: Vec<Header>, body: &str) -> Response {
584 let mut r = Response::new();
585 r.status_code = status as i16;
586 r.reason_phrase = reason_for(status);
587 r.headers.extend(headers);
588 if !body.is_empty() {
589 r.content_range_list = vec![Range::get_content_range(body.as_bytes().to_vec(), "text/plain".to_string())];
590 }
591 r
592}
593
594impl Application for FastCgi {
595 fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
596 let Some(path) = crate::url::URL::request_target_path(&request.request_uri) else {
597 return Ok(simple(400, Vec::new(), "Bad Request"));
598 };
599 match self.resolve(path) {
600 Target::NotFound => Ok(simple(404, Vec::new(), "Not Found")),
601 Target::Redirect(location) => {
602 let query = request.request_uri.split_once('?').map(|(_, q)| format!("?{q}")).unwrap_or_default();
603 Ok(simple(301, vec![Header::new("Location", format!("{location}{query}"))], ""))
604 }
605 Target::Static => match &self.inner.statics {
606 Some(app) => app.execute(request, connection),
607 None => Ok(simple(404, Vec::new(), "Not Found")),
608 },
609 Target::Script { script_name, filename, path_info } => {
610 let params = self.params(request, connection, &script_name, &filename, &path_info);
611 let (head, body) = match self.exchange(¶ms, &request.body) {
612 Ok(out) => out,
613 Err(e) => {
614 eprintln!("[fastcgi] {e}");
615 return Ok(simple(502, Vec::new(), "Bad Gateway"));
616 }
617 };
618 let (status, reason, headers) = match parse_cgi_headers(&head) {
619 Ok(h) => h,
620 Err(e) => {
621 eprintln!("[fastcgi] {e}");
622 return Ok(simple(502, Vec::new(), "Bad Gateway"));
623 }
624 };
625 let mut response = Response::new();
626 response.status_code = status as i16;
627 response.reason_phrase = if reason.is_empty() { reason_for(status) } else { reason };
628 let mut content_type = String::new();
629 for (name, value) in headers {
630 if name.eq_ignore_ascii_case("content-type") {
631 content_type = value;
632 } else if !name.eq_ignore_ascii_case("content-length") && !name.eq_ignore_ascii_case("transfer-encoding") && !name.eq_ignore_ascii_case("connection") {
633 response.headers.push(Header::new(name, value));
634 }
635 }
636 if !body.is_empty() || !content_type.is_empty() {
637 let content_type = if content_type.is_empty() { "application/octet-stream".to_string() } else { content_type };
638 response.content_range_list = vec![Range::get_content_range(body, content_type)];
639 }
640 Ok(response)
641 }
642 }
643 }
644}
645
646pub fn params_from_map(map: &HashMap<String, String>) -> Vec<(String, String)> {
648 let mut v: Vec<(String, String)> = map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
649 v.sort();
650 v
651}
652
653#[doc(hidden)]
654pub mod fuzz {
655 pub fn records(data: &[u8]) {
657 if let Some(records) = super::parse_records(data) {
658 for r in records {
659 if r.kind == super::PARAMS {
660 let _ = super::decode_params(&r.content);
661 }
662 }
663 }
664 let _ = super::decode_params(data);
665 if let Some(end) = super::header_end(data) {
666 let _ = super::parse_cgi_headers(&data[..end]);
667 }
668 }
669}
670
671#[cfg(test)]
672mod tests;