╭ 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 15 pub const SessionHandler = struct { 16 admin_repo_path: []const u8, 17 repo_root_path: []const u8, 18 19 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 20 std.debug.print("ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 21 switch (request) { 22 .shell => |pty_maybe| { 23 const pty = pty_maybe orelse { 24 // a shell without a pty has no useful TUI to render; in 25 // openssh client terms this is `ssh -T host`. say so and 26 // exit non-zero. 27 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 28 try sess.exit(1); 29 return; 30 }; 31 try runTuiSession(self, sess, pty); 32 }, 33 .exec => |command| { 34 try runGitSession(self, sess, command); 35 }, 36 } 37 } 38 }; 39 40 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 41 const allocator = sess.allocator; 42 const io = sess.io; 43 44 // some clients (notably scripted ssh with no local controlling tty) 45 // allocate a pty without ever sending a non-zero size. fall back to a 46 // conventional 80x24 in that case so render emits something. 47 const effective_pty = ssh.PtySize{ 48 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 49 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 50 }; 51 52 // build the Home page in a session-scoped arena. 53 var page_arena = std.heap.ArenaAllocator.init(allocator); 54 defer page_arena.deinit(); 55 56 const repo_opts: rp.RepoOpts(.xit) = .{}; 57 const Repo = rp.Repo(.xit, repo_opts); 58 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 59 defer repo.deinit(io, allocator); 60 const page: ui.Page = .{ .home = try .init(repo_opts, &page_arena, &repo) }; 61 62 var root = try ui.initRoot(allocator, &page); 63 defer root.deinit(); 64 65 // terminal and its writer adapter live in a nested block so the deinit 66 // (which writes leave-alt / show-cursor / disable-mouse to the channel) 67 // fires BEFORE sess.exit closes the channel. otherwise the client's 68 // terminal is left in alt-screen mode after disconnect. 69 { 70 var session_writer_buf: [8192]u8 = undefined; 71 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 72 73 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 74 .width = effective_pty.width_cells, 75 .height = effective_pty.height_cells, 76 }); 77 defer terminal.deinit(); 78 79 var last_size = Size{ .width = 0, .height = 0 }; 80 var last_grid = try Grid.init(allocator, last_size); 81 defer last_grid.deinit(); 82 83 // initial render — user sees the page immediately 84 try root.build(.{ 85 .min_size = .{ .width = null, .height = null }, 86 .max_size = .{ .width = last_size.width, .height = last_size.height }, 87 }, root.getFocus()); 88 _ = try terminal.render(&root, &last_grid, &last_size); 89 90 // event loop. nextEvent blocks until something interesting arrives; 91 // for each event, rebuild the widget tree and re-render so the user 92 // sees the effect of their input on the same iteration. 93 while (!terminal.shouldQuit()) { 94 const event = try sess.nextEvent(); 95 switch (event) { 96 .data => |payload| { 97 defer allocator.free(payload); 98 try terminal.writeBytes(payload); 99 while (terminal.popKey()) |key| { 100 try ui.inputKey(&root, key, &terminal); 101 } 102 }, 103 .resize => |sz| { 104 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 105 while (terminal.popKey()) |key| { 106 try ui.inputKey(&root, key, &terminal); 107 } 108 }, 109 .close => terminal.requestQuit(), 110 } 111 112 try root.build(.{ 113 .min_size = .{ .width = null, .height = null }, 114 .max_size = .{ .width = last_size.width, .height = last_size.height }, 115 }, root.getFocus()); 116 _ = try terminal.render(&root, &last_grid, &last_size); 117 } 118 } 119 120 try sess.exit(0); 121 } 122 123 // --------------------------------------------------------------------------- 124 // git path (exec) 125 // --------------------------------------------------------------------------- 126 127 pub const GitService = enum { upload_pack, receive_pack }; 128 129 pub const ParsedGitCommand = struct { 130 service: GitService, 131 dir: []u8, 132 133 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 134 allocator.free(self.dir); 135 } 136 }; 137 138 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 139 const allocator = sess.allocator; 140 const io = sess.io; 141 142 const parsed = parseGitCommand(allocator, command) catch { 143 try writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 144 try sess.exit(1); 145 return; 146 }; 147 defer parsed.deinit(allocator); 148 149 const repo_path = try resolveRepoPath(allocator, handler.repo_root_path, parsed.dir); 150 defer allocator.free(repo_path); 151 152 if (!isSubPath(handler.repo_root_path, repo_path)) { 153 try writeError(sess, "forbidden path"); 154 try sess.exit(1); 155 return; 156 } 157 158 const repo_opts: rp.RepoOpts(.xit) = .{}; 159 const Repo = rp.Repo(.xit, repo_opts); 160 const create_if_missing = parsed.service == .receive_pack; 161 162 var repo = openOrCreate(Repo, io, allocator, repo_path, create_if_missing) catch |err| switch (err) { 163 error.RepoNotFound => { 164 try writeError(sess, "repo not found"); 165 try sess.exit(1); 166 return; 167 }, 168 else => |e| return e, 169 }; 170 defer repo.deinit(io, allocator); 171 172 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's 173 // pack functions can consume them like any other stream. 174 var session_reader_buf: [4096]u8 = undefined; 175 var session_writer_buf: [4096]u8 = undefined; 176 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 177 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 178 179 switch (parsed.service) { 180 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 181 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 182 } 183 184 // flush whatever the pack op buffered into our writer adapter 185 session_writer.interface.flush() catch {}; 186 187 try sess.exit(0); 188 } 189 190 fn openOrCreate( 191 comptime Repo: type, 192 io: std.Io, 193 allocator: std.mem.Allocator, 194 repo_path: []const u8, 195 create_if_missing: bool, 196 ) !Repo { 197 return Repo.open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 198 error.RepoNotFound => { 199 if (!create_if_missing) return err; 200 var repo = try Repo.init(io, allocator, .{ .path = repo_path }); 201 errdefer repo.deinit(io, allocator); 202 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 203 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 204 return repo; 205 }, 206 else => |e| return e, 207 }; 208 } 209 210 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 211 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 212 defer tokens.deinit(); 213 214 const service_token = tokens.next() orelse return error.InvalidCommand; 215 const dir_token = tokens.next() orelse return error.InvalidCommand; 216 217 const service: GitService = 218 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 219 .upload_pack 220 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 221 .receive_pack 222 else 223 return error.UnsupportedService; 224 225 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 226 } 227 228 fn resolveRepoPath(allocator: std.mem.Allocator, repo_root_path: []const u8, dir: []const u8) ![]const u8 { 229 if (std.fs.path.isAbsolute(dir)) return try std.fs.path.resolve(allocator, &.{dir}); 230 return try std.fs.path.resolve(allocator, &.{ repo_root_path, dir }); 231 } 232 233 fn isSubPath(parent: []const u8, child: []const u8) bool { 234 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 235 if (!std.mem.startsWith(u8, child, parent)) return false; 236 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 237 } 238 239 fn writeError(sess: *ssh.SessionCtx, msg: []const u8) !void { 240 var buf: [256]u8 = undefined; 241 const text = try std.fmt.bufPrint(&buf, "haxy ssh: {s}\n", .{msg}); 242 try sess.writeBytes(text); 243 } 244 245 test "parseGitCommand rejects malformed input" { 246 const allocator = std.testing.allocator; 247 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 248 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 249 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 250 } 251 252 test "parseGitCommand happy paths" { 253 const allocator = std.testing.allocator; 254 255 { 256 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 257 defer parsed.deinit(allocator); 258 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 259 try std.testing.expectEqualStrings("some-repo", parsed.dir); 260 } 261 { 262 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 263 defer parsed.deinit(allocator); 264 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 265 try std.testing.expectEqualStrings("user/proj", parsed.dir); 266 } 267 { 268 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 269 defer parsed.deinit(allocator); 270 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 271 try std.testing.expectEqualStrings("repo", parsed.dir); 272 } 273 } 274 275 test "isSubPath rejects prefix collisions and traversal" { 276 const sep = std.fs.path.sep_str; 277 const parent = sep ++ "srv" ++ sep ++ "git"; 278 279 try std.testing.expect(isSubPath(parent, parent ++ sep ++ "repo")); 280 try std.testing.expect(isSubPath(parent, parent)); 281 282 // common-prefix-but-not-subpath: "/srv/git" should NOT swallow 283 // "/srv/git2" or "/srv/gitignore" just because the bytes start the same. 284 try std.testing.expect(!isSubPath(parent, parent ++ "2")); 285 try std.testing.expect(!isSubPath(parent, parent ++ "ignore")); 286 287 // resolveRepoPath normalizes `..` first, so `/srv/git/../etc/passwd` 288 // becomes `/etc/passwd` — isSubPath then rejects it. 289 try std.testing.expect(!isSubPath(parent, sep ++ "etc" ++ sep ++ "passwd")); 290 291 const builtin = @import("builtin"); 292 293 if (.windows != builtin.os.tag) { 294 try std.testing.expect(isSubPath(sep, sep ++ "anything")); 295 try std.testing.expect(isSubPath(sep, sep)); 296 } 297 } 298