╭ 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 78 var nav = try ui.Nav.init(allocator, &ui_session); 79 defer nav.deinit(allocator); 80 81 var session_writer_buf: [8192]u8 = undefined; 82 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 83 84 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 85 // flushes, restoring the client's screen. as a function-scoped defer it runs 86 // before runTui returns — on the normal path and on any error — so the 87 // caller can write to the client afterward (and sess.exit can close cleanly). 88 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 89 .width = effective_pty.width_cells, 90 .height = effective_pty.height_cells, 91 }); 92 defer terminal.deinit(); 93 94 var last_size = Size{ .width = 0, .height = 0 }; 95 var last_grid = try Grid.init(allocator, last_size); 96 defer last_grid.deinit(); 97 98 // initial render — user sees the page immediately 99 try nav.root.build(allocator, .{ 100 .min_size = .{ .width = null, .height = null }, 101 .max_size = .{ .width = last_size.width, .height = last_size.height }, 102 }, nav.root.getFocus()); 103 _ = try terminal.render(&nav.root, &last_grid, &last_size); 104 105 // event loop. nextEvent blocks until something interesting arrives; 106 // for each event, rebuild the widget tree and re-render so the user 107 // sees the effect of their input on the same iteration. 108 while (!terminal.shouldQuit()) { 109 const event = try sess.nextEvent(); 110 switch (event) { 111 .data => |payload| { 112 defer allocator.free(payload); 113 try terminal.writeBytes(payload); 114 while (terminal.popKey()) |key| { 115 try ui.inputKey(allocator, &nav.root, key, &ui_session); 116 } 117 }, 118 .resize => |sz| { 119 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 120 while (terminal.popKey()) |key| { 121 try ui.inputKey(allocator, &nav.root, key, &ui_session); 122 } 123 }, 124 .close => terminal.requestQuit(), 125 } 126 127 try ui_session.applyAndWritePending(io, allocator, &repo); 128 129 // reconcile navigation: forward to a new page, or back on escape 130 try nav.sync(allocator, &ui_session); 131 132 // the quit button (on the quit tab) asks the host to tear down 133 if (ui_session.quit_requested) terminal.requestQuit(); 134 135 try nav.root.build(allocator, .{ 136 .min_size = .{ .width = null, .height = null }, 137 .max_size = .{ .width = last_size.width, .height = last_size.height }, 138 }, nav.root.getFocus()); 139 _ = try terminal.render(&nav.root, &last_grid, &last_size); 140 } 141 } 142 143 // --------------------------------------------------------------------------- 144 // git path (exec) 145 // --------------------------------------------------------------------------- 146 147 pub const GitService = enum { upload_pack, receive_pack }; 148 149 pub const ParsedGitCommand = struct { 150 service: GitService, 151 dir: []u8, 152 153 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 154 allocator.free(self.dir); 155 } 156 }; 157 158 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 159 const allocator = sess.allocator; 160 const io = sess.io; 161 162 const parsed = parseGitCommand(allocator, command) catch { 163 try writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 164 try sess.exit(1); 165 return; 166 }; 167 defer parsed.deinit(allocator); 168 169 const repo_path = try resolveRepoPath(allocator, handler.repo_root_path, parsed.dir); 170 defer allocator.free(repo_path); 171 172 if (!isSubPath(handler.repo_root_path, repo_path)) { 173 try writeError(sess, "forbidden path"); 174 try sess.exit(1); 175 return; 176 } 177 178 const create_if_missing = parsed.service == .receive_pack; 179 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 180 181 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 182 error.RepoNotFound => { 183 if (!create_if_missing) { 184 try writeError(sess, "repo not found"); 185 try sess.exit(1); 186 return; 187 } 188 // nothing on disk to detect a hash from, so create with the 189 // default concrete options and serve that. 190 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 191 defer repo.deinit(io, allocator); 192 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 193 try sess.exit(0); 194 return; 195 }, 196 else => |e| return e, 197 }; 198 defer any_repo.deinit(io, allocator); 199 200 switch (any_repo) { 201 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, parsed.service), 202 } 203 204 try sess.exit(0); 205 } 206 207 fn createRepo( 208 comptime repo_opts: rp.RepoOpts(.xit), 209 io: std.Io, 210 allocator: std.mem.Allocator, 211 repo_path: []const u8, 212 ) !rp.Repo(.xit, repo_opts) { 213 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 214 errdefer repo.deinit(io, allocator); 215 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 216 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 217 return repo; 218 } 219 220 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 221 // functions can consume them like any other stream, then run the requested 222 // service 223 fn servePack( 224 comptime repo_opts: rp.RepoOpts(.xit), 225 repo: *rp.Repo(.xit, repo_opts), 226 sess: *ssh.SessionCtx, 227 io: std.Io, 228 allocator: std.mem.Allocator, 229 service: GitService, 230 ) !void { 231 var session_reader_buf: [4096]u8 = undefined; 232 var session_writer_buf: [4096]u8 = undefined; 233 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 234 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 235 236 switch (service) { 237 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 238 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 239 } 240 241 // flush whatever the pack op buffered into our writer adapter 242 session_writer.interface.flush() catch {}; 243 } 244 245 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 246 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 247 defer tokens.deinit(); 248 249 const service_token = tokens.next() orelse return error.InvalidCommand; 250 const dir_token = tokens.next() orelse return error.InvalidCommand; 251 252 const service: GitService = 253 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 254 .upload_pack 255 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 256 .receive_pack 257 else 258 return error.UnsupportedService; 259 260 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 261 } 262 263 fn resolveRepoPath(allocator: std.mem.Allocator, repo_root_path: []const u8, dir: []const u8) ![]const u8 { 264 if (std.fs.path.isAbsolute(dir)) return try std.fs.path.resolve(allocator, &.{dir}); 265 return try std.fs.path.resolve(allocator, &.{ repo_root_path, dir }); 266 } 267 268 fn isSubPath(parent: []const u8, child: []const u8) bool { 269 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 270 if (!std.mem.startsWith(u8, child, parent)) return false; 271 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 272 } 273 274 fn writeError(sess: *ssh.SessionCtx, msg: []const u8) !void { 275 var buf: [256]u8 = undefined; 276 const text = try std.fmt.bufPrint(&buf, "haxy ssh: {s}\n", .{msg}); 277 try sess.writeBytes(text); 278 } 279 280 test "parseGitCommand rejects malformed input" { 281 const allocator = std.testing.allocator; 282 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 283 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 284 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 285 } 286 287 test "parseGitCommand happy paths" { 288 const allocator = std.testing.allocator; 289 290 { 291 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 292 defer parsed.deinit(allocator); 293 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 294 try std.testing.expectEqualStrings("some-repo", parsed.dir); 295 } 296 { 297 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 298 defer parsed.deinit(allocator); 299 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 300 try std.testing.expectEqualStrings("user/proj", parsed.dir); 301 } 302 { 303 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 304 defer parsed.deinit(allocator); 305 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 306 try std.testing.expectEqualStrings("repo", parsed.dir); 307 } 308 } 309 310 test "isSubPath rejects prefix collisions and traversal" { 311 const sep = std.fs.path.sep_str; 312 const parent = sep ++ "srv" ++ sep ++ "git"; 313 314 try std.testing.expect(isSubPath(parent, parent ++ sep ++ "repo")); 315 try std.testing.expect(isSubPath(parent, parent)); 316 317 // common-prefix-but-not-subpath: "/srv/git" should NOT swallow 318 // "/srv/git2" or "/srv/gitignore" just because the bytes start the same. 319 try std.testing.expect(!isSubPath(parent, parent ++ "2")); 320 try std.testing.expect(!isSubPath(parent, parent ++ "ignore")); 321 322 // resolveRepoPath normalizes `..` first, so `/srv/git/../etc/passwd` 323 // becomes `/etc/passwd` — isSubPath then rejects it. 324 try std.testing.expect(!isSubPath(parent, sep ++ "etc" ++ sep ++ "passwd")); 325 326 const builtin = @import("builtin"); 327 328 if (.windows != builtin.os.tag) { 329 try std.testing.expect(isSubPath(sep, sep ++ "anything")); 330 try std.testing.expect(isSubPath(sep, sep)); 331 } 332 } 333