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