gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit43ad2bcf43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre43ad2bcf/plugins/fs/fs.zig

54.3 KB

  1. // hl:fs plugin — native shared library
  2. // Compiled to fs.so, loaded by runtime via dlopen
  3. //
  4. // Exports:
  5. // hl_fs_file(path) → file descriptor with metadata + line iterator
  6. // hl_fs_read_file(path) → entire file as string (raw bytes, unchecked)
  7. // hl_fs_write_file(path, text, mode?) / hl_fs_write_file_hex(path, hex, mode?)
  8. // hl_fs_append_file(path, text, mode?) / hl_fs_append_file_hex(path, hex, mode?)
  9. // hl_fs_list_dir(path) → streaming directory iterator
  10. const std = @import("std");
  11. const api = @import("plugin_api");
  12. const linux = std.os.linux;
  13. const HlValue = api.HlValue;
  14. const HlObject = api.HlObject;
  15. const HlField = api.HlField;
  16. const HlIterator = api.HlIterator;
  17. const HlString = api.HlString;
  18. // the plugins' allocator (plugin_api.zig)
  19. const allocator = api.allocator;
  20. // =========================================================================
  21. // Path resolution (mission 068)
  22. //
  23. // CONTRACT: relative paths passed to hl:fs resolve against the MAIN SCRIPT's
  24. // directory, not the process CWD — Hybriel path resolution is file-relative
  25. // everywhere (import, inherit, plugin discovery), and fs follows suit.
  26. // Absolute paths are used as-is. The runtime injects the script dir via the
  27. // optional plugin hook hl_fs_set_script_dir right after dlopen.
  28. // =========================================================================
  29. var script_dir: ?[]u8 = null;
  30. export fn hl_fs_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  31. if (script_dir) |old| allocator.free(old);
  32. script_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  33. }
  34. /// A compiled binary's unpacked `ship` files (mission 316): a relative path
  35. /// one of them answers resolves there; any other as it would without it.
  36. var ship_dir: ?[]u8 = null;
  37. export fn hl_fs_set_ship_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  38. if (ship_dir) |old| allocator.free(old);
  39. ship_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  40. }
  41. /// THE READ TRACE (326 rung 12, the build cache): while a trace file is named
  42. /// — by hl:fs `traceReads(path)`, or by HL_FS_TRACE in the environment, which a build
  43. /// hands the programs it runs — every path this plugin reads, lists or probes
  44. /// is appended to it as one line, `r <path>`, `l <path>` or `e <path>`, the
  45. /// path as resolved (absolute when the process's was). A build records what it
  46. /// depends on this way; nothing else changes.
  47. var trace_path: ?[:0]u8 = null;
  48. var trace_env_read = false;
  49. export fn hl_fs_trace(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  50. trace_env_read = true;
  51. if (trace_path) |old| allocator.free(old);
  52. trace_path = null;
  53. if (argc >= 1 and argv[0].type == .hl_string) {
  54. const p = argv[0].data.string.ptr[0..argv[0].data.string.len];
  55. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  56. }
  57. return api.makeNull();
  58. }
  59. fn traceAccess(kind: u8, resolved: []const u8) void {
  60. if (!trace_env_read) {
  61. trace_env_read = true;
  62. if (std.c.getenv("HL_FS_TRACE")) |e| {
  63. const p = std.mem.span(e);
  64. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  65. }
  66. }
  67. const tp = trace_path orelse return;
  68. var cwd_buf: [4096]u8 = undefined;
  69. const line = if (resolved.len > 0 and resolved[0] == '/')
  70. std.fmt.allocPrint(allocator, "{c} {s}\n", .{ kind, resolved }) catch return
  71. else blk: {
  72. const rc: isize = @bitCast(linux.getcwd(&cwd_buf, cwd_buf.len));
  73. if (rc <= 0) return;
  74. const cwd = std.mem.sliceTo(&cwd_buf, 0);
  75. break :blk std.fmt.allocPrint(allocator, "{c} {s}/{s}\n", .{ kind, cwd, resolved }) catch return;
  76. };
  77. defer allocator.free(line);
  78. const rc = linuxOpenRc(tp, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o600);
  79. if (rc < 0) return;
  80. const fd: i32 = @intCast(rc);
  81. defer _ = linux.close(fd);
  82. _ = linux.write(fd, line.ptr, line.len);
  83. }
  84. /// hl_fs_digest(path) — the SHA-256 of a file's bytes as 64 hex digits, or
  85. /// null when it cannot be read; hl_fs_digest_text(text) — of a text's. The
  86. /// build cache's content keys (326 rung 12): hashed here, in the plugin, so
  87. /// every engine has them and nothing crosses as a value but the answer.
  88. export fn hl_fs_digest(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  89. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digest expects a string path");
  90. const path_str = argv[0].data.string;
  91. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  92. defer allocator.free(resolved);
  93. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  94. defer allocator.free(path_z);
  95. const rc = linuxOpenRc(path_z, .{}, 0);
  96. if (rc < 0) return api.makeNull();
  97. const fd: i32 = @intCast(rc);
  98. defer _ = linux.close(fd);
  99. var h = std.crypto.hash.sha2.Sha256.init(.{});
  100. var buf: [65536]u8 = undefined;
  101. while (true) {
  102. const n: isize = @bitCast(linux.read(fd, &buf, buf.len));
  103. if (n == 0) break;
  104. if (n < 0) {
  105. if (@as(usize, @intCast(-n)) == @intFromEnum(linux.E.INTR)) continue;
  106. return api.makeNull();
  107. }
  108. h.update(buf[0..@intCast(n)]);
  109. }
  110. return hexDigest(&h);
  111. }
  112. export fn hl_fs_digest_text(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  113. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digestText expects a string");
  114. const t = argv[0].data.string;
  115. var h = std.crypto.hash.sha2.Sha256.init(.{});
  116. h.update(t.ptr[0..t.len]);
  117. return hexDigest(&h);
  118. }
  119. fn hexDigest(h: *std.crypto.hash.sha2.Sha256) HlValue {
  120. var d: [32]u8 = undefined;
  121. h.final(&d);
  122. const out = allocator.alloc(u8, 64) catch return api.makeNull();
  123. const hex = "0123456789abcdef";
  124. for (d, 0..) |b, i| {
  125. out[i * 2] = hex[b >> 4];
  126. out[i * 2 + 1] = hex[b & 15];
  127. }
  128. return api.makeString(out);
  129. }
  130. /// Resolve a (possibly relative) path against the script dir. Returned slice
  131. /// is allocated with the plugin allocator; caller frees.
  132. fn resolvePath(path: []const u8) ?[]u8 {
  133. if (path.len == 0) return allocator.dupe(u8, path) catch null;
  134. if (path[0] == '/') return allocator.dupe(u8, path) catch null;
  135. if (ship_dir) |sd| {
  136. if (std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ sd, path }, 0)) |shipped| {
  137. defer allocator.free(shipped);
  138. if (std.c.access(shipped.ptr, 0) == 0) return allocator.dupe(u8, shipped) catch null;
  139. } else |_| {}
  140. }
  141. if (script_dir) |sd| {
  142. return std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, path }) catch null;
  143. }
  144. return allocator.dupe(u8, path) catch null;
  145. }
  146. // =========================================================================
  147. // Error values (mission 068): open failures are LOUD — api.makeError with
  148. // the operation, the path as the caller wrote it, and the OS reason. The
  149. // runtime turns a top-level error value into a located runtime error.
  150. // =========================================================================
  151. fn errnoText(errno: usize) []const u8 {
  152. return switch (errno) {
  153. 2 => "no such file or directory",
  154. 13 => "permission denied",
  155. 20 => "not a directory",
  156. 21 => "is a directory",
  157. 1 => "operation not permitted",
  158. 17 => "file exists",
  159. 23 => "too many open files in the system",
  160. 24 => "too many open files",
  161. 28 => "no space left on device",
  162. 30 => "read-only file system",
  163. 36 => "file name too long",
  164. 40 => "too many levels of symbolic links",
  165. else => "I/O error",
  166. };
  167. }
  168. /// What to do about it, for the two descriptor-limit errors (fd403): a docker soft limit of
  169. /// 1024 turned a boot into an unexplained "I/O error (errno 24)".
  170. fn errnoHint(errno: usize) []const u8 {
  171. return switch (errno) {
  172. 23, 24 => "raise the open-file limit (ulimit -n) or close handles",
  173. else => "relative paths resolve against the script's directory",
  174. };
  175. }
  176. fn errDeinit(val: *api.HlValue) callconv(.c) void {
  177. if (val.type == .hl_error) {
  178. const s = val.data.string;
  179. allocator.free(@constCast(s.ptr[0..s.len]));
  180. }
  181. }
  182. fn makeOpenError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  183. const msg = std.fmt.allocPrint(allocator, "{s}: cannot open '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  184. return api.makeError("fs: cannot open file");
  185. var v = api.makeError(msg);
  186. v.deinit_fn = &errDeinit;
  187. return v;
  188. }
  189. fn makeReadError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  190. const msg = std.fmt.allocPrint(allocator, "{s}: cannot read '{s}' — {s} (errno {d})", .{ op, path, errnoText(errno), errno }) catch
  191. return api.makeError("fs: cannot read file");
  192. var v = api.makeError(msg);
  193. v.deinit_fn = &errDeinit;
  194. return v;
  195. }
  196. // =========================================================================
  197. // hl_fs_file — file descriptor with metadata + line iterator
  198. // =========================================================================
  199. const FileIterState = struct {
  200. fd: i32,
  201. allocated_strings: std.array_list.Managed([]u8),
  202. done: bool,
  203. buf: [4096]u8,
  204. buf_pos: usize,
  205. buf_len: usize,
  206. };
  207. export fn hl_fs_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  208. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.file expects a string path");
  209. const path_str = argv[0].data.string;
  210. const path = path_str.ptr[0..path_str.len];
  211. // Resolve relative paths against the script dir; keep the caller's path
  212. // for the descriptor's name/path fields.
  213. const resolved = resolvePath(path) orelse return api.makeNull();
  214. defer allocator.free(resolved);
  215. traceAccess('r', resolved);
  216. // We need a null-terminated path for the OS
  217. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  218. defer allocator.free(path_z);
  219. // Open file
  220. const rc = linuxOpenRc(path_z, .{}, 0);
  221. if (rc < 0) return makeOpenError("fs.file", path, @intCast(-rc));
  222. const fd: i32 = @intCast(rc);
  223. // Stat for size, chmod, uid, gid
  224. var size: f64 = 0;
  225. var chmod: f64 = 0;
  226. var uid: f64 = 0;
  227. var gid: f64 = 0;
  228. var stat_ok = false;
  229. var statx_buf: std.os.linux.Statx = undefined;
  230. const statx_rc = std.os.linux.statx(
  231. fd,
  232. "",
  233. std.os.linux.AT.EMPTY_PATH,
  234. std.os.linux.STATX.BASIC_STATS,
  235. &statx_buf,
  236. );
  237. if (statx_rc == 0) {
  238. size = @floatFromInt(statx_buf.size);
  239. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  240. uid = @floatFromInt(statx_buf.uid);
  241. gid = @floatFromInt(statx_buf.gid);
  242. stat_ok = true;
  243. }
  244. // Extract name from path
  245. const name = if (std.mem.lastIndexOfScalar(u8, path, '/')) |idx|
  246. path[idx + 1 ..]
  247. else
  248. path;
  249. // Mime from extension
  250. const mime = mimeFromName(name);
  251. // Build fields: name, path, size, mime, chmod, user, group = 7 fields
  252. const field_count: usize = 7;
  253. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  254. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name) };
  255. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(path) };
  256. fields[2] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  257. fields[3] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  258. fields[4] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  259. if (stat_ok) {
  260. fields[5] = .{ .key = hlStr("user"), .value = api.makeNumber(uid) };
  261. fields[6] = .{ .key = hlStr("group"), .value = api.makeNumber(gid) };
  262. } else {
  263. fields[5] = .{ .key = hlStr("user"), .value = api.makeNull() };
  264. fields[6] = .{ .key = hlStr("group"), .value = api.makeNull() };
  265. }
  266. const obj = allocator.create(HlObject) catch return api.makeNull();
  267. obj.* = .{
  268. .fields = fields.ptr,
  269. .field_count = field_count,
  270. .deinit_fn = &fileObjDeinit,
  271. };
  272. // Create line iterator
  273. const iter_state = allocator.create(FileIterState) catch return api.makeNull();
  274. iter_state.* = .{
  275. .fd = fd,
  276. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  277. .done = false,
  278. .buf = undefined,
  279. .buf_pos = 0,
  280. .buf_len = 0,
  281. };
  282. const iter = allocator.create(HlIterator) catch return api.makeNull();
  283. iter.* = .{
  284. .context = @ptrCast(iter_state),
  285. .next_fn = &fileIterNext,
  286. .deinit_fn = &fileIterDeinit,
  287. };
  288. // Return object — runtime will see it has both object fields and an iterator
  289. // We pack the iterator pointer into the object by adding one more field
  290. const full_fields = allocator.alloc(HlField, field_count + 1) catch return api.makeNull();
  291. @memcpy(full_fields[0..field_count], fields);
  292. full_fields[field_count] = .{ .key = hlStr("__iter"), .value = api.makeIterator(iter) };
  293. // Free the original fields, use full_fields
  294. allocator.free(fields);
  295. obj.fields = full_fields.ptr;
  296. obj.field_count = field_count + 1;
  297. return api.makeObject(obj);
  298. }
  299. fn fileIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  300. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  301. if (state.done) return api.makeNull();
  302. var line_buf = std.array_list.Managed(u8).init(allocator);
  303. while (true) {
  304. if (state.buf_pos < state.buf_len) {
  305. const remaining = state.buf[state.buf_pos..state.buf_len];
  306. if (std.mem.indexOfScalar(u8, remaining, '\n')) |nl_pos| {
  307. line_buf.appendSlice(remaining[0..nl_pos]) catch return api.makeNull();
  308. state.buf_pos += nl_pos + 1;
  309. break;
  310. } else {
  311. line_buf.appendSlice(remaining) catch return api.makeNull();
  312. state.buf_pos = 0;
  313. state.buf_len = 0;
  314. }
  315. }
  316. // Read from file using posix read
  317. const n = linuxRead(state.fd, &state.buf) orelse {
  318. state.done = true;
  319. break;
  320. };
  321. if (n == 0) {
  322. state.done = true;
  323. break;
  324. }
  325. state.buf_pos = 0;
  326. state.buf_len = n;
  327. }
  328. if (state.done) closeIterFd(state);
  329. if (line_buf.items.len == 0 and state.done) {
  330. line_buf.deinit();
  331. return api.makeNull();
  332. }
  333. const line = line_buf.toOwnedSlice() catch return api.makeNull();
  334. state.allocated_strings.append(line) catch return api.makeNull();
  335. return api.makeString(line);
  336. }
  337. /// An iterator that ran to its end gives its fd back at once (fd403: the compiler's
  338. /// directory walks held one fd per listDir until the GC finalized them: > 1024 at boot).
  339. /// The fd is -1 afterwards; deinit closes only a still-open one.
  340. fn closeIterFd(state: anytype) void {
  341. if (state.fd >= 0) {
  342. _ = linux.close(state.fd);
  343. state.fd = -1;
  344. }
  345. }
  346. fn fileIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  347. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return));
  348. closeIterFd(state);
  349. for (state.allocated_strings.items) |s| {
  350. allocator.free(s);
  351. }
  352. state.allocated_strings.deinit();
  353. allocator.destroy(state);
  354. }
  355. fn fileObjDeinit(obj: *HlObject) callconv(.c) void {
  356. const fields = obj.fields[0..obj.field_count];
  357. // Check for iterator field and clean it up (only if not already nulled out by runtime)
  358. for (fields) |field| {
  359. if (field.value.type == .hl_iterator) {
  360. const iter = field.value.data.iterator;
  361. if (iter.deinit_fn) |deinit_fn| {
  362. deinit_fn(iter.context);
  363. }
  364. allocator.destroy(iter);
  365. }
  366. }
  367. allocator.free(fields);
  368. allocator.destroy(obj);
  369. }
  370. // =========================================================================
  371. // hl_fs_read_file — read entire file as string
  372. // =========================================================================
  373. fn readFileDeinit(val: *HlValue) callconv(.c) void {
  374. if (val.type == .hl_string) {
  375. const s = val.data.string;
  376. allocator.free(@constCast(s.ptr[0..s.len]));
  377. }
  378. }
  379. /// exists(path) → Boolean (mission 077, 074 GAP 8). The ONLY hl:fs entry point
  380. /// that never errors: it answers a question, and "no" is an answer, not a
  381. /// failure. Same script-relative resolution as everything else. Without it the
  382. /// only way to test a path was to open it and survive the error — which is why
  383. /// the retired live_server used to index `static/` blind instead of probing it.
  384. export fn hl_fs_exists(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  385. if (argc < 1 or argv[0].type != .hl_string) return api.makeBool(false);
  386. const path_str = argv[0].data.string;
  387. const path = path_str.ptr[0..path_str.len];
  388. const resolved = resolvePath(path) orelse return api.makeBool(false);
  389. defer allocator.free(resolved);
  390. traceAccess('e', resolved);
  391. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeBool(false);
  392. defer allocator.free(path_z);
  393. // statx, not open: a directory, a symlink target, a device — anything the
  394. // OS can name — counts, and nothing is opened (no fd, no side effect).
  395. var statx_buf: std.os.linux.Statx = undefined;
  396. const rc = std.os.linux.statx(
  397. std.os.linux.AT.FDCWD,
  398. path_z,
  399. 0,
  400. std.os.linux.STATX.BASIC_STATS,
  401. &statx_buf,
  402. );
  403. return api.makeBool(@as(isize, @bitCast(rc)) == 0);
  404. }
  405. /// changeTime(path) → the path's last status change (ctime, which no write can set
  406. /// back) as milliseconds since the epoch, or null when it is not there (#195). The
  407. /// build cache asks it of everything a build read: an input changed after the build
  408. /// began (a file edited, a checkout, a file made or removed in a listed directory)
  409. /// makes what the build saw differ from what the record would say. Not traced.
  410. export fn hl_fs_change_time(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  411. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  412. const path_str = argv[0].data.string;
  413. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  414. defer allocator.free(resolved);
  415. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  416. defer allocator.free(path_z);
  417. var statx_buf: std.os.linux.Statx = undefined;
  418. const rc = std.os.linux.statx(
  419. std.os.linux.AT.FDCWD,
  420. path_z,
  421. 0,
  422. std.os.linux.STATX.BASIC_STATS,
  423. &statx_buf,
  424. );
  425. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  426. const sec: f64 = @floatFromInt(statx_buf.ctime.sec);
  427. const nsec: f64 = @floatFromInt(statx_buf.ctime.nsec);
  428. return api.makeNumber(sec * 1000.0 + nsec / 1000000.0);
  429. }
  430. export fn hl_fs_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  431. return readWhole(argc, argv, false);
  432. }
  433. /// tryReadFile(path) → the file as a string, or null when the path is not
  434. /// there (ENOENT/ENOTDIR). Any other failure is an error as in readFile. For a
  435. /// file another process may delete between a probe and the read (a shared
  436. /// cache): the vanishing is an answer, not a fault.
  437. export fn hl_fs_try_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  438. return readWhole(argc, argv, true);
  439. }
  440. fn readWhole(argc: u32, argv: [*]const HlValue, absent_is_null: bool) HlValue {
  441. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.readFile expects a string path");
  442. const path_str = argv[0].data.string;
  443. const path = path_str.ptr[0..path_str.len];
  444. const resolved = resolvePath(path) orelse return api.makeNull();
  445. defer allocator.free(resolved);
  446. traceAccess('r', resolved);
  447. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  448. defer allocator.free(path_z);
  449. const rc = linuxOpenRc(path_z, .{}, 0);
  450. if (rc < 0) {
  451. const en: usize = @intCast(-rc);
  452. if (absent_is_null and (en == @intFromEnum(linux.E.NOENT) or en == @intFromEnum(linux.E.NOTDIR))) return api.makeNull();
  453. return makeOpenError("fs.readFile", path, en);
  454. }
  455. const fd: i32 = @intCast(rc);
  456. defer _ = linux.close(fd);
  457. // The whole file: no size cap (a 10 MiB cap once truncated silently, ticket #112).
  458. // A failed read is an error naming the path, never a short string.
  459. var content = std.array_list.Managed(u8).init(allocator);
  460. defer content.deinit();
  461. var buf: [65536]u8 = undefined;
  462. while (true) {
  463. const n_read: isize = @bitCast(linux.read(fd, &buf, buf.len));
  464. if (n_read == 0) break;
  465. if (n_read < 0) {
  466. const errno: usize = @intCast(-n_read);
  467. if (errno == @intFromEnum(linux.E.INTR)) continue;
  468. return makeReadError("fs.readFile", path, errno);
  469. }
  470. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readFile: out of memory reading the file");
  471. }
  472. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  473. var result = api.makeString(result_slice);
  474. result.deinit_fn = &readFileDeinit;
  475. return result;
  476. }
  477. // =========================================================================
  478. // hl_fs_list_dir — streaming directory iterator with metadata
  479. // =========================================================================
  480. const DirIterState = struct {
  481. fd: i32,
  482. base_path: []const u8,
  483. allocated_strings: std.array_list.Managed([]u8),
  484. // fd403: the WHOLE getdents64 output, read when listDir() is called, so the directory fd
  485. // is closed at once. A for-of that ends with break/return never finalizes its iterator
  486. // before the GC runs, and the compiler's own pathKind() returns from inside one: 1000+
  487. // directory fds open at the tracker's boot (docker nofile 1024). Stat is lazy, by path.
  488. raw: std.array_list.Managed(u8),
  489. dir_resolved: []u8,
  490. dents_pos: usize,
  491. dents_len: usize,
  492. done: bool,
  493. };
  494. export fn hl_fs_list_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  495. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.listDir expects a string path");
  496. const path_str = argv[0].data.string;
  497. const path = path_str.ptr[0..path_str.len];
  498. const resolved = resolvePath(path) orelse return api.makeNull();
  499. defer allocator.free(resolved);
  500. traceAccess('l', resolved);
  501. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  502. defer allocator.free(path_z);
  503. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  504. if (rc < 0) return makeOpenError("fs.listDir", path, @intCast(-rc));
  505. const fd: i32 = @intCast(rc);
  506. const path_copy = allocator.dupe(u8, path) catch {
  507. _ = linux.close(fd);
  508. return api.makeNull();
  509. };
  510. var raw = std.array_list.Managed(u8).init(allocator);
  511. var chunk: [4096]u8 align(8) = undefined;
  512. while (true) {
  513. const got = std.os.linux.getdents64(fd, &chunk, chunk.len);
  514. if (@as(isize, @bitCast(got)) <= 0) break;
  515. raw.appendSlice(chunk[0..got]) catch break;
  516. }
  517. _ = linux.close(fd);
  518. const state = allocator.create(DirIterState) catch return api.makeNull();
  519. state.* = .{
  520. .fd = -1,
  521. .base_path = path_copy,
  522. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  523. .raw = raw,
  524. .dir_resolved = allocator.dupe(u8, resolved) catch @constCast(""),
  525. .dents_pos = 0,
  526. .dents_len = raw.items.len,
  527. .done = false,
  528. };
  529. const iter = allocator.create(HlIterator) catch return api.makeNull();
  530. iter.* = .{
  531. .context = @ptrCast(state),
  532. .next_fn = &dirIterNext,
  533. .deinit_fn = &dirIterDeinit,
  534. };
  535. return api.makeIterator(iter);
  536. }
  537. fn dirIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  538. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  539. if (state.done) return api.makeNull();
  540. while (true) {
  541. // Need more directory entries?
  542. if (state.dents_pos >= state.dents_len) {
  543. state.done = true;
  544. return api.makeNull();
  545. }
  546. // Parse next dirent64
  547. const entry_ptr: *align(1) std.os.linux.dirent64 = @ptrCast(&state.raw.items[state.dents_pos]);
  548. state.dents_pos += entry_ptr.reclen;
  549. // Get name
  550. const name_ptr: [*]const u8 = @ptrCast(&entry_ptr.name);
  551. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  552. const name = name_ptr[0..name_len];
  553. // Skip . and ..
  554. if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
  555. const name_copy = allocator.dupe(u8, name) catch return api.makeNull();
  556. state.allocated_strings.append(name_copy) catch return api.makeNull();
  557. // Build full path
  558. const full_path = std.fmt.allocPrint(allocator, "{s}/{s}", .{ state.base_path, name }) catch return api.makeNull();
  559. state.allocated_strings.append(full_path) catch return api.makeNull();
  560. // Entry type from d_type
  561. const kind_str: []const u8 = switch (entry_ptr.type) {
  562. std.os.linux.DT.DIR => "directory",
  563. std.os.linux.DT.REG => "file",
  564. std.os.linux.DT.LNK => "symlink",
  565. else => "other",
  566. };
  567. // Stat for size, chmod, uid, gid
  568. var size: f64 = 0;
  569. var chmod: f64 = 0;
  570. var e_uid: f64 = 0;
  571. var e_gid: f64 = 0;
  572. // null-terminate name for statx
  573. var name_z_buf: [256]u8 = undefined;
  574. if (name.len < name_z_buf.len) {
  575. @memcpy(name_z_buf[0..name.len], name);
  576. name_z_buf[name.len] = 0;
  577. var statx_buf: std.os.linux.Statx = undefined;
  578. var stat_path: [4096]u8 = undefined;
  579. const stat_z = std.fmt.bufPrintZ(&stat_path, "{s}/{s}", .{ state.dir_resolved, name }) catch null;
  580. const src = if (stat_z) |sz| std.os.linux.statx(
  581. std.os.linux.AT.FDCWD,
  582. sz.ptr,
  583. 0,
  584. std.os.linux.STATX.BASIC_STATS,
  585. &statx_buf,
  586. ) else @as(usize, 1);
  587. if (src == 0) {
  588. size = @floatFromInt(statx_buf.size);
  589. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  590. e_uid = @floatFromInt(statx_buf.uid);
  591. e_gid = @floatFromInt(statx_buf.gid);
  592. }
  593. }
  594. const mime = mimeFromName(name_copy);
  595. // Build object: name, path, type, size, mime, chmod, user, group
  596. // The runtime's hlObjectToValue will call entryObjDeinit after conversion,
  597. // so these objects are freed immediately upon consumption.
  598. const field_count: usize = 8;
  599. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  600. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  601. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(full_path) };
  602. fields[2] = .{ .key = hlStr("type"), .value = api.makeString(kind_str) };
  603. fields[3] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  604. fields[4] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  605. fields[5] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  606. fields[6] = .{ .key = hlStr("user"), .value = api.makeNumber(e_uid) };
  607. fields[7] = .{ .key = hlStr("group"), .value = api.makeNumber(e_gid) };
  608. const obj = allocator.create(HlObject) catch return api.makeNull();
  609. obj.* = .{
  610. .fields = fields.ptr,
  611. .field_count = field_count,
  612. .deinit_fn = &entryObjDeinit,
  613. };
  614. return api.makeObject(obj);
  615. }
  616. }
  617. fn entryObjDeinit(obj: *HlObject) callconv(.c) void {
  618. allocator.free(obj.fields[0..obj.field_count]);
  619. allocator.destroy(obj);
  620. }
  621. fn dirIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  622. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));
  623. closeIterFd(state);
  624. state.raw.deinit();
  625. if (state.dir_resolved.len > 0) allocator.free(state.dir_resolved);
  626. for (state.allocated_strings.items) |s| {
  627. allocator.free(s);
  628. }
  629. state.allocated_strings.deinit();
  630. allocator.free(@constCast(state.base_path));
  631. allocator.destroy(state);
  632. }
  633. // =========================================================================
  634. // Helpers
  635. // =========================================================================
  636. /// Raw open: >= 0 is the fd, < 0 is -errno.
  637. fn linuxOpenRc(path_z: [*:0]const u8, flags: linux.O, mode: u32) isize {
  638. const rc = linux.open(path_z, flags, mode);
  639. return @bitCast(rc);
  640. }
  641. fn linuxRead(fd: i32, buf: []u8) ?usize {
  642. const rc = linux.read(fd, buf.ptr, buf.len);
  643. if (@as(isize, @bitCast(rc)) <= 0) return null;
  644. return rc;
  645. }
  646. fn hlStr(comptime s: []const u8) HlString {
  647. return .{ .ptr = s.ptr, .len = s.len };
  648. }
  649. fn mimeFromName(name: []const u8) []const u8 {
  650. const ext = if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot|
  651. name[dot..]
  652. else
  653. return "application/octet-stream";
  654. if (std.mem.eql(u8, ext, ".txt")) return "text/plain";
  655. if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return "text/html";
  656. if (std.mem.eql(u8, ext, ".css")) return "text/css";
  657. if (std.mem.eql(u8, ext, ".js")) return "text/javascript";
  658. if (std.mem.eql(u8, ext, ".json")) return "application/json";
  659. if (std.mem.eql(u8, ext, ".xml")) return "application/xml";
  660. if (std.mem.eql(u8, ext, ".png")) return "image/png";
  661. if (std.mem.eql(u8, ext, ".jpg") or std.mem.eql(u8, ext, ".jpeg")) return "image/jpeg";
  662. if (std.mem.eql(u8, ext, ".gif")) return "image/gif";
  663. if (std.mem.eql(u8, ext, ".svg")) return "image/svg+xml";
  664. if (std.mem.eql(u8, ext, ".pdf")) return "application/pdf";
  665. if (std.mem.eql(u8, ext, ".zip")) return "application/zip";
  666. if (std.mem.eql(u8, ext, ".gz")) return "application/gzip";
  667. if (std.mem.eql(u8, ext, ".mp3")) return "audio/mpeg";
  668. if (std.mem.eql(u8, ext, ".mp4")) return "video/mp4";
  669. if (std.mem.eql(u8, ext, ".wasm")) return "application/wasm";
  670. if (std.mem.eql(u8, ext, ".hl")) return "text/x-hybriel";
  671. if (std.mem.eql(u8, ext, ".md")) return "text/markdown";
  672. if (std.mem.eql(u8, ext, ".yml") or std.mem.eql(u8, ext, ".yaml")) return "text/yaml";
  673. if (std.mem.eql(u8, ext, ".toml")) return "application/toml";
  674. if (std.mem.eql(u8, ext, ".csv")) return "text/csv";
  675. if (std.mem.eql(u8, ext, ".ts")) return "text/typescript";
  676. if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return "text/x-c";
  677. if (std.mem.eql(u8, ext, ".zig")) return "text/x-zig";
  678. if (std.mem.eql(u8, ext, ".rs")) return "text/x-rust";
  679. if (std.mem.eql(u8, ext, ".py")) return "text/x-python";
  680. if (std.mem.eql(u8, ext, ".sh")) return "text/x-shellscript";
  681. if (std.mem.eql(u8, ext, ".sql")) return "application/sql";
  682. if (std.mem.eql(u8, ext, ".webp")) return "image/webp";
  683. if (std.mem.eql(u8, ext, ".ico")) return "image/x-icon";
  684. if (std.mem.eql(u8, ext, ".woff2")) return "font/woff2";
  685. if (std.mem.eql(u8, ext, ".woff")) return "font/woff";
  686. if (std.mem.eql(u8, ext, ".ttf")) return "font/ttf";
  687. return "application/octet-stream";
  688. }
  689. // ── fs.watch: an inotify LOOP SOURCE (the dev-reload bell) ───────────────────
  690. // `watch(path)` returns an event-loop source whose wake_fd IS the inotify fd,
  691. // so the loop's own epoll_wait wakes on a save — no polling anywhere. Watches
  692. // the directory RECURSIVELY at registration (dot-dirs skipped); directories
  693. // created afterwards are picked up the next time the app is restarted, which
  694. // is the honest v1 for a dev tool.
  695. //
  696. // EXCLUSIONS (mission 266). `watch(path, exclude)` takes a second argument —
  697. // a path STRING or a LIST of them, the same either-shape the plugin surface
  698. // already uses in `hl_proc_spawn` — naming directories the descent must not
  699. // enter. One argument still means "watch everything": the argument is optional
  700. // and a null is the same as absent.
  701. //
  702. // This exists because a program that knows, at startup, about a directory it
  703. // will write to constantly (hl:web's session store is the first) had NO way to
  704. // say so. The only skip the walker possessed was "the name starts with a dot",
  705. // so the framework's advice was to RENAME the directory — a lecture standing
  706. // in for a fix. The dot-dir skip STAYS; `.git` is its reason and it is a good
  707. // one. This is a second, explicit reason to skip, not a replacement.
  708. const WatchState = struct {
  709. ifd: i32,
  710. buf: [4096]u8 align(4) = undefined,
  711. len: usize = 0,
  712. pos: usize = 0,
  713. };
  714. /// LEXICAL path normalisation — collapses `//` and resolves `.` / `..`
  715. /// without touching the filesystem. It must be lexical: an excluded directory
  716. /// need not exist yet at the moment the watch is armed (hl:web resolves its
  717. /// session dir before it creates it), and realpath(2) on a missing path fails.
  718. /// Both the watch root and every exclusion go through this, so the comparison
  719. /// below is between two paths written the same way.
  720. fn normalizePath(path: []const u8) ?[]u8 {
  721. const absolute = path.len > 0 and path[0] == '/';
  722. var parts = std.ArrayListUnmanaged([]const u8).empty;
  723. defer parts.deinit(allocator);
  724. var it = std.mem.tokenizeScalar(u8, path, '/');
  725. while (it.next()) |seg| {
  726. if (std.mem.eql(u8, seg, ".")) continue;
  727. if (std.mem.eql(u8, seg, "..")) {
  728. if (parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], "..")) {
  729. _ = parts.pop();
  730. continue;
  731. }
  732. if (absolute) continue; // ".." above "/" is "/"
  733. }
  734. parts.append(allocator, seg) catch return null;
  735. }
  736. var out = std.ArrayListUnmanaged(u8).empty;
  737. defer out.deinit(allocator);
  738. for (parts.items, 0..) |seg, i| {
  739. if (absolute or i > 0) out.append(allocator, '/') catch return null;
  740. out.appendSlice(allocator, seg) catch return null;
  741. }
  742. if (out.items.len == 0) out.appendSlice(allocator, if (absolute) "/" else ".") catch return null;
  743. return allocator.dupe(u8, out.items) catch null;
  744. }
  745. /// Is `child` the directory `root`, or somewhere under it? Both must already
  746. /// be normalised. A bare `startsWith` would call `/a/sessions-old` a child of
  747. /// `/a/sessions`, which is the whole reason this is a function: the byte after
  748. /// the prefix has to BE a separator.
  749. fn pathIsInside(child: []const u8, root: []const u8) bool {
  750. if (root.len == 0) return false;
  751. if (std.mem.eql(u8, child, root)) return true;
  752. if (child.len <= root.len) return false;
  753. if (!std.mem.startsWith(u8, child, root)) return false;
  754. if (root[root.len - 1] == '/') return true; // root is "/" itself
  755. return child[root.len] == '/';
  756. }
  757. fn addWatchesRecursive(ifd: i32, dir_path: []const u8, depth: u32, excludes: []const []const u8) void {
  758. if (depth > 8) return;
  759. // The SECOND reason to skip a directory (mission 266). `dir_path` is
  760. // normalised: the root was normalised before the first call and every
  761. // child below is that root plus one plain name.
  762. for (excludes) |ex| if (pathIsInside(dir_path, ex)) return;
  763. const path_z = allocator.dupeZ(u8, dir_path) catch return;
  764. defer allocator.free(path_z);
  765. const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_TO | linux.IN.MOVED_FROM;
  766. _ = linux.inotify_add_watch(ifd, path_z, mask);
  767. // The descent walks getdents64 directly, like hl_fs_list_dir does — this
  768. // plugin speaks raw syscalls throughout and never pulls in std.fs.
  769. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  770. if (rc < 0) return;
  771. const fd: i32 = @intCast(rc);
  772. defer _ = linux.close(fd);
  773. var dents: [4096]u8 align(8) = undefined;
  774. while (true) {
  775. const got = linux.getdents64(fd, &dents, dents.len);
  776. if (@as(isize, @bitCast(got)) <= 0) break;
  777. var pos: usize = 0;
  778. while (pos < got) {
  779. const entry: *align(1) linux.dirent64 = @ptrCast(&dents[pos]);
  780. pos += entry.reclen;
  781. if (entry.type != linux.DT.DIR) continue;
  782. const name_ptr: [*]const u8 = @ptrCast(&entry.name);
  783. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  784. const name = name_ptr[0..name_len];
  785. // "." and ".." would recurse forever; every other dot-dir is noise
  786. // for a dev watcher (.git alone would cost thousands of watches).
  787. if (name.len == 0 or name[0] == '.') continue;
  788. const child = std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir_path, name }) catch continue;
  789. defer allocator.free(child);
  790. addWatchesRecursive(ifd, child, depth + 1, excludes);
  791. }
  792. }
  793. }
  794. /// One exclusion, resolved against the script dir like every other hl:fs path
  795. /// and then normalised. Appends nothing on an empty string.
  796. fn appendExclusion(list: *std.ArrayListUnmanaged([]u8), raw: []const u8) bool {
  797. if (raw.len == 0) return true;
  798. const resolved = resolvePath(raw) orelse return false;
  799. defer allocator.free(resolved);
  800. const norm = normalizePath(resolved) orelse return false;
  801. list.append(allocator, norm) catch {
  802. allocator.free(norm);
  803. return false;
  804. };
  805. return true;
  806. }
  807. export fn hl_fs_watch(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  808. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:fs: watch(path) needs a path string");
  809. const raw = argv[0].data.string.ptr[0..argv[0].data.string.len];
  810. const resolved = resolvePath(raw) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  811. defer allocator.free(resolved);
  812. const path = normalizePath(resolved) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  813. defer allocator.free(path);
  814. // THE OPTIONAL SECOND ARGUMENT: absent or null → watch everything, exactly
  815. // as before. A string is one directory; an object with numeric keys is the
  816. // loader's list shape (`hl_proc_spawn` reads its argv list the same way).
  817. var excludes = std.ArrayListUnmanaged([]u8).empty;
  818. defer {
  819. for (excludes.items) |e| allocator.free(e);
  820. excludes.deinit(allocator);
  821. }
  822. if (argc >= 2) {
  823. switch (argv[1].type) {
  824. .hl_null => {},
  825. .hl_string => {
  826. const sv = argv[1].data.string;
  827. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  828. },
  829. .hl_object => {
  830. const obj_in = argv[1].data.object;
  831. for (obj_in.fields[0..obj_in.field_count]) |field| {
  832. if (field.value.type == .hl_null) continue;
  833. if (field.value.type != .hl_string) return api.makeError("hl:fs: watch(path, exclude): every exclusion must be a path string");
  834. const sv = field.value.data.string;
  835. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  836. }
  837. },
  838. else => return api.makeError("hl:fs: watch(path, exclude): exclude is a path string or a list of path strings"),
  839. }
  840. }
  841. const rc = linux.inotify_init1(linux.IN.NONBLOCK);
  842. const ifd: i32 = @intCast(@as(isize, @bitCast(rc)));
  843. if (ifd < 0) return api.makeError("hl:fs: watch: inotify unavailable");
  844. addWatchesRecursive(ifd, path, 0, excludes.items);
  845. const state = allocator.create(WatchState) catch return api.makeError("hl:fs: out of memory");
  846. state.* = .{ .ifd = ifd };
  847. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fs: out of memory");
  848. iter.* = .{
  849. .context = @ptrCast(state),
  850. .next_fn = &watchTryNext, // non-blocking either way — event loop only
  851. .try_next_fn = &watchTryNext,
  852. .deinit_fn = &watchDeinit,
  853. .wake_fd = ifd,
  854. };
  855. return api.makeIterator(iter);
  856. }
  857. fn watchTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  858. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  859. if (st.pos >= st.len) {
  860. const r = linux.read(st.ifd, &st.buf, st.buf.len);
  861. const n: isize = @bitCast(r);
  862. if (n <= 0) return api.makeNull(); // EAGAIN: drained
  863. st.len = @intCast(n);
  864. st.pos = 0;
  865. }
  866. // one inotify_event: wd(i32) mask(u32) cookie(u32) len(u32) name[len]
  867. const base = st.pos;
  868. if (st.len - base < 16) {
  869. st.pos = st.len;
  870. return api.makeNull();
  871. }
  872. const name_len = std.mem.readInt(u32, st.buf[base + 12 ..][0..4], .little);
  873. const name_start = base + 16;
  874. var name: []const u8 = "";
  875. if (name_len > 0 and name_start + name_len <= st.len) {
  876. const raw_name = st.buf[name_start .. name_start + name_len];
  877. name = std.mem.sliceTo(raw_name, 0);
  878. }
  879. st.pos = name_start + name_len;
  880. const fields = allocator.alloc(api.HlField, 1) catch return api.makeNull();
  881. const name_copy = allocator.dupe(u8, name) catch {
  882. allocator.free(fields);
  883. return api.makeNull();
  884. };
  885. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  886. const obj = allocator.create(api.HlObject) catch {
  887. allocator.free(name_copy);
  888. allocator.free(fields);
  889. return api.makeNull();
  890. };
  891. obj.* = .{ .fields = fields.ptr, .field_count = 1, .deinit_fn = &watchEventDeinit };
  892. return api.makeObject(obj);
  893. }
  894. /// An event is the loader's to copy and ours to free (the emit soak, 2026-10-02): with
  895. /// no deinit, every inotify event of the dev watcher — each write a db makes under the
  896. /// watched root — kept its name, its field and its object for good.
  897. fn watchEventDeinit(obj: *api.HlObject) callconv(.c) void {
  898. const sv = obj.fields[0].value.data.string;
  899. allocator.free(@constCast(sv.ptr)[0..sv.len]);
  900. allocator.free(obj.fields[0..obj.field_count]);
  901. allocator.destroy(obj);
  902. }
  903. fn watchDeinit(ctx: ?*anyopaque) callconv(.c) void {
  904. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return));
  905. _ = linux.close(st.ifd);
  906. allocator.destroy(st);
  907. }
  908. // =========================================================================
  909. // THE WRITE SURFACE (2026-08-28)
  910. //
  911. // hl:fs was READ-ONLY until this block: file, readFile, listDir, exists,
  912. // watch. It could report a file's `chmod` and never set one. Session
  913. // persistence is the first thing in this tree that has to put bytes on a
  914. // disk, and the rule when the framework can do something the language
  915. // cannot is that the LANGUAGE is missing it — so the capability lands here,
  916. // as an ordinary hl:fs surface any program can use, not as a private hook
  917. // the session store reaches through.
  918. //
  919. // Three calls, and the shape of each is a decision:
  920. //
  921. // writeFile(path, contents, mode?) ATOMIC. Writes a sibling temp file,
  922. // fsyncs it, then rename()s it over the target — so a reader sees
  923. // either the whole previous file or the whole new one, never a torn
  924. // one. A half-written session file that revives as garbage is a
  925. // silent logout, and the crash that produces it is exactly the crash
  926. // nobody can reproduce. rename(2) within one directory is atomic on
  927. // every filesystem Linux ships; that is the whole reason the temp
  928. // file is a SIBLING rather than in /tmp (a cross-device rename fails).
  929. // mkDir(path, mode?) recursive, and succeeds when the
  930. // directory is already there — the caller wants it to exist, not to
  931. // be the one who created it.
  932. // remove(path) IDEMPOTENT: true when the path is
  933. // gone on return, including when it was already gone. A sweep
  934. // deleting an expired file must not fail because something else
  935. // deleted it first.
  936. //
  937. // MODES ARE EXPLICIT AND DEFAULT TIGHT. hybrilior passes no mode anywhere,
  938. // so its session files land at whatever the umask says — 0644 on a shared
  939. // box, i.e. every session on the machine readable by every other tenant.
  940. // Here the default is 0600 for a file and 0700 for a directory, and a
  941. // caller who wants them looser has to say so. This is not the kind of bug
  942. // that shows up in a test; it shows up in someone else's logs.
  943. // =========================================================================
  944. fn makeWriteError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  945. const msg = std.fmt.allocPrint(allocator, "{s}: cannot write '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  946. return api.makeError("fs: write failed");
  947. var v = api.makeError(msg);
  948. v.deinit_fn = &errDeinit;
  949. return v;
  950. }
  951. /// mkdir every missing component of `path`. Returns 0, or the errno of the
  952. /// first component that could not be created for a reason other than "it is
  953. /// already there".
  954. fn mkdirRecursive(path: []const u8, mode: u32) usize {
  955. if (path.len == 0) return 0;
  956. const buf = allocator.dupeZ(u8, path) catch return 12; // ENOMEM
  957. defer allocator.free(buf);
  958. // Walk the separators left to right, creating each prefix in turn. Index
  959. // 0 is skipped so a leading '/' is never itself a component to create.
  960. var i: usize = 1;
  961. while (i <= buf.len) : (i += 1) {
  962. const at_end = i == buf.len;
  963. if (!at_end and buf[i] != '/') continue;
  964. if (!at_end) buf[i] = 0;
  965. const rc: isize = @bitCast(linux.mkdir(buf.ptr, mode));
  966. if (!at_end) buf[i] = '/';
  967. if (rc < 0) {
  968. const errno: usize = @intCast(-rc);
  969. // EEXIST is the success case: the caller wants it to exist.
  970. if (errno != 17) return errno;
  971. }
  972. }
  973. return 0;
  974. }
  975. export fn hl_fs_mk_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  976. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.mkDir expects a string path");
  977. const path_str = argv[0].data.string;
  978. const path = path_str.ptr[0..path_str.len];
  979. var mode: u32 = 0o700;
  980. if (argc >= 2 and argv[1].type == .hl_number) mode = @intFromFloat(argv[1].data.number);
  981. const resolved = resolvePath(path) orelse return api.makeError("fs.mkDir: out of memory");
  982. defer allocator.free(resolved);
  983. const errno = mkdirRecursive(resolved, mode);
  984. if (errno != 0) return makeWriteError("fs.mkDir", path, errno);
  985. return api.makeBool(true);
  986. }
  987. const write_usage = "fs.writeFile expects (String path, String or Bytes contents, Number mode?)";
  988. export fn hl_fs_write_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  989. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  990. return api.makeError(write_usage);
  991. }
  992. const path_str = argv[0].data.string;
  993. const body_str = argv[1].data.string;
  994. return writeWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  995. }
  996. /// hl_fs_write_file_hex(path, hex, mode?) — writeFile with a Bytes (ticket
  997. /// #88): a Bytes crosses the plugin boundary as its hex text (the ABI has no
  998. /// Bytes, as hl:proc's write_hex says), is decoded here and written raw.
  999. export fn hl_fs_write_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1000. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1001. return api.makeError(write_usage);
  1002. }
  1003. const path_str = argv[0].data.string;
  1004. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1005. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.writeFile: out of memory");
  1006. defer allocator.free(raw);
  1007. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.writeFile: not a Bytes");
  1008. return writeWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1009. }
  1010. fn modeArg(argc: u32, argv: [*]const HlValue) u32 {
  1011. if (argc >= 3 and argv[2].type == .hl_number) return @intFromFloat(argv[2].data.number);
  1012. return 0o600;
  1013. }
  1014. fn writeWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1015. const resolved = resolvePath(path) orelse return api.makeError("fs.writeFile: out of memory");
  1016. defer allocator.free(resolved);
  1017. // The temp name is a SIBLING (see the block comment): rename(2) is only
  1018. // atomic within one filesystem, and /tmp is routinely a different one.
  1019. // The pid keeps two processes writing the same path off each other's temp
  1020. // file; the rename itself settles who wins the target.
  1021. const pid = linux.getpid();
  1022. const tmp = std.fmt.allocPrintSentinel(allocator, "{s}.hltmp{d}", .{ resolved, pid }, 0) catch
  1023. return api.makeError("fs.writeFile: out of memory");
  1024. defer allocator.free(tmp);
  1025. const rc = linuxOpenRc(tmp.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode);
  1026. if (rc < 0) return makeWriteError("fs.writeFile", path, @intCast(-rc));
  1027. const fd: i32 = @intCast(rc);
  1028. var wrote: usize = 0;
  1029. while (wrote < body.len) {
  1030. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1031. if (n <= 0) {
  1032. _ = linux.close(fd);
  1033. _ = linux.unlink(tmp.ptr);
  1034. return makeWriteError("fs.writeFile", path, if (n < 0) @intCast(-n) else 5);
  1035. }
  1036. wrote += @intCast(n);
  1037. }
  1038. // fsync BEFORE the rename, or the rename can land while the bytes are
  1039. // still only in the page cache — a power cut then leaves an EMPTY file
  1040. // where a complete one used to be, which is worse than either outcome.
  1041. _ = linux.fsync(fd);
  1042. _ = linux.close(fd);
  1043. // O_CREAT honours the mode only through the umask; say it outright so a
  1044. // 0600 request is 0600 whatever the process umask happens to be.
  1045. _ = linux.chmod(tmp.ptr, mode);
  1046. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.writeFile: out of memory");
  1047. defer allocator.free(path_z);
  1048. const ren: isize = @bitCast(linux.rename(tmp.ptr, path_z.ptr));
  1049. if (ren < 0) {
  1050. _ = linux.unlink(tmp.ptr);
  1051. return makeWriteError("fs.writeFile", path, @intCast(-ren));
  1052. }
  1053. return api.makeBool(true);
  1054. }
  1055. const append_usage = "fs.appendFile expects (String path, String or Bytes contents, Number mode?)";
  1056. export fn hl_fs_append_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1057. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1058. return api.makeError(append_usage);
  1059. }
  1060. const path_str = argv[0].data.string;
  1061. const body_str = argv[1].data.string;
  1062. return appendWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1063. }
  1064. /// hl_fs_append_file_hex(path, hex, mode?) — appendFile with a Bytes (ticket
  1065. /// #88), the same hex-text crossing writeFile's hex sibling uses.
  1066. export fn hl_fs_append_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1067. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1068. return api.makeError(append_usage);
  1069. }
  1070. const path_str = argv[0].data.string;
  1071. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1072. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.appendFile: out of memory");
  1073. defer allocator.free(raw);
  1074. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.appendFile: not a Bytes");
  1075. return appendWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1076. }
  1077. /// APPEND, NOT ATOMIC BY RENAME (writeFile's block comment above): an append
  1078. /// MUTATES the file that is already there, so there is no whole "old" or
  1079. /// "new" version to swap in — O_APPEND gives a narrower guarantee instead.
  1080. /// The kernel positions a single write() at the file's CURRENT end and
  1081. /// performs it as one operation, so two processes each appending a line never
  1082. /// interleave their bytes mid-line and a reader never sees a torn append —
  1083. /// which is why this is ONE write() of the whole body where writeFile's is
  1084. /// (short-write retries aside). The file is created at `mode` (default 0600,
  1085. /// same default as writeFile) if it is not there yet; O_APPEND on an existing
  1086. /// file leaves its mode untouched, same as any other open of it.
  1087. fn appendWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1088. const resolved = resolvePath(path) orelse return api.makeError("fs.appendFile: out of memory");
  1089. defer allocator.free(resolved);
  1090. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.appendFile: out of memory");
  1091. defer allocator.free(path_z);
  1092. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, mode);
  1093. if (rc < 0) return makeWriteError("fs.appendFile", path, @intCast(-rc));
  1094. const fd: i32 = @intCast(rc);
  1095. defer _ = linux.close(fd);
  1096. var wrote: usize = 0;
  1097. while (wrote < body.len) {
  1098. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1099. if (n <= 0) {
  1100. return makeWriteError("fs.appendFile", path, if (n < 0) @intCast(-n) else 5);
  1101. }
  1102. wrote += @intCast(n);
  1103. }
  1104. return api.makeBool(true);
  1105. }
  1106. export fn hl_fs_remove(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1107. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.remove expects a string path");
  1108. const path_str = argv[0].data.string;
  1109. const path = path_str.ptr[0..path_str.len];
  1110. const resolved = resolvePath(path) orelse return api.makeError("fs.remove: out of memory");
  1111. defer allocator.free(resolved);
  1112. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.remove: out of memory");
  1113. defer allocator.free(path_z);
  1114. var rc: isize = @bitCast(linux.unlink(path_z.ptr));
  1115. // an empty directory goes too (EISDIR): hybriel.hl's scratch directories
  1116. // (mission 326 rung 12), with no `rmdir` to shell out to
  1117. if (rc == -21) rc = @bitCast(linux.rmdir(path_z.ptr));
  1118. if (rc < 0) {
  1119. const errno: usize = @intCast(-rc);
  1120. // ENOENT is success: the caller asked for the path to be gone.
  1121. if (errno == 2) return api.makeBool(true);
  1122. return makeWriteError("fs.remove", path, errno);
  1123. }
  1124. return api.makeBool(true);
  1125. }
  1126. /// realPath(path) → the canonical absolute path (symlinks resolved, `.`/`..`
  1127. /// folded; realpath(3)), or null when the path is not there or cannot be
  1128. /// resolved. `/proc/self/exe` answers the running binary without a shell.
  1129. export fn hl_fs_real_path(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1130. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  1131. const path_str = argv[0].data.string;
  1132. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  1133. defer allocator.free(resolved);
  1134. traceAccess('e', resolved);
  1135. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  1136. defer allocator.free(path_z);
  1137. var buf: [std.posix.PATH_MAX]u8 = undefined;
  1138. const out = std.c.realpath(path_z.ptr, &buf) orelse return api.makeNull();
  1139. const text = allocator.dupe(u8, std.mem.span(out)) catch return api.makeNull();
  1140. var result = api.makeString(text);
  1141. result.deinit_fn = &readFileDeinit;
  1142. return result;
  1143. }

Branches

Latest commits

  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre
  • da6b20fcgitoria SG: security audit fixes (uploadMax 0, Secure cookie on https, session rotation at login, nosniff on function routes, no identity in page data) + tests/security.mjs gate + reportmre
  • f98c981fgitoria B1: report wordingmre
  • c6364cedgitoria B1: compact Markdown blocks (one kind flag per block/span, empty and false fields omitted); same rendered HTML, page values -67%mre
  • cd99d2feWIP gitoria#22: always render the repo level's slot (missing-repo boot hang), pages render nothing without a repo; hydration diagnosis in reports/G2-hydrate.mdmre
  • e5404b9breport: commit idsmre