1use std::cell::RefCell;
27use std::collections::HashMap;
28use std::io::Write;
29use std::path::{Path, PathBuf};
30use std::time::{SystemTime, UNIX_EPOCH};
31
32use lua_types::error::LuaError;
33use lua_types::value::LuaValue;
34use lua_vm::state::LuaState;
35
36struct DirIterState {
45 iter: Option<std::fs::ReadDir>,
46}
47
48thread_local! {
49 static DIR_ITER_REGISTRY: RefCell<HashMap<usize, DirIterState>> =
50 RefCell::new(HashMap::new());
51}
52
53fn path_from_bytes(bytes: &[u8]) -> Result<PathBuf, LuaError> {
58 #[cfg(unix)]
59 {
60 use std::os::unix::ffi::OsStrExt;
61 Ok(PathBuf::from(std::ffi::OsStr::from_bytes(bytes)))
62 }
63 #[cfg(not(unix))]
64 {
65 let s = std::str::from_utf8(bytes)
66 .map_err(|_| LuaError::runtime(format_args!("path is not valid UTF-8")))?;
67 Ok(PathBuf::from(s))
68 }
69}
70
71fn path_to_bytes(p: &Path) -> Vec<u8> {
75 #[cfg(unix)]
76 {
77 use std::os::unix::ffi::OsStrExt;
78 p.as_os_str().as_bytes().to_vec()
79 }
80 #[cfg(not(unix))]
81 {
82 p.to_string_lossy().into_owned().into_bytes()
83 }
84}
85
86fn push_fail(state: &mut LuaState, msg: &str) -> Result<usize, LuaError> {
89 state.push(LuaValue::Nil);
90 state.push_string(msg.as_bytes())?;
91 Ok(2)
92}
93
94fn lfs_currentdir(state: &mut LuaState) -> Result<usize, LuaError> {
99 match std::env::current_dir() {
100 Ok(p) => {
101 let bytes = path_to_bytes(&p);
102 state.push_string(&bytes)?;
103 Ok(1)
104 }
105 Err(e) => push_fail(state, &e.to_string()),
106 }
107}
108
109fn lfs_chdir(state: &mut LuaState) -> Result<usize, LuaError> {
114 let path = path_from_bytes(&state.check_arg_string(1)?)?;
115 match std::env::set_current_dir(&path) {
116 Ok(()) => {
117 state.push(LuaValue::Bool(true));
118 Ok(1)
119 }
120 Err(e) => push_fail(
121 state,
122 &format!(
123 "Unable to change working directory to '{}': {}",
124 path.display(),
125 e
126 ),
127 ),
128 }
129}
130
131fn lfs_mkdir(state: &mut LuaState) -> Result<usize, LuaError> {
136 let path = path_from_bytes(&state.check_arg_string(1)?)?;
137 match std::fs::create_dir(&path) {
138 Ok(()) => {
139 state.push(LuaValue::Bool(true));
140 Ok(1)
141 }
142 Err(e) => push_fail(state, &e.to_string()),
143 }
144}
145
146fn lfs_rmdir(state: &mut LuaState) -> Result<usize, LuaError> {
151 let path = path_from_bytes(&state.check_arg_string(1)?)?;
152 match std::fs::remove_dir(&path) {
153 Ok(()) => {
154 state.push(LuaValue::Bool(true));
155 Ok(1)
156 }
157 Err(e) => push_fail(state, &e.to_string()),
158 }
159}
160
161fn lfs_link(state: &mut LuaState) -> Result<usize, LuaError> {
170 let old_path = path_from_bytes(&state.check_arg_string(1)?)?;
171 let new_path = path_from_bytes(&state.check_arg_string(2)?)?;
172 let symlink = lua_vm::api::to_boolean(state, 3);
173
174 let result = if symlink {
175 #[cfg(unix)]
176 {
177 std::os::unix::fs::symlink(&old_path, &new_path)
178 }
179 #[cfg(windows)]
180 {
181 if old_path.is_dir() {
182 std::os::windows::fs::symlink_dir(&old_path, &new_path)
183 } else {
184 std::os::windows::fs::symlink_file(&old_path, &new_path)
185 }
186 }
187 #[cfg(not(any(unix, windows)))]
188 {
189 Err(std::io::Error::new(
190 std::io::ErrorKind::Other,
191 "symlinks not supported on this platform",
192 ))
193 }
194 } else {
195 std::fs::hard_link(&old_path, &new_path)
196 };
197
198 match result {
199 Ok(()) => {
200 state.push(LuaValue::Bool(true));
201 Ok(1)
202 }
203 Err(e) => push_fail(state, &e.to_string()),
204 }
205}
206
207fn lfs_touch(state: &mut LuaState) -> Result<usize, LuaError> {
214 let path = path_from_bytes(&state.check_arg_string(1)?)?;
215
216 let now_secs: f64 = SystemTime::now()
217 .duration_since(UNIX_EPOCH)
218 .map(|d| d.as_secs_f64())
219 .unwrap_or(0.0);
220
221 let arg2_type = lua_vm::api::lua_type_at(state, 2);
222 let atime: f64 = match arg2_type {
223 lua_types::LuaType::None | lua_types::LuaType::Nil => now_secs,
224 _ => state.check_number(2)?,
225 };
226 let arg3_type = lua_vm::api::lua_type_at(state, 3);
227 let mtime: f64 = match arg3_type {
228 lua_types::LuaType::None | lua_types::LuaType::Nil => atime,
229 _ => state.check_number(3)?,
230 };
231
232 let atime_ft = filetime::FileTime::from_unix_time(
233 atime.trunc() as i64,
234 ((atime.fract().abs()) * 1_000_000_000.0) as u32,
235 );
236 let mtime_ft = filetime::FileTime::from_unix_time(
237 mtime.trunc() as i64,
238 ((mtime.fract().abs()) * 1_000_000_000.0) as u32,
239 );
240
241 match filetime::set_file_times(&path, atime_ft, mtime_ft) {
242 Ok(()) => {
243 state.push(LuaValue::Bool(true));
244 Ok(1)
245 }
246 Err(e) => push_fail(state, &e.to_string()),
247 }
248}
249
250fn lfs_lock_free(state: &mut LuaState) -> Result<usize, LuaError> {
253 lua_vm::api::push_value(state, upvalue_index(1));
254 let lockfile = match state.pop() {
255 LuaValue::Str(s) => path_from_bytes(s.as_bytes())?,
256 _ => {
257 return Err(LuaError::runtime(format_args!(
258 "lfs.lock_dir: missing lockfile upvalue"
259 )));
260 }
261 };
262
263 match std::fs::remove_file(&lockfile) {
264 Ok(()) => {
265 state.push(LuaValue::Bool(true));
266 Ok(1)
267 }
268 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
269 state.push(LuaValue::Bool(true));
270 Ok(1)
271 }
272 Err(e) => push_fail(state, &e.to_string()),
273 }
274}
275
276fn lfs_lock_dir(state: &mut LuaState) -> Result<usize, LuaError> {
282 let dir = path_from_bytes(&state.check_arg_string(1)?)?;
283 if let Err(e) = std::fs::create_dir_all(&dir) {
284 return push_fail(state, &e.to_string());
285 }
286
287 let lockfile = dir.join("lockfile.lfs");
288 match std::fs::OpenOptions::new()
289 .write(true)
290 .create_new(true)
291 .open(&lockfile)
292 {
293 Ok(mut file) => {
294 let _ = file.write_all(b"lock");
295 }
296 Err(e) => return push_fail(state, &e.to_string()),
297 }
298
299 state.create_table(0, 1)?;
300 let lockfile_bytes = path_to_bytes(&lockfile);
301 state.push_string(&lockfile_bytes)?;
302 lua_vm::api::push_cclosure(state, lfs_lock_free, 1)?;
303 lua_vm::api::set_field(state, -2, b"free")?;
304 Ok(1)
305}
306
307fn mode_string(ft: std::fs::FileType) -> &'static [u8] {
313 if ft.is_file() {
314 b"file"
315 } else if ft.is_dir() {
316 b"directory"
317 } else if ft.is_symlink() {
318 b"link"
319 } else {
320 #[cfg(unix)]
321 {
322 use std::os::unix::fs::FileTypeExt;
323 if ft.is_socket() {
324 return b"socket";
325 }
326 if ft.is_fifo() {
327 return b"named pipe";
328 }
329 if ft.is_char_device() {
330 return b"char device";
331 }
332 if ft.is_block_device() {
333 return b"block device";
334 }
335 }
336 b"other"
337 }
338}
339
340fn system_time_to_secs(t: std::io::Result<SystemTime>) -> i64 {
344 match t {
345 Ok(st) => match st.duration_since(UNIX_EPOCH) {
346 Ok(d) => d.as_secs() as i64,
347 Err(e) => -(e.duration().as_secs() as i64),
348 },
349 Err(_) => 0,
350 }
351}
352
353fn push_attr_field(
357 state: &mut LuaState,
358 field: &[u8],
359 md: &std::fs::Metadata,
360) -> Result<bool, LuaError> {
361 match field {
362 b"mode" => {
363 state.push_string(mode_string(md.file_type()))?;
364 }
365 b"size" => {
366 state.push(LuaValue::Int(md.len() as i64));
367 }
368 b"modification" => {
369 state.push(LuaValue::Int(system_time_to_secs(md.modified())));
370 }
371 b"access" => {
372 state.push(LuaValue::Int(system_time_to_secs(md.accessed())));
373 }
374 b"change" => {
375 #[cfg(unix)]
376 {
377 use std::os::unix::fs::MetadataExt;
378 state.push(LuaValue::Int(md.ctime()));
379 }
380 #[cfg(not(unix))]
381 {
382 state.push(LuaValue::Int(system_time_to_secs(md.modified())));
383 }
384 }
385 b"permissions" => {
386 #[cfg(unix)]
387 {
388 use std::os::unix::fs::PermissionsExt;
389 let m = md.permissions().mode() & 0o777;
390 let mut buf = [b'-'; 9];
391 let bits = [
392 (0o400, 0, b'r'),
393 (0o200, 1, b'w'),
394 (0o100, 2, b'x'),
395 (0o040, 3, b'r'),
396 (0o020, 4, b'w'),
397 (0o010, 5, b'x'),
398 (0o004, 6, b'r'),
399 (0o002, 7, b'w'),
400 (0o001, 8, b'x'),
401 ];
402 for (mask, idx, ch) in bits {
403 if m & mask != 0 {
404 buf[idx] = ch;
405 }
406 }
407 state.push_string(&buf)?;
408 }
409 #[cfg(not(unix))]
410 {
411 let s = if md.permissions().readonly() {
412 b"r--r--r--"
413 } else {
414 b"rw-rw-rw-"
415 };
416 state.push_string(s)?;
417 }
418 }
419 b"nlink" => {
420 #[cfg(unix)]
421 {
422 use std::os::unix::fs::MetadataExt;
423 state.push(LuaValue::Int(md.nlink() as i64));
424 }
425 #[cfg(not(unix))]
426 {
427 state.push(LuaValue::Int(1));
428 }
429 }
430 b"uid" => {
431 #[cfg(unix)]
432 {
433 use std::os::unix::fs::MetadataExt;
434 state.push(LuaValue::Int(md.uid() as i64));
435 }
436 #[cfg(not(unix))]
437 {
438 state.push(LuaValue::Int(0));
439 }
440 }
441 b"gid" => {
442 #[cfg(unix)]
443 {
444 use std::os::unix::fs::MetadataExt;
445 state.push(LuaValue::Int(md.gid() as i64));
446 }
447 #[cfg(not(unix))]
448 {
449 state.push(LuaValue::Int(0));
450 }
451 }
452 b"dev" => {
453 #[cfg(unix)]
454 {
455 use std::os::unix::fs::MetadataExt;
456 state.push(LuaValue::Int(md.dev() as i64));
457 }
458 #[cfg(not(unix))]
459 {
460 state.push(LuaValue::Int(0));
461 }
462 }
463 b"rdev" => {
464 #[cfg(unix)]
465 {
466 use std::os::unix::fs::MetadataExt;
467 state.push(LuaValue::Int(md.rdev() as i64));
468 }
469 #[cfg(not(unix))]
470 {
471 state.push(LuaValue::Int(0));
472 }
473 }
474 b"ino" => {
475 #[cfg(unix)]
476 {
477 use std::os::unix::fs::MetadataExt;
478 state.push(LuaValue::Int(md.ino() as i64));
479 }
480 #[cfg(not(unix))]
481 {
482 state.push(LuaValue::Int(0));
483 }
484 }
485 b"blocks" => {
486 #[cfg(unix)]
487 {
488 use std::os::unix::fs::MetadataExt;
489 state.push(LuaValue::Int(md.blocks() as i64));
490 }
491 #[cfg(not(unix))]
492 {
493 state.push(LuaValue::Int(0));
494 }
495 }
496 b"blksize" => {
497 #[cfg(unix)]
498 {
499 use std::os::unix::fs::MetadataExt;
500 state.push(LuaValue::Int(md.blksize() as i64));
501 }
502 #[cfg(not(unix))]
503 {
504 state.push(LuaValue::Int(0));
505 }
506 }
507 _ => return Ok(false),
508 }
509 Ok(true)
510}
511
512fn lfs_attributes(state: &mut LuaState) -> Result<usize, LuaError> {
519 let path = path_from_bytes(&state.check_arg_string(1)?)?;
520 let md = match std::fs::metadata(&path) {
521 Ok(m) => m,
522 Err(e) => {
523 return push_fail(
524 state,
525 &format!(
526 "cannot obtain information from file '{}': {}",
527 path.display(),
528 e
529 ),
530 );
531 }
532 };
533
534 let arg2_type = lua_vm::api::lua_type_at(state, 2);
535 match arg2_type {
536 lua_types::LuaType::String => {
537 let req = state.check_arg_string(2)?;
538 if !push_attr_field(state, &req, &md)? {
539 return Err(LuaError::runtime(format_args!(
540 "invalid attribute name '{}'",
541 String::from_utf8_lossy(&req)
542 )));
543 }
544 Ok(1)
545 }
546 lua_types::LuaType::Table => {
547 lua_vm::api::push_value(state, 2);
548 populate_attr_table(state, &md)?;
549 Ok(1)
550 }
551 _ => {
552 state.create_table(0, 14)?;
553 populate_attr_table(state, &md)?;
554 Ok(1)
555 }
556 }
557}
558
559fn populate_attr_table(state: &mut LuaState, md: &std::fs::Metadata) -> Result<(), LuaError> {
562 const FIELDS: &[&[u8]] = &[
563 b"mode",
564 b"size",
565 b"modification",
566 b"access",
567 b"change",
568 b"permissions",
569 b"nlink",
570 b"uid",
571 b"gid",
572 b"dev",
573 b"rdev",
574 b"ino",
575 b"blocks",
576 b"blksize",
577 ];
578 for field in FIELDS {
579 if !push_attr_field(state, field, md)? {
580 continue;
581 }
582 lua_vm::api::set_field(state, -2, field)?;
583 }
584 Ok(())
585}
586
587fn lfs_dir_next(state: &mut LuaState) -> Result<usize, LuaError> {
593 let ud_idx = upvalue_index(1);
594 lua_vm::api::push_value(state, ud_idx);
595 let v = state.pop();
596 let id = match v {
597 LuaValue::UserData(u) => u.identity(),
598 _ => {
599 return Err(LuaError::runtime(format_args!(
600 "lfs.dir iterator: missing handle upvalue"
601 )));
602 }
603 };
604
605 let next = DIR_ITER_REGISTRY.with(|reg| {
606 let mut map = reg.borrow_mut();
607 let entry = match map.get_mut(&id) {
608 Some(e) => e,
609 None => return None,
610 };
611 let iter = match entry.iter.as_mut() {
612 Some(i) => i,
613 None => return None,
614 };
615 loop {
616 match iter.next() {
617 Some(Ok(de)) => {
618 let name = de.file_name();
619 let bytes = {
620 #[cfg(unix)]
621 {
622 use std::os::unix::ffi::OsStrExt;
623 name.as_bytes().to_vec()
624 }
625 #[cfg(not(unix))]
626 {
627 name.to_string_lossy().into_owned().into_bytes()
628 }
629 };
630 return Some(Some(bytes));
631 }
632 Some(Err(_)) => continue,
633 None => {
634 entry.iter = None;
635 return Some(None);
636 }
637 }
638 }
639 });
640
641 match next {
642 Some(Some(bytes)) => {
643 state.push_string(&bytes)?;
644 Ok(1)
645 }
646 _ => {
647 state.push(LuaValue::Nil);
648 Ok(1)
649 }
650 }
651}
652
653fn lfs_dir(state: &mut LuaState) -> Result<usize, LuaError> {
664 let path = path_from_bytes(&state.check_arg_string(1)?)?;
665 let iter = std::fs::read_dir(&path).map_err(|e| {
666 LuaError::runtime(format_args!(
667 "cannot open directory '{}': {}",
668 path.display(),
669 e
670 ))
671 })?;
672
673 let ud = state.new_userdata_typed(b"lfs.dir.handle", 0, 0)?;
674 let id = ud.identity();
675 DIR_ITER_REGISTRY.with(|reg| {
676 reg.borrow_mut()
677 .insert(id, DirIterState { iter: Some(iter) });
678 });
679
680 lua_vm::api::push_cclosure(state, lfs_dir_next, 1)?;
681 Ok(1)
682}
683
684fn upvalue_index(i: i32) -> i32 {
691 -1_001_000 - i
692}
693
694const LFS_FUNCS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
695 (b"attributes", lfs_attributes),
696 (b"chdir", lfs_chdir),
697 (b"currentdir", lfs_currentdir),
698 (b"dir", lfs_dir),
699 (b"link", lfs_link),
700 (b"lock_dir", lfs_lock_dir),
701 (b"mkdir", lfs_mkdir),
702 (b"rmdir", lfs_rmdir),
703 (b"touch", lfs_touch),
704];
705
706pub fn luaopen_lfs(state: &mut LuaState) -> Result<usize, LuaError> {
714 state.create_table(0, LFS_FUNCS.len() as i32)?;
715 for (name, func) in LFS_FUNCS {
716 lua_vm::api::push_cclosure(state, *func, 0)?;
717 lua_vm::api::set_field(state, -2, name)?;
718 }
719 Ok(1)
720}