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