1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
|
//! Rust-to-PHP RPC over a Unix domain socket. See `docs/dev/php-rpc.md`.
use shirabe_external_packages::symfony::process::PhpExecutableFinder;
use shirabe_php_shim::PhpMixed;
use std::io::{Read as _, Write as _};
use std::os::unix::net::{UnixListener, UnixStream};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};
/// PHP `\PHP_VERSION`.
pub fn get_php_version() -> String {
match get_constant("PHP_VERSION") {
PhpMixed::String(s) => s,
_ => String::new(),
}
}
/// PHP `\PHP_BINARY`.
pub fn get_php_binary() -> String {
match get_constant("PHP_BINARY") {
PhpMixed::String(s) => s,
_ => String::new(),
}
}
/// PHP `defined($name)`.
pub fn has_constant(name: &str) -> bool {
matches!(call("defined", name), Some(PhpMixed::Bool(true)))
}
/// PHP `constant($name)`.
pub fn get_constant(name: &str) -> PhpMixed {
call("constant", name).unwrap_or(PhpMixed::Null)
}
/// PHP `inet_pton($address)`.
pub fn inet_pton(address: &str) -> PhpMixed {
call("inet_pton", address).unwrap_or(PhpMixed::Bool(false))
}
/// PHP `curl_version()['version']`.
pub fn curl_version() -> Option<String> {
match call("curl_version", "") {
Some(PhpMixed::String(s)) => Some(s),
_ => None,
}
}
/// PHP `(new \ReflectionExtension($name))->info()` output.
pub fn get_extension_info(name: &str) -> String {
match call("extension_info", name) {
Some(PhpMixed::String(s)) => s,
_ => String::new(),
}
}
/// PHP `phpversion($extension)`.
pub fn phpversion(extension: &str) -> Option<String> {
match call("phpversion", extension) {
Some(PhpMixed::String(s)) => Some(s),
_ => None,
}
}
/// PHP `get_loaded_extensions()`.
///
/// Extension names are joined with `,` on the PHP side and split back here; real
/// extension names never contain a comma.
pub fn get_loaded_extensions() -> Vec<String> {
match call("get_loaded_extensions", "") {
Some(PhpMixed::String(s)) if !s.is_empty() => s.split(',').map(|s| s.to_string()).collect(),
_ => Vec::new(),
}
}
const GLUE_SCRIPT: &str = include_str!("../php/worker.php");
struct Worker {
stream: UnixStream,
// Kept alive for the process lifetime: the child interpreter and the temp dir holding the socket
// and glue script. Neither is dropped because the worker lives in a never-dropped static.
_child: std::process::Child,
_tempdir: tempfile::TempDir,
}
impl Worker {
fn request(&mut self, name: &str, arg: &str) -> Option<Vec<u8>> {
let mut payload = name.as_bytes().to_vec();
payload.push(0);
payload.extend_from_slice(arg.as_bytes());
write_frame(&mut self.stream, &payload).ok()?;
read_frame(&mut self.stream).ok()
}
}
static WORKER: LazyLock<Mutex<Option<Worker>>> = LazyLock::new(|| Mutex::new(spawn_worker()));
fn call(name: &str, arg: &str) -> Option<PhpMixed> {
let mut guard = WORKER.lock().ok()?;
let payload = guard.as_mut()?.request(name, arg)?;
parse_serialized_scalar(&payload)
}
fn spawn_worker() -> Option<Worker> {
let php = PhpExecutableFinder::new().find(false)?;
let tempdir = tempfile::tempdir().ok()?;
let socket_path = tempdir.path().join("rpc.sock");
let script_path = tempdir.path().join("worker.php");
std::fs::write(&script_path, GLUE_SCRIPT).ok()?;
// Bind before spawning so the socket exists when the child connects.
let listener = UnixListener::bind(&socket_path).ok()?;
listener.set_nonblocking(true).ok()?;
let child = std::process::Command::new(&php)
.arg(&script_path)
.arg(&socket_path)
.spawn()
.ok()?;
// Poll for the child's connection with a bounded deadline so a child that never connects does
// not hang the caller.
let deadline = Instant::now() + Duration::from_secs(10);
let stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if Instant::now() >= deadline {
return None;
}
std::thread::sleep(Duration::from_millis(5));
}
Err(_) => return None,
}
};
stream.set_nonblocking(false).ok()?;
Some(Worker {
stream,
_child: child,
_tempdir: tempdir,
})
}
fn write_frame(stream: &mut UnixStream, payload: &[u8]) -> std::io::Result<()> {
stream.write_all(&(payload.len() as u64).to_le_bytes())?;
stream.write_all(payload)?;
stream.flush()
}
fn read_frame(stream: &mut UnixStream) -> std::io::Result<Vec<u8>> {
let mut header = [0u8; 8];
stream.read_exact(&mut header)?;
let len = u64::from_le_bytes(header) as usize;
let mut payload = vec![0u8; len];
stream.read_exact(&mut payload)?;
Ok(payload)
}
/// Parse the `s:<len>:"<bytes>";` form; only strings are needed here, so other forms are rejected.
fn parse_serialized_string(payload: &[u8]) -> Option<String> {
let rest = payload.strip_prefix(b"s:")?;
let colon = rest.iter().position(|&b| b == b':')?;
let len: usize = std::str::from_utf8(&rest[..colon]).ok()?.parse().ok()?;
let after = rest.get(colon + 1..)?;
let bytes = after.strip_prefix(b"\"")?.get(..len)?;
Some(String::from_utf8_lossy(bytes).into_owned())
}
/// Parse any of PHP's scalar/null `serialize()` forms: `N;`, `b:0/1;`, `i:<n>;`, `d:<f>;`,
/// `s:<len>:"<bytes>";`.
fn parse_serialized_scalar(payload: &[u8]) -> Option<PhpMixed> {
if payload == b"N;" {
return Some(PhpMixed::Null);
}
if let Some(rest) = payload.strip_prefix(b"b:") {
return match rest.strip_suffix(b";")? {
b"0" => Some(PhpMixed::Bool(false)),
b"1" => Some(PhpMixed::Bool(true)),
_ => None,
};
}
if let Some(rest) = payload.strip_prefix(b"i:") {
let s = std::str::from_utf8(rest.strip_suffix(b";")?).ok()?;
return s.parse().ok().map(PhpMixed::Int);
}
if let Some(rest) = payload.strip_prefix(b"d:") {
let s = std::str::from_utf8(rest.strip_suffix(b";")?).ok()?;
return s.parse().ok().map(PhpMixed::Float);
}
if payload.starts_with(b"s:") {
return parse_serialized_string(payload).map(PhpMixed::String);
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_string_scalar() {
assert_eq!(
parse_serialized_string(b"s:5:\"8.5.7\";").as_deref(),
Some("8.5.7"),
);
}
#[test]
fn parses_empty_string() {
assert_eq!(parse_serialized_string(b"s:0:\"\";").as_deref(), Some(""));
}
#[test]
fn parses_string_with_embedded_quote() {
assert_eq!(
parse_serialized_string(b"s:3:\"a\"b\";").as_deref(),
Some("a\"b"),
);
}
#[test]
fn rejects_non_string_scalars() {
assert_eq!(parse_serialized_string(b"i:42;"), None);
assert_eq!(parse_serialized_string(b"N;"), None);
assert_eq!(parse_serialized_string(b"b:1;"), None);
}
#[test]
fn rejects_truncated_string() {
assert_eq!(parse_serialized_string(b"s:5:\"ab\";"), None);
}
#[test]
fn rejects_non_numeric_length() {
assert_eq!(parse_serialized_string(b"s:x:\"ab\";"), None);
}
#[test]
fn parses_scalar_null() {
assert_eq!(parse_serialized_scalar(b"N;"), Some(PhpMixed::Null));
}
#[test]
fn parses_scalar_bool() {
assert_eq!(
parse_serialized_scalar(b"b:0;"),
Some(PhpMixed::Bool(false))
);
assert_eq!(parse_serialized_scalar(b"b:1;"), Some(PhpMixed::Bool(true)));
}
#[test]
fn parses_scalar_int() {
assert_eq!(parse_serialized_scalar(b"i:8;"), Some(PhpMixed::Int(8)));
assert_eq!(parse_serialized_scalar(b"i:-1;"), Some(PhpMixed::Int(-1)));
}
#[test]
fn parses_scalar_float() {
assert_eq!(
parse_serialized_scalar(b"d:1.5;"),
Some(PhpMixed::Float(1.5))
);
}
#[test]
fn parses_scalar_string() {
assert_eq!(
parse_serialized_scalar(b"s:5:\"8.5.7\";"),
Some(PhpMixed::String("8.5.7".to_string())),
);
}
#[test]
fn rejects_malformed_scalar() {
assert_eq!(parse_serialized_scalar(b"b:2;"), None);
assert_eq!(parse_serialized_scalar(b"i:x;"), None);
assert_eq!(parse_serialized_scalar(b"d:x;"), None);
assert_eq!(parse_serialized_scalar(b"garbage"), None);
}
#[test]
fn frame_roundtrip() {
let (mut a, mut b) = UnixStream::pair().unwrap();
write_frame(&mut a, b"get_php_version").unwrap();
assert_eq!(read_frame(&mut b).unwrap(), b"get_php_version");
}
#[test]
fn frame_roundtrip_empty_payload() {
let (mut a, mut b) = UnixStream::pair().unwrap();
write_frame(&mut a, b"").unwrap();
assert_eq!(read_frame(&mut b).unwrap(), b"");
}
#[test]
fn queries_real_php_when_available() {
if PhpExecutableFinder::new().find(false).is_none() {
// No PHP in this environment; the worker cannot start.
return;
}
let version = get_php_version();
assert!(!version.is_empty(), "expected a PHP version");
assert!(
version
.split('.')
.next()
.and_then(|n| n.parse::<u32>().ok())
.is_some(),
"version should start with a number: {version}",
);
let binary = get_php_binary();
assert!(!binary.is_empty(), "expected a PHP binary path");
assert!(
std::path::Path::new(&binary).exists(),
"binary should exist: {binary}",
);
}
#[test]
fn queries_constants_when_php_available() {
if PhpExecutableFinder::new().find(false).is_none() {
// No PHP in this environment; the worker cannot start.
return;
}
assert!(has_constant("PHP_VERSION"));
assert!(!has_constant("SHIRABE_DOES_NOT_EXIST_XYZ"));
assert_eq!(get_constant("PHP_INT_SIZE"), PhpMixed::Int(8));
assert_eq!(get_constant("SHIRABE_DOES_NOT_EXIST_XYZ"), PhpMixed::Null);
match get_constant("PHP_VERSION") {
PhpMixed::String(s) => assert!(!s.is_empty(), "expected a non-empty PHP_VERSION"),
other => panic!("expected a string, got {other:?}"),
}
}
}
|