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