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