╭ 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 // runTui owns the terminal, whose deinit restores the client's screen and 42 // runs as the function unwinds — so any error it returns leaves the TUI torn 43 // down and we can surface the failure on the restored screen before exiting. 44 runTui(handler, sess, pty) catch |err| { 45 std.debug.print("ssh tui session failed: {s}\n", .{@errorName(err)}); 46 var buf: [256]u8 = undefined; 47 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 48 sess.writeBytes(msg) catch {}; 49 try sess.exit(1); 50 return; 51 }; 52 try sess.exit(0); 53 } 54 55 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 56 const allocator = sess.allocator; 57 const io = sess.io; 58 59 // some clients (notably scripted ssh with no local controlling tty) 60 // allocate a pty without ever sending a non-zero size. fall back to a 61 // conventional 80x24 in that case so render emits something. 62 const effective_pty = ssh.PtySize{ 63 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 64 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 65 }; 66 67 // build the Home page in a session-scoped arena. 68 var page_arena = std.heap.ArenaAllocator.init(allocator); 69 defer page_arena.deinit(); 70 71 const repo_opts: rp.RepoOpts(.xit) = .{}; 72 const Repo = rp.Repo(.xit, 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(repo_opts, &page_arena, &repo, .{}); 76 77 const page: ui.Page = .{ .home = try .init(repo_opts, &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 // apply any actions the widgets queued this frame, persisting those 129 // that belong to a logged-in user 130 try ui.Action.dispatchPending(repo_opts, io, allocator, &repo, &ui_session); 131 132 try root.build(allocator, .{ 133 .min_size = .{ .width = null, .height = null }, 134 .max_size = .{ .width = last_size.width, .height = last_size.height }, 135 }, root.getFocus()); 136 _ = try terminal.render(&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 repo_opts: rp.RepoOpts(.xit) = .{}; 176 const Repo = rp.Repo(.xit, repo_opts); 177 const create_if_missing = parsed.service == .receive_pack; 178 179 var repo = openOrCreate(Repo, io, allocator, repo_path, create_if_missing) catch |err| switch (err) { 180 error.RepoNotFound => { 181 try writeError(sess, "repo not found"); 182 try sess.exit(1); 183 return; 184 }, 185 else => |e| return e, 186 }; 187 defer repo.deinit(io, allocator); 188 189 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's 190 // pack functions can consume them like any other stream. 191 var session_reader_buf: [4096]u8 = undefined; 192 var session_writer_buf: [4096]u8 = undefined; 193 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 194 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 195 196 switch (parsed.service) { 197 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 198 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 199 } 200 201 // flush whatever the pack op buffered into our writer adapter 202 session_writer.interface.flush() catch {}; 203 204 try sess.exit(0); 205 } 206 207 fn openOrCreate( 208 comptime Repo: type, 209 io: std.Io, 210 allocator: std.mem.Allocator, 211 repo_path: []const u8, 212 create_if_missing: bool, 213 ) !Repo { 214 return Repo.open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 215 error.RepoNotFound => { 216 if (!create_if_missing) return err; 217 var repo = try Repo.init(io, allocator, .{ .path = repo_path }); 218 errdefer repo.deinit(io, allocator); 219 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 220 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 221 return repo; 222 }, 223 else => |e| return e, 224 }; 225 } 226 227 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 228 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 229 defer tokens.deinit(); 230 231 const service_token = tokens.next() orelse return error.InvalidCommand; 232 const dir_token = tokens.next() orelse return error.InvalidCommand; 233 234 const service: GitService = 235 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 236 .upload_pack 237 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 238 .receive_pack 239 else 240 return error.UnsupportedService; 241 242 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 243 } 244 245 fn resolveRepoPath(allocator: std.mem.Allocator, repo_root_path: []const u8, dir: []const u8) ![]const u8 { 246 if (std.fs.path.isAbsolute(dir)) return try std.fs.path.resolve(allocator, &.{dir}); 247 return try std.fs.path.resolve(allocator, &.{ repo_root_path, dir }); 248 } 249 250 fn isSubPath(parent: []const u8, child: []const u8) bool { 251 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 252 if (!std.mem.startsWith(u8, child, parent)) return false; 253 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 254 } 255 256 fn writeError(sess: *ssh.SessionCtx, msg: []const u8) !void { 257 var buf: [256]u8 = undefined; 258 const text = try std.fmt.bufPrint(&buf, "haxy ssh: {s}\n", .{msg}); 259 try sess.writeBytes(text); 260 } 261 262 test "parseGitCommand rejects malformed input" { 263 const allocator = std.testing.allocator; 264 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 265 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 266 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 267 } 268 269 test "parseGitCommand happy paths" { 270 const allocator = std.testing.allocator; 271 272 { 273 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 274 defer parsed.deinit(allocator); 275 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 276 try std.testing.expectEqualStrings("some-repo", parsed.dir); 277 } 278 { 279 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 280 defer parsed.deinit(allocator); 281 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 282 try std.testing.expectEqualStrings("user/proj", parsed.dir); 283 } 284 { 285 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 286 defer parsed.deinit(allocator); 287 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 288 try std.testing.expectEqualStrings("repo", parsed.dir); 289 } 290 } 291 292 test "isSubPath rejects prefix collisions and traversal" { 293 const sep = std.fs.path.sep_str; 294 const parent = sep ++ "srv" ++ sep ++ "git"; 295 296 try std.testing.expect(isSubPath(parent, parent ++ sep ++ "repo")); 297 try std.testing.expect(isSubPath(parent, parent)); 298 299 // common-prefix-but-not-subpath: "/srv/git" should NOT swallow 300 // "/srv/git2" or "/srv/gitignore" just because the bytes start the same. 301 try std.testing.expect(!isSubPath(parent, parent ++ "2")); 302 try std.testing.expect(!isSubPath(parent, parent ++ "ignore")); 303 304 // resolveRepoPath normalizes `..` first, so `/srv/git/../etc/passwd` 305 // becomes `/etc/passwd` — isSubPath then rejects it. 306 try std.testing.expect(!isSubPath(parent, sep ++ "etc" ++ sep ++ "passwd")); 307 308 const builtin = @import("builtin"); 309 310 if (.windows != builtin.os.tag) { 311 try std.testing.expect(isSubPath(sep, sep ++ "anything")); 312 try std.testing.expect(isSubPath(sep, sep)); 313 } 314 } 315