use crate::host::with_host;
use crate::stdlib::common::*;
use fusevm::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StreamKind {
Plain,
Memory,
Temp,
Stdin,
Stdout,
Stderr,
Output,
}
const TEMP_MAX_MEMORY: usize = 2 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct Stream {
pub id: i64,
pub kind: StreamKind,
pub path: String,
pub buf: Vec<u8>,
pub pos: usize,
pub readable: bool,
pub writable: bool,
pub append: bool,
pub eof: bool,
pub dirty: bool,
pub closed: bool,
pub spill_at: Option<usize>,
pub source_done: bool,
}
impl Stream {
fn new(kind: StreamKind, readable: bool, writable: bool) -> Self {
Stream {
id: 0,
kind,
path: String::new(),
buf: Vec::new(),
pos: 0,
readable,
writable,
append: false,
eof: false,
dirty: false,
closed: false,
spill_at: None,
source_done: false,
}
}
pub fn stdio(kind: StreamKind) -> Self {
Stream::new(kind, kind == StreamKind::Stdin, kind != StreamKind::Stdin)
}
pub(crate) fn read(&mut self, n: usize) -> Vec<u8> {
let start = self.pos.min(self.buf.len());
let end = start.saturating_add(n).min(self.buf.len());
if end - start < n {
self.eof = true;
}
if end > start {
self.pos = end;
}
self.buf[start..end].to_vec()
}
fn gets(&mut self, max: Option<usize>) -> Option<Vec<u8>> {
if self.pos >= self.buf.len() {
self.eof = true;
return None;
}
let cap = max.map_or(self.buf.len(), |m| (self.pos + m).min(self.buf.len()));
let mut end = self.pos;
while end < cap && self.buf[end] != b'\n' {
end += 1;
}
if end < cap {
end += 1; } else if end == self.buf.len() && max.is_none_or(|m| end - self.pos < m) {
self.eof = true;
}
let line = self.buf[self.pos..end].to_vec();
self.pos = end;
Some(line)
}
pub fn write_at_cursor(&mut self, bytes: &[u8]) -> usize {
let at = if self.append {
self.buf.len()
} else {
self.pos
};
if at > self.buf.len() {
self.buf.resize(at, 0);
}
let overlap = (self.buf.len() - at).min(bytes.len());
self.buf[at..at + overlap].copy_from_slice(&bytes[..overlap]);
self.buf.extend_from_slice(&bytes[overlap..]);
self.pos += bytes.len();
self.dirty = true;
bytes.len()
}
fn seek(&mut self, offset: i64, whence: i64) -> bool {
let base = match whence {
1 => self.pos as i64,
2 => self.buf.len() as i64,
_ => 0,
};
let Some(target) = base.checked_add(offset).filter(|t| *t >= 0) else {
return false;
};
self.pos = target as usize;
self.eof = false;
true
}
pub fn type_name(&self) -> &'static str {
if self.closed {
"Unknown"
} else {
"stream"
}
}
}
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
let v = match name {
"fopen" => {
let path = str_arg(args, 0);
if path.is_empty() {
return Some(Err(throws("ValueError", "Path must not be empty")));
}
fopen(&path, &str_arg(args, 1))
}
"readline" => readline(args),
"tmpfile" => with_host(|h| h.new_stream(Stream::new(StreamKind::Memory, true, true))),
"fread" => {
let res = arg(args, 0);
let n = int_arg(args, 1);
if n <= 0 {
return Some(Err(throws(
"ValueError",
"fread(): Argument #2 ($length) must be greater than 0",
)));
}
match read(name, &res, |s| Some(s.read(n as usize))) {
Some(b) => bytes_value(b),
None => Value::bool(false),
}
}
"fgets" => {
let res = arg(args, 0);
let max = if matches!(args.get(1), Some(v) if !matches!(v, Value::Undef)) {
let len = int_arg(args, 1);
if len <= 0 {
return Some(Err(throws(
"ValueError",
"fgets(): Argument #2 ($length) must be greater than 0",
)));
}
Some((len as usize).saturating_sub(1))
} else {
None
};
match read(name, &res, |s| s.gets(max)) {
Some(b) => bytes_value(b),
None => Value::bool(false),
}
}
"fgetcsv" => return Some(fgetcsv(args)),
"fputcsv" => return Some(fputcsv(args)),
"fgetc" => {
let res = arg(args, 0);
match read(name, &res, |s| Some(s.read(1)).filter(|b| !b.is_empty())) {
Some(b) => bytes_value(b),
None => Value::bool(false),
}
}
"stream_get_contents" => {
let res = arg(args, 0);
let max = match args.get(1) {
Some(Value::Undef) | None => -1,
Some(_) => int_arg(args, 1),
};
let offset = match args.get(2) {
Some(Value::Undef) | None => -1,
Some(_) => int_arg(args, 2),
};
if offset >= 0 {
with_host(|h| h.stream_mut(&res).map(|s| s.seek(offset, 0)));
}
let want = if max < 0 { usize::MAX } else { max as usize };
match read(name, &res, |s| Some(s.read(want))) {
Some(b) => bytes_value(b),
None => Value::str(String::new()),
}
}
"fpassthru" => {
let res = arg(args, 0);
match read(name, &res, |s| Some(s.read(usize::MAX))) {
Some(b) => {
let n = b.len();
with_host(|h| h.write_out(&crate::bytes::from_bytes(&b)));
Value::int(n as i64)
}
None => Value::int(0),
}
}
"fwrite" | "fputs" => {
let res = arg(args, 0);
let mut data = crate::bytes::to_bytes(&str_arg(args, 1)).into_owned();
if matches!(args.get(2), Some(v) if !matches!(v, Value::Undef)) {
let len = int_arg(args, 2).max(0) as usize;
data.truncate(len);
}
match write_bytes(name, &res, &data) {
Some(n) => Value::int(n as i64),
None => Value::bool(false),
}
}
"fclose" => {
let res = arg(args, 0);
flush(&res);
Value::bool(with_host(|h| {
h.stream_mut(&res).is_some_and(|s| {
s.closed = true;
true
})
}))
}
"fflush" => {
let res = arg(args, 0);
flush(&res);
Value::bool(true)
}
"feof" => {
let res = arg(args, 0);
Value::bool(with_host(|h| h.stream(&res).is_none_or(|s| s.eof)))
}
"ftell" => {
let res = arg(args, 0);
with_host(|h| match h.stream(&res) {
Some(s) => Value::int(s.pos as i64),
None => Value::bool(false),
})
}
"rewind" => {
let res = arg(args, 0);
Value::bool(with_host(|h| {
h.stream_mut(&res).is_some_and(|s| s.seek(0, 0))
}))
}
"fseek" => {
let res = arg(args, 0);
let offset = int_arg(args, 1);
let whence = if args.len() > 2 { int_arg(args, 2) } else { 0 };
let ok = with_host(|h| h.stream_mut(&res).is_some_and(|s| s.seek(offset, whence)));
Value::int(if ok { 0 } else { -1 })
}
"ftruncate" => {
let res = arg(args, 0);
let size = int_arg(args, 1);
if size < 0 {
return Some(Err(throws(
"ValueError",
"ftruncate(): Argument #2 ($size) must be greater than or equal to 0",
)));
}
let ok = with_host(|h| {
h.stream_mut(&res).is_some_and(|s| {
if !s.writable {
return false;
}
s.buf.resize(size as usize, 0);
s.dirty = true;
true
})
});
flush(&res);
Value::bool(ok)
}
"fstat" => fstat(&arg(args, 0)),
"is_resource" => Value::bool(with_host(|h| h.is_resource(&arg(args, 0)))),
"get_resource_type" => with_host(|h| match h.stream_any(&arg(args, 0)) {
Some(s) => Value::str(s.type_name()),
None => Value::bool(false),
}),
"get_resource_id" => with_host(|h| match h.stream_any(&arg(args, 0)) {
Some(s) => Value::int(s.id),
None => Value::int(0),
}),
_ => return None,
};
Some(Ok(v))
}
fn bytes_value(b: Vec<u8>) -> Value {
Value::str(crate::bytes::from_bytes(&b))
}
pub(crate) fn strerror(e: &std::io::Error) -> String {
let s = e.to_string();
match s.find(" (os error") {
Some(i) => s[..i].to_string(),
None => s,
}
}
pub(crate) fn read(
fname: &str,
res: &Value,
op: impl FnOnce(&mut Stream) -> Option<Vec<u8>>,
) -> Option<Vec<u8>> {
let (kind, readable) = with_host(|h| h.stream(res).map(|s| (s.kind, s.readable)))?;
if !readable {
with_host(|h| {
h.notice(format!(
"{fname}(): Read of 8192 bytes failed with errno=9 Bad file descriptor"
))
});
return None;
}
if kind == StreamKind::Stdin {
fill_stdin(fname, res);
}
with_host(|h| h.stream_mut(res).and_then(op))
}
fn with_stdin_source<R>(f: impl FnOnce(&mut dyn std::io::BufRead) -> R) -> R {
match with_host(|h| h.stdin_feed.take()) {
Some(mut feed) => {
let r = f(&mut feed);
with_host(|h| h.stdin_feed = Some(feed));
r
}
None => f(&mut std::io::stdin().lock()),
}
}
fn readline(args: &[Value]) -> Value {
use std::io::IsTerminal;
let feed = with_host(|h| h.stdin_feed.is_some());
if !feed && std::io::stdin().is_terminal() {
let prompt = str_arg(args, 0);
with_host(|h| h.write_stdout_direct(&prompt));
}
let mut line = Vec::new();
match with_stdin_source(|src| src.read_until(b'\n', &mut line)) {
Ok(n) if n > 0 => {
if line.last() == Some(&b'\n') {
line.pop();
}
bytes_value(line)
}
_ => Value::bool(false),
}
}
fn fill_stdin(fname: &str, res: &Value) {
let pending = with_host(|h| {
h.stream(res).map(|s| {
(
s.source_done,
s.buf[s.pos.min(s.buf.len())..].contains(&b'\n'),
)
})
});
let Some((false, has_line)) = pending else {
return;
};
if has_line && matches!(fname, "fgets" | "fscanf") {
return;
}
let mut chunk = Vec::new();
let got = with_stdin_source(|src| match fname {
"fgets" | "fscanf" => src.read_until(b'\n', &mut chunk),
"stream_get_contents" | "fpassthru" | "file_get_contents" | "file" | "readfile" => {
src.read_to_end(&mut chunk)
}
_ => {
chunk.resize(8192, 0);
let n = src.read(&mut chunk);
chunk.truncate(*n.as_ref().unwrap_or(&0));
n
}
});
with_host(|h| {
if let Some(s) = h.stream_mut(res) {
if !matches!(got, Ok(n) if n > 0) {
s.source_done = true;
}
s.buf.extend_from_slice(&chunk);
}
});
}
pub fn write_bytes(fname: &str, res: &Value, data: &[u8]) -> Option<usize> {
let (kind, writable) = with_host(|h| h.stream(res).map(|s| (s.kind, s.writable)))?;
if !writable {
if kind == StreamKind::Plain {
with_host(|h| {
h.notice(format!(
"{fname}(): Write of {} bytes failed with errno=9 Bad file descriptor",
data.len()
))
});
}
return None;
}
match kind {
StreamKind::Stdout => with_host(|h| h.write_stdout_direct(&crate::bytes::from_bytes(data))),
StreamKind::Output => with_host(|h| h.write_out(&crate::bytes::from_bytes(data))),
StreamKind::Stderr => crate::host::PhpHost::write_err(data),
_ => {
with_host(|h| h.stream_write(res, data));
flush(res);
}
}
Some(data.len())
}
fn fopen(path: &str, mode: &str) -> Value {
if let Some(rest) = path.strip_prefix("php://") {
return open_php_wrapper("fopen", path, rest, mode);
}
let m = mode.replace(['b', 't'], "");
let plus = m.contains('+');
let first = m.chars().next().unwrap_or('\0');
if !matches!(first, 'r' | 'w' | 'a' | 'x' | 'c') {
with_host(|h| {
h.warn(format!(
"fopen({path}): Failed to open stream: `{mode}' is not a valid mode for fopen"
))
});
return Value::bool(false);
}
let fail = |e: std::io::Error| {
with_host(|h| {
h.warn(format!(
"fopen({path}): Failed to open stream: {}",
strerror(&e)
))
});
Value::bool(false)
};
let p = std::path::Path::new(path);
let mut s = Stream::new(
StreamKind::Plain,
first == 'r' || plus,
first != 'r' || plus,
);
s.path = path.to_string();
match first {
'r' => {
if p.is_dir() {
} else {
match std::fs::read(path) {
Ok(buf) => s.buf = buf,
Err(e) => return fail(e),
}
}
}
_ => {
if p.is_dir() {
return fail(std::io::Error::from_raw_os_error(21));
}
if first == 'x' && p.exists() {
return fail(std::io::Error::from_raw_os_error(17));
}
s.buf = if first == 'w' {
Vec::new()
} else {
std::fs::read(path).unwrap_or_default()
};
s.append = first == 'a';
let made = if first == 'w' || !p.exists() {
std::fs::write(path, b"")
} else {
std::fs::OpenOptions::new()
.append(true)
.open(path)
.map(|_| ())
};
if let Err(e) = made {
return fail(e);
}
}
}
with_host(|h| h.new_stream(s))
}
fn open_php_wrapper(fname: &str, url: &str, rest: &str, mode: &str) -> Value {
let lower = rest.to_ascii_lowercase();
let read_only = !mode.contains(['+', 'w', 'a', 'x', 'c']);
let s = match lower.as_str() {
"stdin" => Stream::stdio(StreamKind::Stdin),
"stdout" => Stream::stdio(StreamKind::Stdout),
"stderr" => Stream::stdio(StreamKind::Stderr),
"output" => Stream::stdio(StreamKind::Output),
"memory" => Stream::new(StreamKind::Memory, true, !read_only),
_ if lower == "temp" || lower.starts_with("temp/maxmemory:") => {
let mut s = Stream::new(StreamKind::Temp, true, !read_only);
s.spill_at = Some(match lower.strip_prefix("temp/maxmemory:") {
Some(n) => n.parse().unwrap_or(0),
None => TEMP_MAX_MEMORY,
});
s
}
_ => {
with_host(|h| {
h.warn(format!("{fname}(): Invalid php:// URL specified"));
h.warn(format!(
"{fname}({url}): Failed to open stream: operation failed"
));
});
return Value::bool(false);
}
};
let mut s = s;
s.append = matches!(s.kind, StreamKind::Memory | StreamKind::Temp) && mode.starts_with('a');
with_host(|h| h.new_stream(s))
}
pub fn flush(res: &Value) {
let data = with_host(|h| {
h.stream_mut(res).and_then(|s| {
if s.kind == StreamKind::Plain && s.dirty && !s.closed {
s.dirty = false;
Some((s.path.clone(), s.buf.clone()))
} else {
None
}
})
});
if let Some((path, buf)) = data {
let _ = std::fs::write(path, buf);
}
}
pub fn read_line(fname: &str, res: &Value) -> Option<String> {
read(fname, res, |s| s.gets(None)).map(|b| crate::bytes::from_bytes(&b))
}
fn fstat(res: &Value) -> Value {
use crate::stdlib::fileio::{stat_fields, stat_value};
let Some((kind, path, size, writable)) = with_host(|h| {
h.stream(res)
.map(|s| (s.kind, s.path.clone(), s.buf.len() as i64, s.writable))
}) else {
return Value::bool(false);
};
let real = |p: &str| match std::fs::metadata(p) {
Ok(m) => stat_value(&stat_fields(&m)),
Err(_) => Value::bool(false),
};
match kind {
StreamKind::Plain => match std::fs::metadata(&path) {
Ok(m) => {
let mut fields = stat_fields(&m);
fields[7].1 = size;
stat_value(&fields)
}
Err(_) => Value::bool(false),
},
StreamKind::Stdin => real("/dev/stdin"),
StreamKind::Stdout => real("/dev/stdout"),
StreamKind::Stderr => real("/dev/stderr"),
StreamKind::Output => Value::bool(false),
StreamKind::Memory | StreamKind::Temp => {
let mode = 0o100000 | if writable { 0o666 } else { 0o444 };
stat_value(&[
("dev", 0xC),
("ino", 0),
("mode", mode),
("nlink", 1),
("uid", 0),
("gid", 0),
("rdev", -1),
("size", size),
("atime", 0),
("mtime", 0),
("ctime", 0),
("blksize", -1),
("blocks", -1),
])
}
}
}
pub fn is_php_url(path: &str) -> bool {
path.len() > 6 && path[..6].eq_ignore_ascii_case("php://")
}
pub fn read_url(fname: &str, url: &str) -> Option<Vec<u8>> {
let res = open_php_wrapper(fname, url, &url[6..], "rb");
if matches!(res, Value::Bool(false)) {
return None;
}
let data = read(fname, &res, |s| Some(s.read(usize::MAX)));
with_host(|h| h.stream_mut(&res).map(|s| s.closed = true));
Some(data.unwrap_or_default())
}
pub fn write_url(fname: &str, url: &str, data: &[u8]) -> Option<usize> {
let res = open_php_wrapper(fname, url, &url[6..], "wb");
if matches!(res, Value::Bool(false)) {
return None;
}
let n = write_bytes(fname, &res, data);
with_host(|h| h.stream_mut(&res).map(|s| s.closed = true));
n
}
pub fn note_file_opened() {
with_host(|h| h.consume_resource_id());
}
pub fn warn_open_failed(fname: &str, path: &str, e: &std::io::Error) {
with_host(|h| {
h.warn(format!(
"{fname}({path}): Failed to open stream: {}",
strerror(e)
))
});
}
fn fgetcsv(args: &[Value]) -> Result<Value, String> {
use crate::stdlib::misc::{csv_char_arg, csv_escape_arg, csv_fields_value, php_fgetcsv};
let res = arg(args, 0);
let delimiter = csv_char_arg("fgetcsv", args, 2, "separator", b',')?;
let enclosure = csv_char_arg("fgetcsv", args, 3, "enclosure", b'"')?;
let escape = csv_escape_arg("fgetcsv", args, 4)?;
let len = match args.get(1) {
None | Some(Value::Undef) => 0,
Some(_) => int_arg(args, 1),
};
if !(0..i64::MAX).contains(&len) {
return Err(throws(
"ValueError",
format!(
"fgetcsv(): Argument #2 ($length) must be between 0 and {}",
i64::MAX - 1
),
));
}
let max = (len > 0).then_some(len as usize);
let Some(first) = read("fgetcsv", &res, |s| s.gets(max)) else {
return Ok(Value::bool(false));
};
let next = || read("fgetcsv", &res, |s| s.gets(None));
Ok(csv_fields_value(php_fgetcsv(
delimiter, enclosure, escape, first, next,
)))
}
fn fputcsv(args: &[Value]) -> Result<Value, String> {
use crate::stdlib::misc::{csv_char_arg, csv_escape_arg, CSV_NO_ESCAPE};
let res = arg(args, 0);
let delimiter = csv_char_arg("fputcsv", args, 2, "separator", b',')?;
let enclosure = csv_char_arg("fputcsv", args, 3, "enclosure", b'"')?;
let escape = csv_escape_arg("fputcsv", args, 4)?;
let eol = match args.get(5) {
None | Some(Value::Undef) => b"\n".to_vec(),
Some(_) => crate::bytes::to_bytes(&str_arg(args, 5)).into_owned(),
};
let fields = with_host(|h| h.array_pairs(&arg(args, 1))).unwrap_or_default();
let count = fields.len();
let mut line: Vec<u8> = Vec::new();
for (i, (_, v)) in fields.into_iter().enumerate() {
let field = crate::bytes::to_bytes(&with_host(|h| h.to_str_diag(&v))).into_owned();
let needs = |c: u8| field.contains(&c);
if needs(delimiter)
|| needs(enclosure)
|| (escape != CSV_NO_ESCAPE && needs(escape as u8))
|| needs(b'\n')
|| needs(b'\r')
|| needs(b'\t')
|| needs(b' ')
{
line.push(enclosure);
let mut escaped = false;
for &c in &field {
if escape != CSV_NO_ESCAPE && c as i32 == escape {
escaped = true;
} else if !escaped && c == enclosure {
line.push(enclosure);
} else {
escaped = false;
}
line.push(c);
}
line.push(enclosure);
} else {
line.extend(field);
}
if i + 1 != count {
line.push(delimiter);
}
}
line.extend(eol);
Ok(match write_bytes("fputcsv", &res, &line) {
Some(n) => Value::int(n as i64),
None => Value::bool(false),
})
}