1use 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
11pub trait WebRequest {
13 fn params(&self) -> &[(String, String)];
15 fn read_body(&mut self, buf: &mut [u8]) -> usize;
17 fn send_headers(&mut self, status: u16, headers: &[String]) -> bool;
19 fn write(&mut self, data: &[u8]) -> bool;
21}
22
23#[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
35fn with_current<R>(f: impl FnOnce(&mut dyn WebRequest) -> R) -> Option<R> {
37 let current = CURRENT.with(Cell::get)?;
38 Some(f(unsafe { &mut *current }))
40}
41
42pub(crate) fn active() -> bool {
43 CURRENT.with(Cell::get).is_some()
44}
45
46pub(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 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
66pub(crate) fn write(bytes: &[u8]) -> Option<bool> {
68 with_current(|request| request.write(bytes))
69}
70
71const 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 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 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 unsafe {
129 php_register_variable_safe(name.as_ptr(), value.as_ptr().cast(), value.len(), vars)
130 };
131 }
132 });
133}