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.is_empty())) || decoded.contains('\0') {
381 return Target::NotFound;
382 }
383 let path = if decoded.starts_with('/') { decoded.clone() } else { format!("/{decoded}") };
384 let full = self.inner.root.join(path.trim_start_matches('/'));
385 if let Some(file) = self.file_under_root(&path) {
387 if self.is_script(&path) {
388 return Target::Script { script_name: path, filename: file, path_info: String::new() };
389 }
390 return Target::Static;
391 }
392 if full.is_dir() && full.canonicalize().is_ok_and(|r| r.starts_with(&self.inner.root)) {
394 for index in &self.inner.config.index {
395 let script = format!("{}/{}", path.trim_end_matches('/'), index);
396 if let Some(file) = self.file_under_root(&script) {
397 if !path.ends_with('/') {
398 return Target::Redirect(format!("{path}/"));
399 }
400 if self.is_script(&script) {
401 return Target::Script { script_name: script, filename: file, path_info: String::new() };
402 }
403 return Target::Static;
404 }
405 }
406 }
407 let split = &self.inner.config.split_path;
409 if !split.is_empty() {
410 let mut from = 0;
411 while let Some(found) = path[from..].find(split.as_str()) {
412 let end = from + found + split.len();
413 if path[end..].starts_with('/') {
414 let script = &path[..end];
415 if let Some(file) = self.file_under_root(script) {
416 return Target::Script { script_name: script.to_string(), filename: file, path_info: path[end..].to_string() };
417 }
418 }
419 from = end;
420 }
421 }
422 let front = &self.inner.config.front_controller;
424 if !front.is_empty() {
425 let script = format!("/{}", front.trim_start_matches('/'));
426 if let Some(file) = self.file_under_root(&script) {
427 return Target::Script { script_name: script, filename: file, path_info: String::new() };
428 }
429 }
430 Target::NotFound
431 }
432
433 pub(crate) fn params(&self, request: &Request, connection: &ConnectionInfo, script_name: &str, filename: &Path, path_info: &str) -> Vec<(String, String)> {
435 let (_, query) = request.request_uri.split_once('?').unwrap_or((&request.request_uri, ""));
436 let host = request.header("Host").map(|h| h.value.to_string()).unwrap_or_default();
437 let server_name = match host.rsplit_once(':') {
438 Some((h, p)) if p.bytes().all(|b| b.is_ascii_digit()) && !h.ends_with(':') => h.to_string(),
439 _ => host.clone(),
440 };
441 let root = self.inner.root.to_string_lossy().to_string();
442 let mut params: Vec<(String, String)> = vec![
443 ("GATEWAY_INTERFACE".into(), "CGI/1.1".into()),
444 ("SERVER_SOFTWARE".into(), format!("rws/{}", env!("CARGO_PKG_VERSION"))),
445 ("SERVER_PROTOCOL".into(), "HTTP/1.1".into()),
446 ("REQUEST_METHOD".into(), request.method.clone()),
447 ("REQUEST_URI".into(), request.request_uri.clone()),
448 ("QUERY_STRING".into(), query.to_string()),
449 ("SCRIPT_NAME".into(), script_name.to_string()),
450 ("SCRIPT_FILENAME".into(), filename.to_string_lossy().to_string()),
451 ("DOCUMENT_ROOT".into(), root.clone()),
452 ("DOCUMENT_URI".into(), format!("{script_name}{path_info}")),
453 ("PATH_INFO".into(), path_info.to_string()),
454 ("REMOTE_ADDR".into(), connection.client.ip.clone()),
455 ("REMOTE_PORT".into(), connection.client.port.to_string()),
456 ("SERVER_ADDR".into(), connection.server.ip.clone()),
457 ("SERVER_PORT".into(), connection.server.port.to_string()),
458 ("SERVER_NAME".into(), server_name),
459 ("REQUEST_SCHEME".into(), if connection.tls { "https" } else { "http" }.into()),
460 ("REDIRECT_STATUS".into(), "200".into()),
462 ];
463 if !path_info.is_empty() {
464 params.push(("PATH_TRANSLATED".into(), format!("{root}{path_info}")));
465 }
466 if connection.tls {
467 params.push(("HTTPS".into(), "on".into()));
468 }
469 params.push(("CONTENT_LENGTH".into(), if request.body.is_empty() { String::new() } else { request.body.len().to_string() }));
470 params.push(("CONTENT_TYPE".into(), request.header("Content-Type").map(|h| h.value.to_string()).unwrap_or_default()));
471 for header in &request.headers {
472 let name = header.name.to_ascii_uppercase().replace('-', "_");
473 if name == "PROXY" || name == "CONTENT_TYPE" || name == "CONTENT_LENGTH" || name.bytes().any(|b| !(b.is_ascii_alphanumeric() || b == b'_')) {
475 continue;
476 }
477 let key = format!("HTTP_{name}");
478 match params.iter_mut().find(|(k, _)| *k == key) {
479 Some((_, v)) => {
480 v.push_str(if name == "COOKIE" { "; " } else { ", " });
481 v.push_str(&header.value);
482 }
483 None => params.push((key, header.value.to_string())),
484 }
485 }
486 for (k, v) in &self.inner.config.params {
487 match params.iter_mut().find(|(name, _)| name == k) {
488 Some((_, value)) => *value = v.clone(),
489 None => params.push((k.clone(), v.clone())),
490 }
491 }
492 params
493 }
494
495 fn take_conn(&self) -> Option<Conn> {
496 self.inner.pool.idle.lock().unwrap_or_else(|e| e.into_inner()).pop()
497 }
498
499 fn put_conn(&self, conn: Conn) {
500 let mut idle = self.inner.pool.idle.lock().unwrap_or_else(|e| e.into_inner());
501 if idle.len() < self.inner.pool.max {
502 idle.push(conn);
503 }
504 }
505
506 fn exchange(&self, params: &[(String, String)], body: &[u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
508 let mut message = Vec::with_capacity(body.len() + 1024);
509 let mut begin = Vec::with_capacity(8);
510 begin.extend_from_slice(&RESPONDER.to_be_bytes());
511 begin.extend_from_slice(&[KEEP_CONN, 0, 0, 0, 0, 0]);
512 encode_record(&mut message, BEGIN_REQUEST, 1, &begin);
513 encode_stream(&mut message, PARAMS, 1, &encode_params(params));
514 encode_stream(&mut message, STDIN, 1, body);
515 let cfg = &self.inner.config;
516 let mut tried_fresh = false;
519 loop {
520 let (mut conn, pooled) = match self.take_conn() {
521 Some(c) if !tried_fresh => (c, true),
522 _ => (Conn::open(&self.inner.address, cfg.connect_timeout, cfg.read_timeout).map_err(|e| format!("FastCGI server {}: {e}", cfg.address))?, false),
523 };
524 match self.round_trip(&mut conn, &message) {
525 Ok((out, keep)) => {
526 if keep {
527 self.put_conn(conn);
528 }
529 let end = header_end(&out).ok_or_else(|| "FastCGI: the response has no header block".to_string())?;
530 let mut out = out;
531 let body = out.split_off(end);
532 return Ok((out, body));
533 }
534 Err((e, nothing_read)) if pooled && nothing_read => {
535 let _ = e;
536 tried_fresh = true;
537 }
538 Err((e, _)) => return Err(format!("FastCGI server {}: {e}", cfg.address)),
539 }
540 }
541 }
542
543 fn round_trip(&self, conn: &mut Conn, message: &[u8]) -> Result<(Vec<u8>, bool), (String, bool)> {
546 conn.stream.write_all(message).and_then(|_| conn.stream.flush()).map_err(|e| (e.to_string(), true))?;
547 let mut stdout = Vec::new();
548 let mut stderr = Vec::new();
549 let mut read_any = false;
550 loop {
551 let record = match read_record(&mut conn.stream) {
552 Ok(Some(r)) => r,
553 Ok(None) => return Err(("the connection closed before the response ended".to_string(), !read_any)),
554 Err(e) => return Err((e.to_string(), !read_any)),
555 };
556 read_any = true;
557 if record.request_id != 1 {
558 continue;
559 }
560 match record.kind {
561 STDOUT => stdout.extend_from_slice(&record.content),
562 STDERR => stderr.extend_from_slice(&record.content),
563 END_REQUEST => {
564 let text = String::from_utf8_lossy(&stderr);
565 for line in text.lines().filter(|l| !l.trim().is_empty()) {
566 eprintln!("[fastcgi] {line}");
567 }
568 let complete = record.content.get(4).is_none_or(|s| *s == 0);
570 if !complete {
571 return Err((format!("the server refused the request (protocol status {})", record.content[4]), false));
572 }
573 return Ok((stdout, true));
574 }
575 _ => {}
576 }
577 }
578 }
579}
580
581fn simple(status: u16, headers: Vec<Header>, body: &str) -> Response {
582 let mut r = Response::new();
583 r.status_code = status as i16;
584 r.reason_phrase = reason_for(status);
585 r.headers.extend(headers);
586 if !body.is_empty() {
587 r.content_range_list = vec![Range::get_content_range(body.as_bytes().to_vec(), "text/plain".to_string())];
588 }
589 r
590}
591
592impl Application for FastCgi {
593 fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
594 let Some(path) = crate::url::URL::request_target_path(&request.request_uri) else {
595 return Ok(simple(400, Vec::new(), "Bad Request"));
596 };
597 match self.resolve(path) {
598 Target::NotFound => Ok(simple(404, Vec::new(), "Not Found")),
599 Target::Redirect(location) => {
600 let query = request.request_uri.split_once('?').map(|(_, q)| format!("?{q}")).unwrap_or_default();
601 Ok(simple(301, vec![Header::new("Location", format!("{location}{query}"))], ""))
602 }
603 Target::Static => match &self.inner.statics {
604 Some(app) => app.execute(request, connection),
605 None => Ok(simple(404, Vec::new(), "Not Found")),
606 },
607 Target::Script { script_name, filename, path_info } => {
608 let params = self.params(request, connection, &script_name, &filename, &path_info);
609 let (head, body) = match self.exchange(¶ms, &request.body) {
610 Ok(out) => out,
611 Err(e) => {
612 eprintln!("[fastcgi] {e}");
613 return Ok(simple(502, Vec::new(), "Bad Gateway"));
614 }
615 };
616 let (status, reason, headers) = match parse_cgi_headers(&head) {
617 Ok(h) => h,
618 Err(e) => {
619 eprintln!("[fastcgi] {e}");
620 return Ok(simple(502, Vec::new(), "Bad Gateway"));
621 }
622 };
623 let mut response = Response::new();
624 response.status_code = status as i16;
625 response.reason_phrase = if reason.is_empty() { reason_for(status) } else { reason };
626 let mut content_type = String::new();
627 for (name, value) in headers {
628 if name.eq_ignore_ascii_case("content-type") {
629 content_type = value;
630 } else if !name.eq_ignore_ascii_case("content-length") && !name.eq_ignore_ascii_case("transfer-encoding") && !name.eq_ignore_ascii_case("connection") {
631 response.headers.push(Header::new(name, value));
632 }
633 }
634 if !body.is_empty() || !content_type.is_empty() {
635 let content_type = if content_type.is_empty() { "application/octet-stream".to_string() } else { content_type };
636 response.content_range_list = vec![Range::get_content_range(body, content_type)];
637 }
638 Ok(response)
639 }
640 }
641 }
642}
643
644pub fn params_from_map(map: &HashMap<String, String>) -> Vec<(String, String)> {
646 let mut v: Vec<(String, String)> = map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
647 v.sort();
648 v
649}
650
651#[doc(hidden)]
652pub mod fuzz {
653 pub fn records(data: &[u8]) {
655 if let Some(records) = super::parse_records(data) {
656 for r in records {
657 if r.kind == super::PARAMS {
658 let _ = super::decode_params(&r.content);
659 }
660 }
661 }
662 let _ = super::decode_params(data);
663 if let Some(end) = super::header_end(data) {
664 let _ = super::parse_cgi_headers(&data[..end]);
665 }
666 }
667}
668
669#[cfg(test)]
670mod tests;