╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 //! haxy-side dispatcher for SSH sessions served by serve_ssh_protocol. 2 //! routes shell + pty-req → StreamTerminal (TUI), exec git-upload-pack / 3 //! git-receive-pack → repo.uploadPack / repo.receivePack (git). 4 5 const std = @import("std"); 6 const xit = @import("xit"); 7 const rp = xit.repo; 8 const xitui = xit.xitui; 9 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 10 const Grid = xitui.grid.Grid; 11 const Size = xitui.layout.Size; 12 const ui = @import("./ui.zig"); 13 const ssh = @import("./serve_ssh_protocol.zig"); 14 const evt = @import("./event.zig"); 15 16 pub const SessionHandler = struct { 17 admin_repo_path: []const u8, 18 repo_root_path: []const u8, 19 20 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 21 std.debug.print("ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 22 switch (request) { 23 .shell => |pty_maybe| { 24 const pty = pty_maybe orelse { 25 // a shell without a pty has no useful TUI to render; in 26 // openssh client terms this is `ssh -T host`. say so and 27 // exit non-zero. 28 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 29 try sess.exit(1); 30 return; 31 }; 32 try runTuiSession(self, sess, pty); 33 }, 34 .exec => |command| { 35 try runGitSession(self, sess, command); 36 }, 37 } 38 } 39 }; 40 41 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 42 // runTui owns the terminal, whose deinit restores the client's screen and 43 // runs as the function unwinds — so any error it returns leaves the TUI torn 44 // down and we can surface the failure on the restored screen before exiting. 45 runTui(handler, sess, pty) catch |err| { 46 std.debug.print("ssh tui session failed: {s}\n", .{@errorName(err)}); 47 var buf: [256]u8 = undefined; 48 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 49 sess.writeBytes(msg) catch {}; 50 try sess.exit(1); 51 return; 52 }; 53 try sess.exit(0); 54 } 55 56 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 57 const allocator = sess.allocator; 58 const io = sess.io; 59 60 // some clients (notably scripted ssh with no local controlling tty) 61 // allocate a pty without ever sending a non-zero size. fall back to a 62 // conventional 80x24 in that case so render emits something. 63 const effective_pty = ssh.PtySize{ 64 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 65 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 66 }; 67 68 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 69 var session_arena = std.heap.ArenaAllocator.init(allocator); 70 defer session_arena.deinit(); 71 72 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 73 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 74 defer repo.deinit(io, allocator); 75 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 76 ui_session.is_terminal = true; 77 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 78 ui_session.io = io; 79 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 80 81 var nav = try ui.Nav.init(allocator, &ui_session); 82 defer nav.deinit(allocator); 83 84 var session_writer_buf: [8192]u8 = undefined; 85 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 86 87 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 88 // flushes, restoring the client's screen. as a function-scoped defer it runs 89 // before runTui returns — on the normal path and on any error — so the 90 // caller can write to the client afterward (and sess.exit can close cleanly). 91 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 92 .width = effective_pty.width_cells, 93 .height = effective_pty.height_cells, 94 }); 95 defer terminal.deinit(); 96 97 var last_size = Size{ .width = 0, .height = 0 }; 98 var last_grid = try Grid.init(allocator, last_size); 99 defer last_grid.deinit(); 100 101 // initial render — user sees the page immediately 102 try nav.root.build(allocator, .{ 103 .min_size = .{ .width = null, .height = null }, 104 .max_size = .{ .width = last_size.width, .height = last_size.height }, 105 }, nav.root.getFocus()); 106 _ = try terminal.render(&nav.root, &last_grid, &last_size); 107 108 // event loop. nextEvent blocks until something interesting arrives; 109 // for each event, rebuild the widget tree and re-render so the user 110 // sees the effect of their input on the same iteration. 111 while (!terminal.shouldQuit()) { 112 const event = try sess.nextEvent(); 113 switch (event) { 114 .data => |payload| { 115 defer allocator.free(payload); 116 try terminal.writeBytes(payload); 117 while (terminal.popKey()) |key| { 118 try ui.inputKey(allocator, &nav.root, key, &ui_session); 119 } 120 }, 121 .resize => |sz| { 122 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 123 while (terminal.popKey()) |key| { 124 try ui.inputKey(allocator, &nav.root, key, &ui_session); 125 } 126 }, 127 .close => terminal.requestQuit(), 128 } 129 130 try ui_session.applyAndWritePending(io, allocator, &repo); 131 132 // reconcile navigation: forward to a new page, or back on escape 133 try nav.sync(allocator, &ui_session); 134 135 // the quit button (on the quit tab) asks the host to tear down 136 if (ui_session.quit_requested) terminal.requestQuit(); 137 138 try nav.root.build(allocator, .{ 139 .min_size = .{ .width = null, .height = null }, 140 .max_size = .{ .width = last_size.width, .height = last_size.height }, 141 }, nav.root.getFocus()); 142 _ = try terminal.render(&nav.root, &last_grid, &last_size); 143 } 144 } 145 146 // --------------------------------------------------------------------------- 147 // git path (exec) 148 // --------------------------------------------------------------------------- 149 150 pub const GitService = enum { upload_pack, receive_pack }; 151 152 pub const ParsedGitCommand = struct { 153 service: GitService, 154 dir: []u8, 155 156 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 157 allocator.free(self.dir); 158 } 159 }; 160 161 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 162 const allocator = sess.allocator; 163 const io = sess.io; 164 165 const parsed = parseGitCommand(allocator, command) catch { 166 try writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 167 try sess.exit(1); 168 return; 169 }; 170 defer parsed.deinit(allocator); 171 172 const repo_path = try resolveRepoPath(allocator, handler.repo_root_path, parsed.dir); 173 defer allocator.free(repo_path); 174 175 if (!isSubPath(handler.repo_root_path, repo_path)) { 176 try writeError(sess, "forbidden path"); 177 try sess.exit(1); 178 return; 179 } 180 181 const create_if_missing = parsed.service == .receive_pack; 182 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 183 184 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 185 error.RepoNotFound => { 186 if (!create_if_missing) { 187 try writeError(sess, "repo not found"); 188 try sess.exit(1); 189 return; 190 } 191 // nothing on disk to detect a hash from, so create with the 192 // default concrete options and serve that. 193 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 194 defer repo.deinit(io, allocator); 195 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 196 try sess.exit(0); 197 return; 198 }, 199 else => |e| return e, 200 }; 201 defer any_repo.deinit(io, allocator); 202 203 switch (any_repo) { 204 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, parsed.service), 205 } 206 207 try sess.exit(0); 208 } 209 210 fn createRepo( 211 comptime repo_opts: rp.RepoOpts(.xit), 212 io: std.Io, 213 allocator: std.mem.Allocator, 214 repo_path: []const u8, 215 ) !rp.Repo(.xit, repo_opts) { 216 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 217 errdefer repo.deinit(io, allocator); 218 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 219 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 220 return repo; 221 } 222 223 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 224 // functions can consume them like any other stream, then run the requested 225 // service 226 fn servePack( 227 comptime repo_opts: rp.RepoOpts(.xit), 228 repo: *rp.Repo(.xit, repo_opts), 229 sess: *ssh.SessionCtx, 230 io: std.Io, 231 allocator: std.mem.Allocator, 232 service: GitService, 233 ) !void { 234 var session_reader_buf: [4096]u8 = undefined; 235 var session_writer_buf: [4096]u8 = undefined; 236 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 237 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 238 239 switch (service) { 240 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 241 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 242 } 243 244 // flush whatever the pack op buffered into our writer adapter 245 session_writer.interface.flush() catch {}; 246 } 247 248 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 249 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 250 defer tokens.deinit(); 251 252 const service_token = tokens.next() orelse return error.InvalidCommand; 253 const dir_token = tokens.next() orelse return error.InvalidCommand; 254 255 const service: GitService = 256 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 257 .upload_pack 258 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 259 .receive_pack 260 else 261 return error.UnsupportedService; 262 263 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 264 } 265 266 fn resolveRepoPath(allocator: std.mem.Allocator, repo_root_path: []const u8, dir: []const u8) ![]const u8 { 267 if (std.fs.path.isAbsolute(dir)) return try std.fs.path.resolve(allocator, &.{dir}); 268 return try std.fs.path.resolve(allocator, &.{ repo_root_path, dir }); 269 } 270 271 fn isSubPath(parent: []const u8, child: []const u8) bool { 272 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 273 if (!std.mem.startsWith(u8, child, parent)) return false; 274 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 275 } 276 277 fn writeError(sess: *ssh.SessionCtx, msg: []const u8) !void { 278 var buf: [256]u8 = undefined; 279 const text = try std.fmt.bufPrint(&buf, "haxy ssh: {s}\n", .{msg}); 280 try sess.writeBytes(text); 281 } 282 283 test "parseGitCommand rejects malformed input" { 284 const allocator = std.testing.allocator; 285 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 286 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 287 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 288 } 289 290 test "parseGitCommand happy paths" { 291 const allocator = std.testing.allocator; 292 293 { 294 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 295 defer parsed.deinit(allocator); 296 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 297 try std.testing.expectEqualStrings("some-repo", parsed.dir); 298 } 299 { 300 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 301 defer parsed.deinit(allocator); 302 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 303 try std.testing.expectEqualStrings("user/proj", parsed.dir); 304 } 305 { 306 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 307 defer parsed.deinit(allocator); 308 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 309 try std.testing.expectEqualStrings("repo", parsed.dir); 310 } 311 } 312 313 test "isSubPath rejects prefix collisions and traversal" { 314 const sep = std.fs.path.sep_str; 315 const parent = sep ++ "srv" ++ sep ++ "git"; 316 317 try std.testing.expect(isSubPath(parent, parent ++ sep ++ "repo")); 318 try std.testing.expect(isSubPath(parent, parent)); 319 320 // common-prefix-but-not-subpath: "/srv/git" should NOT swallow 321 // "/srv/git2" or "/srv/gitignore" just because the bytes start the same. 322 try std.testing.expect(!isSubPath(parent, parent ++ "2")); 323 try std.testing.expect(!isSubPath(parent, parent ++ "ignore")); 324 325 // resolveRepoPath normalizes `..` first, so `/srv/git/../etc/passwd` 326 // becomes `/etc/passwd` — isSubPath then rejects it. 327 try std.testing.expect(!isSubPath(parent, sep ++ "etc" ++ sep ++ "passwd")); 328 329 const builtin = @import("builtin"); 330 331 if (.windows != builtin.os.tag) { 332 try std.testing.expect(isSubPath(sep, sep ++ "anything")); 333 try std.testing.expect(isSubPath(sep, sep)); 334 } 335 } 336