Skip to main content

speedyspec_php/
web.rs

1//! Web requests: what [`crate::Php::serve`] needs from the server, and the SAPI callbacks that route PHP's output,
2//! headers, request body, cookies and `$_SERVER` to it while a web request runs. Outside one, the callbacks keep
3//! the CLI behaviour (output to stdout or stderr, no headers, an empty `$_SERVER` beyond PHP's own entries).
4
5use std::cell::{Cell, RefCell};
6use std::ffi::{CString, c_char, c_int};
7
8use ext_php_rs::ffi::{php_register_variable_safe, sapi_header_struct, sapi_headers_struct, zval};
9use ext_php_rs::types::Zval;
10
11/// One HTTP request, as PHP sees it.
12pub trait WebRequest {
13    /// The CGI/1.1 parameters, which become `$_SERVER` (`SCRIPT_FILENAME`, `REQUEST_METHOD`, `HTTP_*`, …).
14    fn params(&self) -> &[(String, String)];
15    /// Reads the request body; 0 at its end (or when it cannot be read).
16    fn read_body(&mut self, buf: &mut [u8]) -> usize;
17    /// The response status and header lines (`Name: value`), once, before any body.
18    fn send_headers(&mut self, status: u16, headers: &[String]) -> bool;
19    /// Response body bytes; false when the client is gone.
20    fn write(&mut self, data: &[u8]) -> bool;
21}
22
23/// What PHP tells `SG(sapi_headers)` the response is, read back after a request.
24#[derive(Clone, Debug, Default)]
25pub struct WebState {
26    pub headers_sent: bool,
27}
28
29thread_local! {
30    static CURRENT: Cell<Option<*mut dyn WebRequest>> = const { Cell::new(None) };
31    static COOKIES: RefCell<Option<CString>> = const { RefCell::new(None) };
32    pub(crate) static STATE: RefCell<WebState> = RefCell::new(WebState::default());
33}
34
35/// Runs `f` with the current web request, if one is being served.
36fn with_current<R>(f: impl FnOnce(&mut dyn WebRequest) -> R) -> Option<R> {
37    let current = CURRENT.with(Cell::get)?;
38    // SAFETY: `serve` sets the pointer for exactly the duration of the request, from a `&mut` it holds.
39    Some(f(unsafe { &mut *current }))
40}
41
42pub(crate) fn active() -> bool {
43    CURRENT.with(Cell::get).is_some()
44}
45
46/// Makes `request` the current web request until [`end`]. The caller keeps `request` borrowed until then.
47pub(crate) fn begin(request: &mut dyn WebRequest) {
48    let cookie = request
49        .params()
50        .iter()
51        .find(|(k, _)| k == "HTTP_COOKIE")
52        .map(|(_, v)| v.clone());
53    COOKIES.with(|c| *c.borrow_mut() = cookie.and_then(|v| CString::new(v).ok()));
54    STATE.with(|s| *s.borrow_mut() = WebState::default());
55    // SAFETY: erases the borrow's lifetime; `end` clears the pointer before `serve` returns.
56    let ptr: *mut dyn WebRequest =
57        unsafe { std::mem::transmute::<&mut dyn WebRequest, &'static mut dyn WebRequest>(request) };
58    CURRENT.with(|c| c.set(Some(ptr)));
59}
60
61pub(crate) fn end() {
62    CURRENT.with(|c| c.set(None));
63    COOKIES.with(|c| c.borrow_mut().take());
64}
65
66/// `ub_write` while a web request runs: the response body.
67pub(crate) fn write(bytes: &[u8]) -> Option<bool> {
68    with_current(|request| request.write(bytes))
69}
70
71/// `SAPI_HEADER_SENT_SUCCESSFULLY`.
72const HEADER_SENT: c_int = 1;
73
74pub(crate) extern "C" fn send_headers(headers: *mut sapi_headers_struct) -> c_int {
75    if headers.is_null() || !active() {
76        return HEADER_SENT;
77    }
78    // SAFETY: PHP passes its live `SG(sapi_headers)`; each list element stores a `sapi_header_struct` inline.
79    let (status, lines) = unsafe {
80        let status = match (*headers).http_response_code {
81            code if (100..=999).contains(&code) => code as u16,
82            _ => 200,
83        };
84        let mut lines = Vec::new();
85        let mut element = (*headers).headers.head;
86        while !element.is_null() {
87            let header = (&raw const (*element).data).cast::<sapi_header_struct>();
88            let text = (*header).header;
89            if !text.is_null() {
90                let bytes = std::slice::from_raw_parts(text.cast::<u8>(), (*header).header_len);
91                lines.push(String::from_utf8_lossy(bytes).into_owned());
92            }
93            element = (*element).next;
94        }
95        (status, lines)
96    };
97    STATE.with(|s| s.borrow_mut().headers_sent = true);
98    with_current(|request| request.send_headers(status, &lines));
99    HEADER_SENT
100}
101
102pub(crate) extern "C" fn read_post(buffer: *mut c_char, length: usize) -> usize {
103    if buffer.is_null() || length == 0 {
104        return 0;
105    }
106    // SAFETY: PHP passes a writable buffer of `length` bytes.
107    let buf = unsafe { std::slice::from_raw_parts_mut(buffer.cast::<u8>(), length) };
108    with_current(|request| request.read_body(buf)).unwrap_or(0)
109}
110
111pub(crate) extern "C" fn read_cookies() -> *mut c_char {
112    COOKIES.with(|c| {
113        c.borrow()
114            .as_ref()
115            .map_or(std::ptr::null_mut(), |s| s.as_ptr().cast_mut())
116    })
117}
118
119pub(crate) extern "C" fn register_server_variables(vars: *mut Zval) {
120    let vars: *mut zval = vars;
121    with_current(|request| {
122        for (name, value) in request.params() {
123            let Ok(name) = CString::new(name.as_str()) else {
124                continue;
125            };
126            // SAFETY: PHP passes the live `$_SERVER` array being built; the name is NUL-terminated and the value
127            // has its length.
128            unsafe {
129                php_register_variable_safe(name.as_ptr(), value.as_ptr().cast(), value.len(), vars)
130            };
131        }
132    });
133}