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