diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c655013..4bcce53 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,8 @@ jobs: - name: Install Zig run: | - curl -sL "https://ziglang.org/download/0.15.2/zig-x86_64-linux-0.15.2.tar.xz" | tar -xJ - echo "$PWD/zig-x86_64-linux-0.15.2" >> "$GITHUB_PATH" + curl -sL "https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz" | tar -xJ + echo "$PWD/zig-x86_64-linux-0.16.0" >> "$GITHUB_PATH" - name: Format check continue-on-error: true diff --git a/.gitignore b/.gitignore index 3389c86..03cb27d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .zig-cache/ zig-out/ +zig-pkg/ diff --git a/build.zig.zon b/build.zig.zon index 4fb7064..5469450 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -2,11 +2,12 @@ .name = .sshz, .version = "0.1.0", .fingerprint = 0x138d7fea3306d410, + .minimum_zig_version = "0.16.0", .paths = .{ "build.zig", "build.zig.zon", "src" }, .dependencies = .{ .zigzag = .{ - .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.2.tar.gz", - .hash = "zigzag-0.1.0-YXwYS20gCwATYmA0IOAYQVHykNP--Dl7bKfp2UDE0K2I", + .url = "https://github.com/meszmate/zigzag/archive/refs/tags/v0.1.5.tar.gz", + .hash = "zigzag-0.1.2-YXwYS17aEQBlpxPETTrhY5leFh7vV0DpnXJbHogs4Lsv", }, }, } diff --git a/src/app.zig b/src/app.zig index 91a3d4e..a6f57b8 100644 --- a/src/app.zig +++ b/src/app.zig @@ -26,6 +26,9 @@ pub const HostEntry = struct { pub const Model = struct { screen: Screen = .list, hosts: std.ArrayList(HostEntry), + /// Indices into `hosts` that pass the active search/tag filters, in + /// display order. `selected` is an index into this list, NOT `hosts`. + visible_indices: std.ArrayList(usize), config: ssh_config.Config, meta_store: meta_mod.MetaStore, config_path: []const u8, @@ -48,6 +51,8 @@ pub const Model = struct { connect_host: ?[]const u8 = null, checker_generation: u32 = 0, pa: std.mem.Allocator, + io: std.Io = undefined, + env: *const std.process.Environ.Map = undefined, pub const SortMode = enum { name, recent, tag }; @@ -58,27 +63,30 @@ pub const Model = struct { pub fn init(self: *Model, ctx: *zz.Context) zz.Cmd(Msg) { self.pa = ctx.persistent_allocator; + self.io = ctx.io; + self.env = ctx.environ_map; - self.hosts = .{}; - self.search_text = .{}; - self.all_tags = .{}; + self.hosts = .empty; + self.visible_indices = .empty; + self.search_text = .empty; + self.all_tags = .empty; // Load config - self.config_path = ssh_config.defaultConfigPath(self.pa) catch "/dev/null"; - self.meta_path = meta_mod.defaultMetaPath(self.pa) catch "/dev/null"; - self.backup_dir = meta_mod.defaultBackupDir(self.pa) catch "/dev/null"; + self.config_path = ssh_config.defaultConfigPath(self.pa, self.env) catch "/dev/null"; + self.meta_path = meta_mod.defaultMetaPath(self.pa, self.env) catch "/dev/null"; + self.backup_dir = meta_mod.defaultBackupDir(self.pa, self.env) catch "/dev/null"; - self.config = ssh_config.readFile(self.pa, self.config_path) catch ssh_config.Config{ + self.config = ssh_config.readFile(self.pa, self.io, self.config_path) catch ssh_config.Config{ .hosts = &.{}, .raw_lines = &.{}, }; - self.meta_store = meta_mod.readFile(self.pa, self.meta_path) catch meta_mod.MetaStore.initWith(self.pa); + self.meta_store = meta_mod.readFile(self.pa, self.io, self.meta_path) catch meta_mod.MetaStore.initWith(self.pa); self.rebuildHostList(); // Status checker - self.result_queue = checker_mod.ResultQueue.init(self.pa); - self.status_checker = checker_mod.StatusChecker.init(&self.result_queue, self.pa); + self.result_queue = checker_mod.ResultQueue.init(self.pa, self.io); + self.status_checker = checker_mod.StatusChecker.init(&self.result_queue, self.pa, self.io); self.startStatusChecks(); self.collectTags(); @@ -88,6 +96,7 @@ pub const Model = struct { pub fn deinit(self: *Model) void { self.status_checker.deinit(); self.hosts.deinit(self.pa); + self.visible_indices.deinit(self.pa); self.search_text.deinit(self.pa); self.all_tags.deinit(self.pa); self.result_queue.deinit(); @@ -106,10 +115,56 @@ pub const Model = struct { .status = .unknown, }) catch {}; } + self.rebuildVisibleIndices(); + } + + fn rebuildVisibleIndices(self: *Model) void { + self.visible_indices.clearRetainingCapacity(); + for (self.hosts.items, 0..) |entry, i| { + if (!self.entryMatchesFilters(entry)) continue; + self.visible_indices.append(self.pa, i) catch {}; + } + // Clamp `selected` so it stays in range when filters shrink the list. + if (self.selected >= self.visible_indices.items.len) { + self.selected = if (self.visible_indices.items.len == 0) 0 else self.visible_indices.items.len - 1; + } + } + + fn entryMatchesFilters(self: *const Model, entry: HostEntry) bool { + if (self.search_text.items.len > 0 and !matchesSearch(entry, self.search_text.items)) return false; + if (self.tag_filter) |tag| { + if (!hasTag(entry, tag)) return false; + } + return true; + } + + fn matchesSearch(entry: HostEntry, search: []const u8) bool { + if (std.mem.indexOf(u8, entry.config.name, search) != null) return true; + if (entry.config.hostname) |hn| { + if (std.mem.indexOf(u8, hn, search) != null) return true; + } + if (entry.config.user) |u| { + if (std.mem.indexOf(u8, u, search) != null) return true; + } + if (entry.meta) |m| { + for (m.tags) |tag| { + if (std.mem.indexOf(u8, tag, search) != null) return true; + } + } + return false; + } + + fn hasTag(entry: HostEntry, tag: []const u8) bool { + if (entry.meta) |m| { + for (m.tags) |t| { + if (std.mem.eql(u8, t, tag)) return true; + } + } + return false; } fn startStatusChecks(self: *Model) void { - var requests: std.ArrayList(checker_mod.CheckRequest) = .{}; + var requests: std.ArrayList(checker_mod.CheckRequest) = .empty; defer requests.deinit(self.pa); for (self.hosts.items, 0..) |entry, i| { @@ -135,7 +190,10 @@ pub const Model = struct { for (entry.value_ptr.tags) |tag| { var found = false; for (self.all_tags.items) |existing| { - if (std.mem.eql(u8, existing, tag)) { found = true; break; } + if (std.mem.eql(u8, existing, tag)) { + found = true; + break; + } } if (!found) self.all_tags.append(self.pa, tag) catch {}; } @@ -183,7 +241,9 @@ pub const Model = struct { if (self.screen == .help) { switch (k.key) { .escape => self.screen = .list, - .char => |c| if (c == '?') { self.screen = .list; }, + .char => |c| if (c == '?') { + self.screen = .list; + }, else => {}, } return .none; @@ -191,21 +251,32 @@ pub const Model = struct { // Search mode if (self.search_active) { + var changed = false; switch (k.key) { .escape => { self.search_active = false; self.search_text.clearRetainingCapacity(); + changed = true; }, .backspace => { - if (self.search_text.items.len > 0) _ = self.search_text.pop(); + if (self.search_text.items.len > 0) { + _ = self.search_text.pop(); + changed = true; + } }, .enter => self.search_active = false, .char => |c| { - if (c < 128) self.search_text.append(self.pa, @intCast(c)) catch {}; + if (c < 128) { + self.search_text.append(self.pa, @intCast(c)) catch {}; + changed = true; + } }, else => {}, } - self.selected = 0; + if (changed) { + self.selected = 0; + self.rebuildVisibleIndices(); + } return .none; } @@ -241,9 +312,10 @@ pub const Model = struct { self.screen = .add_form; }, 'e' => { - if (self.hosts.items.len > 0 and self.selected < self.hosts.items.len) { + if (self.selected < self.visible_indices.items.len) { var form = host_form.FormState.init(self.pa); - const entry = self.hosts.items[self.selected]; + const hi = self.visible_indices.items[self.selected]; + const entry = self.hosts.items[hi]; form.editing_host = entry.config.name; // Load values form.fields[0].setValue(entry.config.name) catch {}; @@ -262,14 +334,15 @@ pub const Model = struct { } }, 'd' => { - if (self.hosts.items.len > 0) self.confirm_delete = true; + if (self.visible_indices.items.len > 0) self.confirm_delete = true; }, 'r' => self.startStatusChecks(), 's' => self.cycleSortMode(), 't' => self.cycleTagFilter(), 'f' => { - if (self.selected < self.hosts.items.len) { - const entry = self.hosts.items[self.selected]; + if (self.selected < self.visible_indices.items.len) { + const hi = self.visible_indices.items[self.selected]; + const entry = self.hosts.items[hi]; const fwds = if (entry.meta) |m| m.port_forwards else &.{}; self.forward_state = forward_view.ForwardState.init(self.pa, entry.config.name, fwds); self.screen = .forward_select; @@ -279,7 +352,7 @@ pub const Model = struct { else => {}, }, .enter => { - if (self.hosts.items.len > 0 and self.selected < self.hosts.items.len) { + if (self.selected < self.visible_indices.items.len) { self.connectToSelected(); return .quit; } @@ -347,7 +420,7 @@ pub const Model = struct { } fn moveDown(self: *Model) void { - if (self.selected + 1 < self.hosts.items.len) self.selected += 1; + if (self.selected + 1 < self.visible_indices.items.len) self.selected += 1; } fn cycleSortMode(self: *Model) void { @@ -357,6 +430,8 @@ pub const Model = struct { .tag => .name, }; self.sortHosts(); + // hosts.items has been reordered; visible_indices points to old slots. + self.rebuildVisibleIndices(); } fn sortHosts(self: *Model) void { @@ -389,13 +464,15 @@ pub const Model = struct { if (self.tag_filter_index > self.all_tags.items.len) self.tag_filter_index = 0; self.tag_filter = if (self.tag_filter_index == 0) null else self.all_tags.items[self.tag_filter_index - 1]; self.selected = 0; + self.rebuildVisibleIndices(); } fn connectToSelected(self: *Model) void { - if (self.selected >= self.hosts.items.len) return; - const entry = self.hosts.items[self.selected]; - self.meta_store.recordConnection(self.pa, entry.config.name) catch {}; - meta_mod.writeFile(self.pa, &self.meta_store, self.meta_path) catch {}; + if (self.selected >= self.visible_indices.items.len) return; + const hi = self.visible_indices.items[self.selected]; + const entry = self.hosts.items[hi]; + // Connection metadata is recorded by `directConnect` after the TUI + // exits, so don't record here as well — that double-counts. self.connect_host = self.pa.dupe(u8, entry.config.name) catch null; } @@ -407,8 +484,10 @@ pub const Model = struct { fn saveForm(self: *Model) void { const form = &(self.form_state orelse return); - // IMPORTANT: dupe values before form deinit - const name = self.pa.dupe(u8, form.getValue(.name)) catch return; + // The form values stay valid until handleFormKey calls form.deinit + // after saveForm returns. ssh_config.addHost / meta_store.setTags + // both deep-copy what they need, so we can pass form-owned slices. + const name = form.getValue(.name); if (name.len == 0) return; const hostname_val = form.getValue(.hostname); @@ -421,11 +500,11 @@ pub const Model = struct { const new_host = ssh_config.Host{ .name = name, - .hostname = if (hostname_val.len > 0) (self.pa.dupe(u8, hostname_val) catch null) else null, - .user = if (user_val.len > 0) (self.pa.dupe(u8, user_val) catch null) else null, + .hostname = if (hostname_val.len > 0) hostname_val else null, + .user = if (user_val.len > 0) user_val else null, .port = if (port_val.len > 0) std.fmt.parseInt(u16, port_val, 10) catch null else null, - .identity_file = if (identity_val.len > 0) (self.pa.dupe(u8, identity_val) catch null) else null, - .proxy_jump = if (proxy_val.len > 0) (self.pa.dupe(u8, proxy_val) catch null) else null, + .identity_file = if (identity_val.len > 0) identity_val else null, + .proxy_jump = if (proxy_val.len > 0) proxy_val else null, .address_family = if (addr_family_val.len > 0) ssh_config.AddressFamily.fromString(addr_family_val) else null, }; @@ -446,20 +525,19 @@ pub const Model = struct { } ssh_config.addHost(self.pa, &self.config, new_host) catch {}; - ssh_config.writeFile(self.pa, &self.config, self.config_path, self.backup_dir) catch {}; - - // Save tags - if (tags_val.len > 0) { - var tags: std.ArrayList([]const u8) = .{}; - defer tags.deinit(self.pa); - var tag_it = std.mem.splitScalar(u8, tags_val, ','); - while (tag_it.next()) |tag| { - const trimmed = std.mem.trim(u8, tag, " "); - if (trimmed.len > 0) tags.append(self.pa, trimmed) catch {}; - } - self.meta_store.setTags(self.pa, name, tags.items) catch {}; + ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path, self.backup_dir) catch {}; + + // Save tags. Always call setTags so clearing the tags field in the + // edit form actually persists an empty tag list. + var tags: std.ArrayList([]const u8) = .empty; + defer tags.deinit(self.pa); + var tag_it = std.mem.splitScalar(u8, tags_val, ','); + while (tag_it.next()) |tag| { + const trimmed = std.mem.trim(u8, tag, " "); + if (trimmed.len > 0) tags.append(self.pa, trimmed) catch {}; } - meta_mod.writeFile(self.pa, &self.meta_store, self.meta_path) catch {}; + self.meta_store.setTags(self.pa, name, tags.items) catch {}; + meta_mod.writeFile(self.pa, self.io, &self.meta_store, self.meta_path) catch {}; self.rebuildHostList(); self.collectTags(); @@ -468,23 +546,28 @@ pub const Model = struct { } fn deleteSelectedHost(self: *Model) void { - if (self.selected >= self.hosts.items.len) return; + if (self.selected >= self.visible_indices.items.len) return; + // Look up the config entry by name from the visible list so sorting + // and tag-filtering don't desynchronise the display index from the + // raw config order. + const hi = self.visible_indices.items[self.selected]; + const selected_name = self.hosts.items[hi].config.name; var config_index: ?usize = null; - var display_i: usize = 0; for (self.config.hosts, 0..) |h, ci| { - if (h.is_wildcard) continue; - if (display_i == self.selected) { config_index = ci; break; } - display_i += 1; + if (std.mem.eql(u8, h.name, selected_name)) { + config_index = ci; + break; + } } if (config_index) |ci| { ssh_config.removeHost(self.pa, &self.config, ci) catch {}; - ssh_config.writeFile(self.pa, &self.config, self.config_path, self.backup_dir) catch {}; + ssh_config.writeFile(self.pa, self.io, &self.config, self.config_path, self.backup_dir) catch {}; } + // rebuildHostList → rebuildVisibleIndices clamps `selected` for us. self.rebuildHostList(); - if (self.selected > 0 and self.selected >= self.hosts.items.len) self.selected -= 1; self.notification = "Host deleted"; self.notification_timer = 30; } diff --git a/src/checker.zig b/src/checker.zig index 7bfcc99..fd5a0d6 100644 --- a/src/checker.zig +++ b/src/checker.zig @@ -20,12 +20,13 @@ pub const CheckRequest = struct { }; pub const ResultQueue = struct { - mutex: std.Thread.Mutex = .{}, - results: std.ArrayList(CheckResult) = .{}, + mutex: std.Io.Mutex = std.Io.Mutex.init, + results: std.ArrayList(CheckResult) = .empty, allocator: std.mem.Allocator, + io: std.Io, - pub fn init(allocator: std.mem.Allocator) ResultQueue { - return .{ .allocator = allocator }; + pub fn init(allocator: std.mem.Allocator, io: std.Io) ResultQueue { + return .{ .allocator = allocator, .io = io }; } pub fn deinit(self: *ResultQueue) void { @@ -33,14 +34,14 @@ pub const ResultQueue = struct { } pub fn push(self: *ResultQueue, result: CheckResult) void { - self.mutex.lock(); - defer self.mutex.unlock(); + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); self.results.append(self.allocator, result) catch {}; } pub fn drain(self: *ResultQueue, allocator: std.mem.Allocator) []CheckResult { - self.mutex.lock(); - defer self.mutex.unlock(); + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); if (self.results.items.len == 0) return &.{}; return self.results.toOwnedSlice(allocator) catch return &.{}; } @@ -51,19 +52,21 @@ pub const StatusChecker = struct { active_count: std.atomic.Value(u32), max_concurrent: u32 = 3, shutdown: std.atomic.Value(bool), - threads: std.ArrayList(std.Thread) = .{}, - threads_mutex: std.Thread.Mutex = .{}, + threads: std.ArrayList(std.Thread) = .empty, + threads_mutex: std.Io.Mutex = std.Io.Mutex.init, dispatcher_thread: ?std.Thread = null, generation: std.atomic.Value(u32), allocator: std.mem.Allocator, + io: std.Io, - pub fn init(queue: *ResultQueue, allocator: std.mem.Allocator) StatusChecker { + pub fn init(queue: *ResultQueue, allocator: std.mem.Allocator, io: std.Io) StatusChecker { return .{ .queue = queue, .active_count = std.atomic.Value(u32).init(0), .shutdown = std.atomic.Value(bool).init(false), .generation = std.atomic.Value(u32).init(0), .allocator = allocator, + .io = io, }; } @@ -78,9 +81,12 @@ pub const StatusChecker = struct { } fn joinAllThreads(self: *StatusChecker) void { - self.threads_mutex.lock(); - const threads = self.threads.toOwnedSlice(self.allocator) catch return; - self.threads_mutex.unlock(); + self.threads_mutex.lockUncancelable(self.io); + const threads = self.threads.toOwnedSlice(self.allocator) catch { + self.threads_mutex.unlock(self.io); + return; + }; + self.threads_mutex.unlock(self.io); for (threads) |t| t.join(); self.allocator.free(threads); } @@ -131,13 +137,13 @@ pub const StatusChecker = struct { _ = self.active_count.fetchSub(1, .release); continue; }; - self.threads_mutex.lock(); + self.threads_mutex.lockUncancelable(self.io); self.threads.append(self.allocator, thread) catch { - self.threads_mutex.unlock(); + self.threads_mutex.unlock(self.io); thread.join(); continue; }; - self.threads_mutex.unlock(); + self.threads_mutex.unlock(self.io); } } @@ -145,13 +151,22 @@ pub const StatusChecker = struct { defer _ = self.active_count.fetchSub(1, .release); if (self.shutdown.load(.acquire)) return; - const status = tcpCheck(hostname, port); + const status = tcpCheck(self.io, hostname, port); self.queue.push(.{ .host_index = host_index, .status = status, .generation = gen }); } }; -fn tcpCheck(hostname: []const u8, port: u16) HostStatus { - const stream = std.net.tcpConnectToHost(std.heap.page_allocator, hostname, port) catch return .offline; - stream.close(); +fn tcpCheck(io: std.Io, hostname: []const u8, port: u16) HostStatus { + // Try IPv4/IPv6 literals first; HostName.init rejects ':' so a bare IPv6 + // address would otherwise always report offline. + if (std.Io.net.IpAddress.parse(hostname, port)) |addr| { + const stream = addr.connect(io, .{ .mode = .stream }) catch return .offline; + stream.close(io); + return .online; + } else |_| {} + + const host = std.Io.net.HostName.init(hostname) catch return .offline; + const stream = host.connect(io, port, .{ .mode = .stream }) catch return .offline; + stream.close(io); return .online; } diff --git a/src/main.zig b/src/main.zig index 948d29c..a22f1f0 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5,42 +5,40 @@ const app = @import("app"); const version = "0.1.0"; -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); +pub fn main(init: std.process.Init) !void { + const allocator = init.gpa; + const arena_allocator = init.arena.allocator(); - const args = try std.process.argsAlloc(allocator); - defer std.process.argsFree(allocator, args); + const args = try init.minimal.args.toSlice(arena_allocator); if (args.len >= 2 and std.mem.eql(u8, args[1], "--help")) { - printUsage(); + printUsage(init.io); return; } if (args.len >= 2 and std.mem.eql(u8, args[1], "--version")) { - const file = std.fs.File{ .handle = std.posix.STDOUT_FILENO }; + const file = std.Io.File.stdout(); var buf: [256]u8 = undefined; - var w = file.writer(&buf); + var w = file.writer(init.io, &buf); try w.interface.print("sshz {s}\n", .{version}); try w.interface.flush(); return; } // sshz [command...] — direct connect - if (args.len >= 2 and args[1][0] != '-') { - try directConnect(allocator, args[1], args[2..]); + if (args.len >= 2 and args[1].len > 0 and args[1][0] != '-') { + try directConnect(allocator, init.io, init.environ_map, args[1], args[2..]); return; } // sshz — launch TUI - try launchTui(allocator); + try launchTui(init); } -fn printUsage() void { - const file = std.fs.File{ .handle = std.posix.STDOUT_FILENO }; +fn printUsage(io: std.Io) void { + const file = std.Io.File.stdout(); var buf: [4096]u8 = undefined; - var w = file.writer(&buf); + var w = file.writer(io, &buf); w.interface.print( \\SSHZ - SSH Connection Manager \\ @@ -55,8 +53,9 @@ fn printUsage() void { w.interface.flush() catch {}; } -fn launchTui(allocator: std.mem.Allocator) !void { - var program = try zz.Program(app.Model).init(allocator); +fn launchTui(init: std.process.Init) !void { + const allocator = init.gpa; + var program = try zz.Program(app.Model).init(init.gpa, init.io, init.environ_map); try program.run(); // Grab connect_host before deinit frees it @@ -73,23 +72,23 @@ fn launchTui(allocator: std.mem.Allocator) !void { program.deinit(); if (connect_host) |host_name| { - try directConnect(allocator, host_name, &.{}); + try directConnect(allocator, init.io, init.environ_map, host_name, &.{}); } } -fn directConnect(allocator: std.mem.Allocator, host_name: []const u8, extra_args: []const [:0]u8) !void { +fn directConnect(allocator: std.mem.Allocator, io: std.Io, env: *const std.process.Environ.Map, host_name: []const u8, extra_args: []const [:0]const u8) !void { // Record connection in meta.json - const meta_path = try meta_mod.defaultMetaPath(allocator); + const meta_path = try meta_mod.defaultMetaPath(allocator, env); defer allocator.free(meta_path); - var store = try meta_mod.readFile(allocator, meta_path); + var store = try meta_mod.readFile(allocator, io, meta_path); defer store.deinit(allocator); - try store.recordConnection(allocator, host_name); - meta_mod.writeFile(allocator, &store, meta_path) catch {}; + try store.recordConnection(allocator, io, host_name); + meta_mod.writeFile(allocator, io, &store, meta_path) catch {}; // Build args - var argv: std.ArrayList([]const u8) = .{}; + var argv: std.ArrayList([]const u8) = .empty; defer argv.deinit(allocator); try argv.append(allocator, "ssh"); @@ -97,15 +96,16 @@ fn directConnect(allocator: std.mem.Allocator, host_name: []const u8, extra_args for (extra_args) |arg| try argv.append(allocator, arg); // Exec ssh - var child = std.process.Child.init(argv.items, allocator); - child.stdin_behavior = .Inherit; - child.stdout_behavior = .Inherit; - child.stderr_behavior = .Inherit; - try child.spawn(); - const term = try child.wait(); + var child = try std.process.spawn(io, .{ + .argv = argv.items, + .stdin = .inherit, + .stdout = .inherit, + .stderr = .inherit, + }); + const term = try child.wait(io); switch (term) { - .Exited => |code| if (code != 0) std.process.exit(code), + .exited => |code| if (code != 0) std.process.exit(code), else => std.process.exit(1), } } diff --git a/src/meta.zig b/src/meta.zig index bc0bd6d..e4920e2 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -45,8 +45,8 @@ pub const MetaStore = struct { return self.entries.getPtr(name); } - pub fn recordConnection(self: *MetaStore, allocator: std.mem.Allocator, name: []const u8) !void { - const now = std.time.timestamp(); + pub fn recordConnection(self: *MetaStore, allocator: std.mem.Allocator, io: std.Io, name: []const u8) !void { + const now = std.Io.Timestamp.now(io, .real).toSeconds(); if (self.entries.getPtr(name)) |entry| { entry.last_connected = now; entry.connect_count += 1; @@ -121,7 +121,7 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !MetaStore { const name = try allocator.dupe(u8, entry.key_ptr.*); const obj = entry.value_ptr.object; - var tags_list: std.ArrayList([]const u8) = .{}; + var tags_list: std.ArrayList([]const u8) = .empty; defer tags_list.deinit(allocator); if (obj.get("tags")) |tags_val| { for (tags_val.array.items) |tag| { @@ -129,7 +129,7 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !MetaStore { } } - var fwds_list: std.ArrayList(PortForward) = .{}; + var fwds_list: std.ArrayList(PortForward) = .empty; defer fwds_list.deinit(allocator); if (obj.get("port_forwards")) |fwds_val| { for (fwds_val.array.items) |fwd| { @@ -157,8 +157,30 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !MetaStore { return store; } +/// Append a JSON string literal (including surrounding quotes) with proper +/// escaping for `"`, `\`, and ASCII control characters. +fn appendJsonString(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, s: []const u8) !void { + try buf.append(allocator, '"'); + for (s) |c| switch (c) { + '"' => try buf.appendSlice(allocator, "\\\""), + '\\' => try buf.appendSlice(allocator, "\\\\"), + '\n' => try buf.appendSlice(allocator, "\\n"), + '\r' => try buf.appendSlice(allocator, "\\r"), + '\t' => try buf.appendSlice(allocator, "\\t"), + 0x08 => try buf.appendSlice(allocator, "\\b"), + 0x0C => try buf.appendSlice(allocator, "\\f"), + 0x00...0x07, 0x0B, 0x0E...0x1F => { + var hex_buf: [6]u8 = undefined; + const hex = std.fmt.bufPrint(&hex_buf, "\\u{x:0>4}", .{c}) catch unreachable; + try buf.appendSlice(allocator, hex); + }, + else => try buf.append(allocator, c), + }; + try buf.append(allocator, '"'); +} + pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const u8 { - var buf: std.ArrayList(u8) = .{}; + var buf: std.ArrayList(u8) = .empty; defer buf.deinit(allocator); try buf.appendSlice(allocator, "{\n \"version\": "); @@ -172,15 +194,13 @@ pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const while (it.next()) |entry| { if (!first) try buf.appendSlice(allocator, ","); first = false; - try buf.appendSlice(allocator, "\n \""); - try buf.appendSlice(allocator, entry.key_ptr.*); - try buf.appendSlice(allocator, "\": {\n \"tags\": ["); + try buf.appendSlice(allocator, "\n "); + try appendJsonString(&buf, allocator, entry.key_ptr.*); + try buf.appendSlice(allocator, ": {\n \"tags\": ["); for (entry.value_ptr.tags, 0..) |tag, i| { if (i > 0) try buf.appendSlice(allocator, ", "); - try buf.appendSlice(allocator, "\""); - try buf.appendSlice(allocator, tag); - try buf.appendSlice(allocator, "\""); + try appendJsonString(&buf, allocator, tag); } try buf.appendSlice(allocator, "],\n \"last_connected\": "); @@ -193,13 +213,13 @@ pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const for (entry.value_ptr.port_forwards, 0..) |fwd, i| { if (i > 0) try buf.appendSlice(allocator, ", "); - try buf.appendSlice(allocator, "{\"type\": \""); - try buf.appendSlice(allocator, fwd.forward_type); - try buf.appendSlice(allocator, "\", \"bind\": \""); - try buf.appendSlice(allocator, fwd.bind); - try buf.appendSlice(allocator, "\", \"target\": \""); - try buf.appendSlice(allocator, fwd.target); - try buf.appendSlice(allocator, "\"}"); + try buf.appendSlice(allocator, "{\"type\": "); + try appendJsonString(&buf, allocator, fwd.forward_type); + try buf.appendSlice(allocator, ", \"bind\": "); + try appendJsonString(&buf, allocator, fwd.bind); + try buf.appendSlice(allocator, ", \"target\": "); + try appendJsonString(&buf, allocator, fwd.target); + try buf.append(allocator, '}'); } try buf.appendSlice(allocator, "]\n }"); @@ -209,48 +229,50 @@ pub fn serialize(allocator: std.mem.Allocator, store: *const MetaStore) ![]const return try buf.toOwnedSlice(allocator); } -pub fn readFile(allocator: std.mem.Allocator, path: []const u8) !MetaStore { - const file = std.fs.cwd().openFile(path, .{}) catch |err| switch (err) { +pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !MetaStore { + const cwd = std.Io.Dir.cwd(); + const content = cwd.readFileAlloc(io, path, allocator, .limited(1024 * 1024)) catch |err| switch (err) { error.FileNotFound => return MetaStore.initWith(allocator), else => return err, }; - defer file.close(); - const content = try file.readToEndAlloc(allocator, 1024 * 1024); defer allocator.free(content); return parse(allocator, content) catch MetaStore.initWith(allocator); } -pub fn writeFile(allocator: std.mem.Allocator, store: *const MetaStore, path: []const u8) !void { +pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, store: *const MetaStore, path: []const u8) !void { const content = try serialize(allocator, store); defer allocator.free(content); const dir_path = std.fs.path.dirname(path) orelse "."; const basename = std.fs.path.basename(path); - std.fs.cwd().makePath(dir_path) catch {}; + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, dir_path); var tmp_buf: [256]u8 = undefined; const tmp_name = std.fmt.bufPrint(&tmp_buf, ".{s}.tmp", .{basename}) catch return error.NameTooLong; - var dir_fd = try std.fs.cwd().openDir(dir_path, .{}); - defer dir_fd.close(); + var dir_fd = try cwd.openDir(io, dir_path, .{}); + defer dir_fd.close(io); - const tmp_file = try dir_fd.createFile(tmp_name, .{}); - tmp_file.writeAll(content) catch |e| { - tmp_file.close(); - return e; - }; - tmp_file.close(); + { + const tmp_file = try dir_fd.createFile(io, tmp_name, .{}); + defer tmp_file.close(io); + var write_buf: [4096]u8 = undefined; + var w = tmp_file.writer(io, &write_buf); + try w.interface.writeAll(content); + try w.interface.flush(); + } - try dir_fd.rename(tmp_name, basename); + try dir_fd.rename(tmp_name, dir_fd, basename, io); } -pub fn defaultMetaPath(allocator: std.mem.Allocator) ![]const u8 { - const home = std.posix.getenv("HOME") orelse return error.NoHome; +pub fn defaultMetaPath(allocator: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const u8 { + const home = env.get("HOME") orelse return error.NoHome; return std.fmt.allocPrint(allocator, "{s}/.config/sshz/meta.json", .{home}); } -pub fn defaultBackupDir(allocator: std.mem.Allocator) ![]const u8 { - const home = std.posix.getenv("HOME") orelse return error.NoHome; +pub fn defaultBackupDir(allocator: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const u8 { + const home = env.get("HOME") orelse return error.NoHome; return std.fmt.allocPrint(allocator, "{s}/.config/sshz/backups", .{home}); } diff --git a/src/ssh_config.zig b/src/ssh_config.zig index 84b406d..e414937 100644 --- a/src/ssh_config.zig +++ b/src/ssh_config.zig @@ -39,11 +39,17 @@ pub const Host = struct { }; pub const Config = struct { + /// Each Host's string fields (`name`, `hostname`, `user`, ...) are + /// owned by `allocator`. `parse`/`addHost` allocate copies; `removeHost` + /// and `deinit` free them via `freeHostStrings`. hosts: []Host, + /// Each `raw_lines` element is owned by `allocator`. raw_lines: [][]const u8, pub fn deinit(self: *Config, allocator: std.mem.Allocator) void { + for (self.hosts) |h| freeHostStrings(allocator, h); allocator.free(self.hosts); + for (self.raw_lines) |line| allocator.free(line); allocator.free(self.raw_lines); } @@ -75,20 +81,44 @@ fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool { return true; } +fn freeHostStrings(allocator: std.mem.Allocator, host: Host) void { + allocator.free(host.name); + if (host.hostname) |v| allocator.free(v); + if (host.user) |v| allocator.free(v); + if (host.identity_file) |v| allocator.free(v); + if (host.proxy_jump) |v| allocator.free(v); + if (host.proxy_command) |v| allocator.free(v); + if (host.local_forward) |v| allocator.free(v); + if (host.remote_forward) |v| allocator.free(v); + if (host.dynamic_forward) |v| allocator.free(v); +} + pub fn parse(allocator: std.mem.Allocator, content: []const u8) !Config { - var hosts: std.ArrayList(Host) = .{}; - defer hosts.deinit(allocator); + var hosts: std.ArrayList(Host) = .empty; + errdefer { + for (hosts.items) |h| freeHostStrings(allocator, h); + hosts.deinit(allocator); + } - var lines_list: std.ArrayList([]const u8) = .{}; - defer lines_list.deinit(allocator); + var lines_list: std.ArrayList([]const u8) = .empty; + errdefer { + for (lines_list.items) |line| allocator.free(line); + lines_list.deinit(allocator); + } + + var current_host: ?Host = null; + errdefer if (current_host) |h| freeHostStrings(allocator, h); var line_iter = std.mem.splitScalar(u8, content, '\n'); var line_num: usize = 0; - var current_host: ?Host = null; var in_match_block: bool = false; while (line_iter.next()) |line| { - try lines_list.append(allocator, line); + const owned_line = try allocator.dupe(u8, line); + { + errdefer allocator.free(owned_line); + try lines_list.append(allocator, owned_line); + } const trimmed = std.mem.trim(u8, line, " \t\r"); if (trimmed.len == 0 or trimmed[0] == '#') { @@ -108,9 +138,10 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !Config { if (startsWithIgnoreCase(trimmed, "Match ") or startsWithIgnoreCase(trimmed, "Match\t")) { - if (current_host) |*h| { - h.end_line = line_num; - try hosts.append(allocator, h.*); + if (current_host) |h| { + var hh = h; + hh.end_line = line_num; + try hosts.append(allocator, hh); current_host = null; } in_match_block = true; @@ -125,29 +156,34 @@ pub fn parse(allocator: std.mem.Allocator, content: []const u8) !Config { if (std.ascii.eqlIgnoreCase(kv.key, "Host")) { in_match_block = false; - if (current_host) |*h| { - h.end_line = line_num; - try hosts.append(allocator, h.*); + if (current_host) |h| { + var hh = h; + hh.end_line = line_num; + try hosts.append(allocator, hh); + current_host = null; } const is_wildcard = std.mem.indexOfScalar(u8, kv.value, '*') != null or std.mem.indexOfScalar(u8, kv.value, '?') != null; + const name_dup = try allocator.dupe(u8, kv.value); current_host = Host{ - .name = kv.value, + .name = name_dup, .start_line = line_num, .is_wildcard = is_wildcard, }; } else if (!in_match_block) { if (current_host) |*h| { - setHostField(h, kv.key, kv.value); + try setHostField(allocator, h, kv.key, kv.value); } } line_num += 1; } - if (current_host) |*h| { - h.end_line = line_num; - try hosts.append(allocator, h.*); + if (current_host) |h| { + var hh = h; + hh.end_line = line_num; + try hosts.append(allocator, hh); + current_host = null; } return Config{ @@ -172,32 +208,50 @@ fn parseKeyValue(line: []const u8) ?KeyValue { return KeyValue{ .key = key, .value = value }; } -fn setHostField(h: *Host, key: []const u8, value: []const u8) void { +fn setHostField(allocator: std.mem.Allocator, h: *Host, key: []const u8, value: []const u8) !void { + // Pattern: dupe first, then free old (so a failed dup doesn't dangle the + // old value). Repeated keys in the same Host block are rare but legal. if (std.ascii.eqlIgnoreCase(key, "HostName")) { - h.hostname = value; + const new_val = try allocator.dupe(u8, value); + if (h.hostname) |old| allocator.free(old); + h.hostname = new_val; } else if (std.ascii.eqlIgnoreCase(key, "User")) { - h.user = value; + const new_val = try allocator.dupe(u8, value); + if (h.user) |old| allocator.free(old); + h.user = new_val; } else if (std.ascii.eqlIgnoreCase(key, "Port")) { h.port = std.fmt.parseInt(u16, value, 10) catch null; } else if (std.ascii.eqlIgnoreCase(key, "IdentityFile")) { - h.identity_file = value; + const new_val = try allocator.dupe(u8, value); + if (h.identity_file) |old| allocator.free(old); + h.identity_file = new_val; } else if (std.ascii.eqlIgnoreCase(key, "ProxyJump")) { - h.proxy_jump = value; + const new_val = try allocator.dupe(u8, value); + if (h.proxy_jump) |old| allocator.free(old); + h.proxy_jump = new_val; } else if (std.ascii.eqlIgnoreCase(key, "ProxyCommand")) { - h.proxy_command = value; + const new_val = try allocator.dupe(u8, value); + if (h.proxy_command) |old| allocator.free(old); + h.proxy_command = new_val; } else if (std.ascii.eqlIgnoreCase(key, "LocalForward")) { - h.local_forward = value; + const new_val = try allocator.dupe(u8, value); + if (h.local_forward) |old| allocator.free(old); + h.local_forward = new_val; } else if (std.ascii.eqlIgnoreCase(key, "RemoteForward")) { - h.remote_forward = value; + const new_val = try allocator.dupe(u8, value); + if (h.remote_forward) |old| allocator.free(old); + h.remote_forward = new_val; } else if (std.ascii.eqlIgnoreCase(key, "DynamicForward")) { - h.dynamic_forward = value; + const new_val = try allocator.dupe(u8, value); + if (h.dynamic_forward) |old| allocator.free(old); + h.dynamic_forward = new_val; } else if (std.ascii.eqlIgnoreCase(key, "AddressFamily")) { h.address_family = AddressFamily.fromString(value); } } pub fn serialize(allocator: std.mem.Allocator, config: *const Config) ![]const u8 { - var result: std.ArrayList(u8) = .{}; + var result: std.ArrayList(u8) = .empty; defer result.deinit(allocator); for (config.raw_lines) |line| { @@ -208,15 +262,25 @@ pub fn serialize(allocator: std.mem.Allocator, config: *const Config) ![]const u return try result.toOwnedSlice(allocator); } +/// Append `host` to `config`. `addHost` takes ownership: it deep-copies +/// every string field of `host` and every line in `config.raw_lines`, so +/// callers may pass borrowed slices (form input, string literals) safely. pub fn addHost(allocator: std.mem.Allocator, config: *Config, host: Host) !void { - var new_lines: std.ArrayList([]const u8) = .{}; - defer new_lines.deinit(allocator); - for (config.raw_lines) |l| try new_lines.append(allocator, l); - try new_lines.append(allocator, ""); + // Phase 1: build all new owned state in locals. On any failure, the + // errdefers free everything we allocated; `config` stays untouched. - // Track where the new host block starts - const host_start_line = new_lines.items.len; + var new_lines: std.ArrayList([]const u8) = .empty; + errdefer { + for (new_lines.items) |s| allocator.free(s); + new_lines.deinit(allocator); + } + + for (config.raw_lines) |l| { + try new_lines.append(allocator, try allocator.dupe(u8, l)); + } + try new_lines.append(allocator, try allocator.dupe(u8, "")); + const host_start_line = new_lines.items.len; try new_lines.append(allocator, try std.fmt.allocPrint(allocator, "Host {s}", .{host.name})); if (host.hostname) |v| { try new_lines.append(allocator, try std.fmt.allocPrint(allocator, " HostName {s}", .{v})); @@ -236,21 +300,51 @@ pub fn addHost(allocator: std.mem.Allocator, config: *Config, host: Host) !void if (host.address_family) |af| { try new_lines.append(allocator, try std.fmt.allocPrint(allocator, " AddressFamily {s}", .{af.toString()})); } - const host_end_line = new_lines.items.len; - allocator.free(config.raw_lines); - config.raw_lines = try new_lines.toOwnedSlice(allocator); - - var new_hosts: std.ArrayList(Host) = .{}; - defer new_hosts.deinit(allocator); + var new_host: Host = .{ + .name = try allocator.dupe(u8, host.name), + .start_line = host_start_line, + .end_line = host_end_line, + .is_wildcard = host.is_wildcard, + .port = host.port, + .address_family = host.address_family, + }; + errdefer freeHostStrings(allocator, new_host); + + if (host.hostname) |v| new_host.hostname = try allocator.dupe(u8, v); + if (host.user) |v| new_host.user = try allocator.dupe(u8, v); + if (host.identity_file) |v| new_host.identity_file = try allocator.dupe(u8, v); + if (host.proxy_jump) |v| new_host.proxy_jump = try allocator.dupe(u8, v); + if (host.proxy_command) |v| new_host.proxy_command = try allocator.dupe(u8, v); + if (host.local_forward) |v| new_host.local_forward = try allocator.dupe(u8, v); + if (host.remote_forward) |v| new_host.remote_forward = try allocator.dupe(u8, v); + if (host.dynamic_forward) |v| new_host.dynamic_forward = try allocator.dupe(u8, v); + + var new_hosts: std.ArrayList(Host) = .empty; + errdefer new_hosts.deinit(allocator); for (config.hosts) |h| try new_hosts.append(allocator, h); - var new_host = host; - new_host.start_line = host_start_line; - new_host.end_line = host_end_line; try new_hosts.append(allocator, new_host); + + // Phase 2: commit. Past `toOwnedSlice` only no-fail operations remain. + const new_lines_slice = try new_lines.toOwnedSlice(allocator); + const new_hosts_slice = new_hosts.toOwnedSlice(allocator) catch |err| { + // Couldn't commit hosts — release the lines we just took ownership of + // (they reference the allocator-owned strings we duped above). + for (new_lines_slice) |s| allocator.free(s); + allocator.free(new_lines_slice); + return err; + }; + + // Free old raw_lines content (each element was allocator-owned) and array. + for (config.raw_lines) |l| allocator.free(l); + allocator.free(config.raw_lines); + config.raw_lines = new_lines_slice; + + // Old `config.hosts` array is replaced; the host structs inside still + // reference their own owned strings, which transfer through `new_hosts`. allocator.free(config.hosts); - config.hosts = try new_hosts.toOwnedSlice(allocator); + config.hosts = new_hosts_slice; } pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) !void { @@ -259,19 +353,18 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! const host = config.hosts[index]; const start = host.start_line; const end = @min(host.end_line, config.raw_lines.len); + const removed_count = end - start; - var new_lines: std.ArrayList([]const u8) = .{}; - defer new_lines.deinit(allocator); + // Phase 1: build new arrays without committing. + var new_lines: std.ArrayList([]const u8) = .empty; + errdefer new_lines.deinit(allocator); for (config.raw_lines, 0..) |line, i| { if (i >= start and i < end) continue; try new_lines.append(allocator, line); } - allocator.free(config.raw_lines); - config.raw_lines = try new_lines.toOwnedSlice(allocator); - const removed_count = end - start; - var new_hosts: std.ArrayList(Host) = .{}; - defer new_hosts.deinit(allocator); + var new_hosts: std.ArrayList(Host) = .empty; + errdefer new_hosts.deinit(allocator); for (config.hosts, 0..) |h, i| { if (i == index) continue; var adjusted = h; @@ -281,20 +374,37 @@ pub fn removeHost(allocator: std.mem.Allocator, config: *Config, index: usize) ! } try new_hosts.append(allocator, adjusted); } + + // Phase 2: commit. Take ownership of the new slices, then free the + // strings that are no longer referenced. + const new_lines_slice = try new_lines.toOwnedSlice(allocator); + const new_hosts_slice = new_hosts.toOwnedSlice(allocator) catch |err| { + allocator.free(new_lines_slice); + return err; + }; + + // Free strings of the lines being dropped, then the old array. + for (config.raw_lines[start..end]) |line| allocator.free(line); + allocator.free(config.raw_lines); + config.raw_lines = new_lines_slice; + + // Free the removed host's owned string fields, then the old array. + freeHostStrings(allocator, host); allocator.free(config.hosts); - config.hosts = try new_hosts.toOwnedSlice(allocator); + config.hosts = new_hosts_slice; } -pub fn readFile(allocator: std.mem.Allocator, path: []const u8) !Config { - const file = try std.fs.cwd().openFile(path, .{}); - defer file.close(); - const content = try file.readToEndAlloc(allocator, 1024 * 1024); +pub fn readFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !Config { + const cwd = std.Io.Dir.cwd(); + const content = try cwd.readFileAlloc(io, path, allocator, .limited(1024 * 1024)); defer allocator.free(content); + // `parse` deep-copies all strings out of `content`, so it's safe to free + // the buffer here. return parse(allocator, content); } -pub fn writeFile(allocator: std.mem.Allocator, config: *const Config, path: []const u8, backup_dir: []const u8) !void { - backupFile(allocator, path, backup_dir) catch {}; +pub fn writeFile(allocator: std.mem.Allocator, io: std.Io, config: *const Config, path: []const u8, backup_dir: []const u8) !void { + backupFile(allocator, io, path, backup_dir) catch {}; const content = try serialize(allocator, config); defer allocator.free(content); @@ -305,54 +415,62 @@ pub fn writeFile(allocator: std.mem.Allocator, config: *const Config, path: []co var tmp_name_buf: [256]u8 = undefined; const tmp_name = std.fmt.bufPrint(&tmp_name_buf, ".{s}.tmp", .{basename}) catch return error.NameTooLong; - var dir_fd = try std.fs.cwd().openDir(dir_path, .{}); - defer dir_fd.close(); - - const tmp_file = try dir_fd.createFile(tmp_name, .{}); - tmp_file.writeAll(content) catch |e| { - tmp_file.close(); - return e; - }; - tmp_file.close(); + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, dir_path); + var dir_fd = try cwd.openDir(io, dir_path, .{}); + defer dir_fd.close(io); + + { + const tmp_file = try dir_fd.createFile(io, tmp_name, .{}); + defer tmp_file.close(io); + var write_buf: [4096]u8 = undefined; + var w = tmp_file.writer(io, &write_buf); + try w.interface.writeAll(content); + try w.interface.flush(); + } - try dir_fd.rename(tmp_name, basename); + try dir_fd.rename(tmp_name, dir_fd, basename, io); } -fn backupFile(allocator: std.mem.Allocator, source_path: []const u8, backup_dir: []const u8) !void { - std.fs.cwd().makePath(backup_dir) catch {}; +fn backupFile(allocator: std.mem.Allocator, io: std.Io, source_path: []const u8, backup_dir: []const u8) !void { + const cwd = std.Io.Dir.cwd(); + try cwd.createDirPath(io, backup_dir); - const source = std.fs.cwd().openFile(source_path, .{}) catch return; - defer source.close(); + const content = cwd.readFileAlloc(io, source_path, allocator, .limited(1024 * 1024)) catch return; + defer allocator.free(content); - const ts = std.time.timestamp(); + const ts = std.Io.Timestamp.now(io, .real).toSeconds(); var name_buf: [256]u8 = undefined; const backup_name = std.fmt.bufPrint(&name_buf, "ssh_config_{d}", .{ts}) catch return; var path_buf: [512]u8 = undefined; const backup_path = std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ backup_dir, backup_name }) catch return; - const content = source.readToEndAlloc(allocator, 1024 * 1024) catch return; - defer allocator.free(content); - - const dest = std.fs.cwd().createFile(backup_path, .{}) catch return; - defer dest.close(); - dest.writeAll(content) catch {}; + { + const dest = try cwd.createFile(io, backup_path, .{}); + defer dest.close(io); + var write_buf: [4096]u8 = undefined; + var w = dest.writer(io, &write_buf); + try w.interface.writeAll(content); + try w.interface.flush(); + } - rotateBackups(allocator, backup_dir) catch {}; + rotateBackups(allocator, io, backup_dir) catch {}; } -fn rotateBackups(allocator: std.mem.Allocator, backup_dir: []const u8) !void { - var dir = try std.fs.cwd().openDir(backup_dir, .{ .iterate = true }); - defer dir.close(); +fn rotateBackups(allocator: std.mem.Allocator, io: std.Io, backup_dir: []const u8) !void { + const cwd = std.Io.Dir.cwd(); + var dir = try cwd.openDir(io, backup_dir, .{ .iterate = true }); + defer dir.close(io); - var entries: std.ArrayList([]const u8) = .{}; + var entries: std.ArrayList([]const u8) = .empty; defer { for (entries.items) |name| allocator.free(@constCast(name)); entries.deinit(allocator); } var it = dir.iterate(); - while (try it.next()) |entry| { + while (try it.next(io)) |entry| { if (std.mem.startsWith(u8, entry.name, "ssh_config_")) { try entries.append(allocator, try allocator.dupe(u8, entry.name)); } @@ -368,11 +486,11 @@ fn rotateBackups(allocator: std.mem.Allocator, backup_dir: []const u8) !void { const to_delete = entries.items.len - 10; for (entries.items[0..to_delete]) |name| { - dir.deleteFile(name) catch {}; + try dir.deleteFile(io, name); } } -pub fn defaultConfigPath(allocator: std.mem.Allocator) ![]const u8 { - const home = std.posix.getenv("HOME") orelse return error.NoHome; +pub fn defaultConfigPath(allocator: std.mem.Allocator, env: *const std.process.Environ.Map) ![]const u8 { + const home = env.get("HOME") orelse return error.NoHome; return std.fmt.allocPrint(allocator, "{s}/.ssh/config", .{home}); } diff --git a/src/utils.zig b/src/utils.zig index dfe8b96..e8dfe70 100644 --- a/src/utils.zig +++ b/src/utils.zig @@ -18,9 +18,9 @@ pub fn relativeTime(seconds_ago: i64, buf: *[32]u8) []const u8 { } } -pub fn relativeTimeFromTimestamp(timestamp: i64, buf: *[32]u8) []const u8 { +pub fn relativeTimeFromTimestamp(io: std.Io, timestamp: i64, buf: *[32]u8) []const u8 { if (timestamp == 0) return "never"; - const now = std.time.timestamp(); + const now = std.Io.Timestamp.now(io, .real).toSeconds(); const diff = now - timestamp; if (diff < 0) return "future"; return relativeTime(diff, buf); diff --git a/src/views/forward.zig b/src/views/forward.zig index ec4d1da..3db1194 100644 --- a/src/views/forward.zig +++ b/src/views/forward.zig @@ -13,7 +13,7 @@ pub const ForwardState = struct { selected: usize = 0, pub fn init(allocator: std.mem.Allocator, host_name: []const u8, forwards: []const meta_mod.PortForward) ForwardState { - var entries: std.ArrayList(ForwardEntry) = .{}; + var entries: std.ArrayList(ForwardEntry) = .empty; for (forwards) |fwd| { entries.append(allocator, .{ .forward = fwd }) catch {}; } @@ -42,7 +42,7 @@ pub const ForwardState = struct { pub fn render(state: *const ForwardState, ctx: *const zz.Context) ![]const u8 { const a = ctx.allocator; - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const title = try std.fmt.allocPrint(a, " Connect to {s}", .{state.host_name}); const title_rendered = try title_style.render(a, title); @@ -51,7 +51,7 @@ pub fn render(state: *const ForwardState, ctx: *const zz.Context) ![]const u8 { @memset(sep_chars, '-'); const sep = try dim.render(a, sep_chars); - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, title_rendered); try lines.append(a, sep); diff --git a/src/views/help.zig b/src/views/help.zig index c880757..6c2354d 100644 --- a/src/views/help.zig +++ b/src/views/help.zig @@ -4,7 +4,7 @@ const zz = @import("zigzag"); pub fn render(ctx: *const zz.Context) ![]const u8 { const a = ctx.allocator; - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const key_style = (zz.Style{}).bold(true).fg(zz.Color.fromRgb(255, 200, 0)); const dim = (zz.Style{}).fg(zz.Color.gray(15)); @@ -23,7 +23,7 @@ pub fn render(ctx: *const zz.Context) ![]const u8 { .{ "q ", "Quit" }, }; - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, try title_style.render(a, " sshz Keybindings")); @@ -43,7 +43,7 @@ pub fn render(ctx: *const zz.Context) ![]const u8 { return try (zz.Style{}) .borderAll(zz.Border.rounded) - .borderForeground(zz.Color.cyan()) + .borderForeground(zz.Color.cyan) .paddingAll(1) .width(@min(ctx.width -| 4, 50)) .render(a, content); diff --git a/src/views/host_form.zig b/src/views/host_form.zig index 0f21e2c..45c5d1b 100644 --- a/src/views/host_form.zig +++ b/src/views/host_form.zig @@ -72,7 +72,7 @@ pub fn render(form: *const FormState, ctx: *const zz.Context) ![]const u8 { const a = ctx.allocator; const title_text = if (form.editing_host != null) " Edit Host" else " Add Host"; - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const title = try title_style.render(a, title_text); const dim = (zz.Style{}).fg(zz.Color.gray(12)); @@ -91,10 +91,10 @@ pub fn render(form: *const FormState, ctx: *const zz.Context) ![]const u8 { " Tags: ", }; - const label_style = (zz.Style{}).fg(zz.Color.white()).bold(true); - const focus_indicator = (zz.Style{}).fg(zz.Color.cyan()).bold(true); + const label_style = (zz.Style{}).fg(zz.Color.white).bold(true); + const focus_indicator = (zz.Style{}).fg(zz.Color.cyan).bold(true); - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, title); try lines.append(a, sep); diff --git a/src/views/host_list.zig b/src/views/host_list.zig index 1fe82f6..27edfd9 100644 --- a/src/views/host_list.zig +++ b/src/views/host_list.zig @@ -9,7 +9,7 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { const w = ctx.width; // Title - const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan()); + const title_style = (zz.Style{}).bold(true).fg(zz.Color.cyan); const title = try title_style.render(a, " sshz - SSH Manager"); // Host count @@ -34,31 +34,21 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { const separator = try dim.render(a, sep_chars); // Build lines - var lines: std.ArrayList([]const u8) = .{}; + var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(a); try lines.append(a, header); try lines.append(a, separator); - // Filtered host list - var display_idx: usize = 0; - for (model.hosts.items) |entry| { - // Search filter - if (model.search_text.items.len > 0) { - if (!matchesSearch(entry, model.search_text.items)) continue; - } - - // Tag filter - if (model.tag_filter) |tag| { - if (!hasTag(entry, tag)) continue; - } - - const is_selected = (display_idx == model.selected); - const line = try renderHostLine(a, entry, is_selected, w); + // Filtered host list (filter logic lives in app.zig now; + // model.visible_indices already reflects search + tag filters). + for (model.visible_indices.items, 0..) |hi, idx| { + const entry = model.hosts.items[hi]; + const is_selected = (idx == model.selected); + const line = try renderHostLine(a, ctx.io, entry, is_selected, w); try lines.append(a, line); - display_idx += 1; } - if (display_idx == 0) { + if (model.visible_indices.items.len == 0) { const empty_style = (zz.Style{}).fg(zz.Color.gray(10)).italic(true); try lines.append(a, try empty_style.render(a, " No hosts found. Press 'a' to add one.")); } @@ -71,9 +61,10 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { const prompt = try std.fmt.allocPrint(a, " /{s}_", .{model.search_text.items}); try lines.append(a, try search_style.render(a, prompt)); } else if (model.confirm_delete) { - if (model.selected < model.hosts.items.len) { + if (model.selected < model.visible_indices.items.len) { const warn_style = (zz.Style{}).fg(zz.Color.fromRgb(255, 80, 80)).bold(true); - const name = model.hosts.items[model.selected].config.name; + const hi = model.visible_indices.items[model.selected]; + const name = model.hosts.items[hi].config.name; const msg = try std.fmt.allocPrint(a, " Delete '{s}'? (y/n)", .{name}); try lines.append(a, try warn_style.render(a, msg)); } @@ -100,32 +91,7 @@ pub fn render(model: *const App.Model, ctx: *const zz.Context) ![]const u8 { return try zz.joinVertical(a, lines.items); } -fn matchesSearch(entry: App.HostEntry, search: []const u8) bool { - if (std.mem.indexOf(u8, entry.config.name, search) != null) return true; - if (entry.config.hostname) |hn| { - if (std.mem.indexOf(u8, hn, search) != null) return true; - } - if (entry.config.user) |u| { - if (std.mem.indexOf(u8, u, search) != null) return true; - } - if (entry.meta) |m| { - for (m.tags) |tag| { - if (std.mem.indexOf(u8, tag, search) != null) return true; - } - } - return false; -} - -fn hasTag(entry: App.HostEntry, tag: []const u8) bool { - if (entry.meta) |m| { - for (m.tags) |t| { - if (std.mem.eql(u8, t, tag)) return true; - } - } - return false; -} - -fn renderHostLine(a: std.mem.Allocator, entry: App.HostEntry, is_selected: bool, width: u16) ![]const u8 { +fn renderHostLine(a: std.mem.Allocator, io: std.Io, entry: App.HostEntry, is_selected: bool, width: u16) ![]const u8 { // Status indicator const StatusInfo = struct { sym: []const u8, color: zz.Color }; const status_info: StatusInfo = switch (entry.status) { @@ -157,7 +123,7 @@ fn renderHostLine(a: std.mem.Allocator, entry: App.HostEntry, is_selected: bool, var tags_str: []const u8 = ""; if (entry.meta) |m| { if (m.tags.len > 0) { - var tag_buf: std.ArrayList(u8) = .{}; + var tag_buf: std.ArrayList(u8) = .empty; defer tag_buf.deinit(a); try tag_buf.appendSlice(a, "["); for (m.tags, 0..) |tag, j| { @@ -172,7 +138,7 @@ fn renderHostLine(a: std.mem.Allocator, entry: App.HostEntry, is_selected: bool, // Last connected var time_buf: [32]u8 = undefined; const last_time = if (entry.meta) |m| - utils.relativeTimeFromTimestamp(m.last_connected, &time_buf) + utils.relativeTimeFromTimestamp(io, m.last_connected, &time_buf) else "never"; diff --git a/tests/test_meta.zig b/tests/test_meta.zig index f7ee611..0903cf7 100644 --- a/tests/test_meta.zig +++ b/tests/test_meta.zig @@ -23,7 +23,7 @@ test "record connection creates new host entry" { var store = meta.MetaStore.initWith(allocator); defer store.deinit(allocator); - try store.recordConnection(allocator, "newhost"); + try store.recordConnection(allocator, std.testing.io, "newhost"); const host = store.getHost("newhost"); try std.testing.expect(host != null); @@ -36,8 +36,8 @@ test "record connection increments existing count" { var store = meta.MetaStore.initWith(allocator); defer store.deinit(allocator); - try store.recordConnection(allocator, "host1"); - try store.recordConnection(allocator, "host1"); + try store.recordConnection(allocator, std.testing.io, "host1"); + try store.recordConnection(allocator, std.testing.io, "host1"); const host = store.getHost("host1"); try std.testing.expectEqual(@as(u32, 2), host.?.connect_count); @@ -48,7 +48,7 @@ test "serialize and parse round-trip" { var store = meta.MetaStore.initWith(allocator); defer store.deinit(allocator); - try store.recordConnection(allocator, "roundtrip"); + try store.recordConnection(allocator, std.testing.io, "roundtrip"); const tags = [_][]const u8{ "dev", "local" }; try store.setTags(allocator, "roundtrip", &tags); diff --git a/tests/test_ssh_config.zig b/tests/test_ssh_config.zig index 996f1f3..6609daa 100644 --- a/tests/test_ssh_config.zig +++ b/tests/test_ssh_config.zig @@ -162,15 +162,13 @@ test "remove all hosts" { } test "add then remove host" { - // Use page_allocator because addHost allocPrints new lines - // that aren't tracked for individual deallocation (by design— - // parsed lines are slices into original content, added lines are owned). - const allocator = std.heap.page_allocator; + const allocator = std.testing.allocator; const content = \\Host existing \\ HostName 10.0.0.1 ; var config = try ssh_config.parse(allocator, content); + defer config.deinit(allocator); // Add a new host try ssh_config.addHost(allocator, &config, .{ @@ -188,6 +186,7 @@ test "add then remove host" { // Serialize const output = try ssh_config.serialize(allocator, &config); + defer allocator.free(output); try std.testing.expect(std.mem.indexOf(u8, output, "newhost") != null); try std.testing.expect(std.mem.indexOf(u8, output, "existing") == null); } @@ -258,12 +257,13 @@ test "parse invalid AddressFamily yields null" { } test "addHost with AddressFamily serializes correctly" { - const allocator = std.heap.page_allocator; + const allocator = std.testing.allocator; const content = \\Host existing \\ HostName 10.0.0.1 ; var config = try ssh_config.parse(allocator, content); + defer config.deinit(allocator); try ssh_config.addHost(allocator, &config, .{ .name = "v6host", @@ -274,16 +274,18 @@ test "addHost with AddressFamily serializes correctly" { try std.testing.expectEqual(@as(usize, 2), config.hosts.len); const output = try ssh_config.serialize(allocator, &config); + defer allocator.free(output); try std.testing.expect(std.mem.indexOf(u8, output, " AddressFamily inet6") != null); } test "addHost without AddressFamily omits directive" { - const allocator = std.heap.page_allocator; + const allocator = std.testing.allocator; const content = \\Host existing \\ HostName 10.0.0.1 ; var config = try ssh_config.parse(allocator, content); + defer config.deinit(allocator); try ssh_config.addHost(allocator, &config, .{ .name = "v4host", @@ -291,6 +293,7 @@ test "addHost without AddressFamily omits directive" { }); const output = try ssh_config.serialize(allocator, &config); + defer allocator.free(output); try std.testing.expect(std.mem.indexOf(u8, output, "AddressFamily") == null); }