╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const xitui = xit.xitui; 5 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 6 const Grid = xitui.grid.Grid; 7 const Size = xitui.layout.Size; 8 const ui = @import("./ui.zig"); 9 const ssh = @import("./serve_ssh_protocol.zig"); 10 const evt = @import("./event.zig"); 11 const serve_common = @import("./serve_common.zig"); 12 13 pub const SessionHandler = struct { 14 admin_repo_path: []const u8, 15 repo_root_path: []const u8, 16 // test mode serves repos directly by path instead of resolving them as 17 // <owner>/<repo> through the event store 18 is_test: bool, 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 pub fn runListener( 42 io: std.Io, 43 allocator: std.mem.Allocator, 44 host_key: *const ssh.HostKey, 45 session_handler: *const SessionHandler, 46 net_server: *std.Io.net.Server, 47 tasks: *std.Io.Group, 48 err: *std.Io.Writer, 49 ) void { 50 const Context = struct { 51 io: std.Io, 52 allocator: std.mem.Allocator, 53 host_key: *const ssh.HostKey, 54 session_handler: *const SessionHandler, 55 err: *std.Io.Writer, 56 }; 57 58 const handle = struct { 59 fn h(ctx: Context, stream: std.Io.net.Stream) void { 60 defer stream.close(ctx.io); 61 var recv_buf: [4096]u8 = undefined; 62 var send_buf: [4096]u8 = undefined; 63 var stream_reader = stream.reader(ctx.io, &recv_buf); 64 var stream_writer = stream.writer(ctx.io, &send_buf); 65 ssh.handleConnection( 66 ctx.io, 67 ctx.allocator, 68 &stream_reader.interface, 69 &stream_writer.interface, 70 ctx.host_key, 71 ctx.session_handler, 72 ) catch |session_err| { 73 serve_common.logError(ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 74 }; 75 } 76 }.h; 77 78 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 79 .io = io, 80 .allocator = allocator, 81 .host_key = host_key, 82 .session_handler = session_handler, 83 .err = err, 84 }, handle); 85 } 86 87 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 88 // runTui owns the terminal, whose deinit restores the client's screen and 89 // runs as the function unwinds — so any error it returns leaves the TUI torn 90 // down and we can surface the failure on the restored screen before exiting. 91 runTui(handler, sess, pty) catch |err| { 92 std.debug.print("ssh tui session failed: {s}\n", .{@errorName(err)}); 93 var buf: [256]u8 = undefined; 94 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 95 sess.writeBytes(msg) catch {}; 96 try sess.exit(1); 97 return; 98 }; 99 try sess.exit(0); 100 } 101 102 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 103 const allocator = sess.allocator; 104 const io = sess.io; 105 106 // some clients (notably scripted ssh with no local controlling tty) 107 // allocate a pty without ever sending a non-zero size. fall back to a 108 // conventional 80x24 in that case so render emits something. 109 const effective_pty = ssh.PtySize{ 110 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 111 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 112 }; 113 114 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 115 var session_arena = std.heap.ArenaAllocator.init(allocator); 116 defer session_arena.deinit(); 117 118 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 119 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 120 defer repo.deinit(io, allocator); 121 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 122 ui_session.is_terminal = true; 123 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 124 ui_session.io = io; 125 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 126 127 var nav = try ui.Nav.init(allocator, &ui_session); 128 defer nav.deinit(allocator); 129 130 var session_writer_buf: [8192]u8 = undefined; 131 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 132 133 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 134 // flushes, restoring the client's screen. as a function-scoped defer it runs 135 // before runTui returns — on the normal path and on any error — so the 136 // caller can write to the client afterward (and sess.exit can close cleanly). 137 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 138 .width = effective_pty.width_cells, 139 .height = effective_pty.height_cells, 140 }); 141 defer terminal.deinit(); 142 143 var last_size = Size{ .width = 0, .height = 0 }; 144 var last_grid = try Grid.init(allocator, last_size); 145 defer last_grid.deinit(); 146 147 // initial render — user sees the page immediately 148 try nav.root.build(allocator, .{ 149 .min_size = .{ .width = null, .height = null }, 150 .max_size = .{ .width = last_size.width, .height = last_size.height }, 151 }, nav.root.getFocus()); 152 _ = try terminal.render(&nav.root, &last_grid, &last_size); 153 154 // event loop. nextEvent blocks until something interesting arrives; 155 // for each event, rebuild the widget tree and re-render so the user 156 // sees the effect of their input on the same iteration. 157 while (!terminal.shouldQuit()) { 158 const event = try sess.nextEvent(); 159 switch (event) { 160 .data => |payload| { 161 defer allocator.free(payload); 162 try terminal.writeBytes(payload); 163 while (terminal.popKey()) |key| { 164 try ui.inputKey(allocator, &nav.root, key, &ui_session); 165 } 166 }, 167 .resize => |sz| { 168 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 169 while (terminal.popKey()) |key| { 170 try ui.inputKey(allocator, &nav.root, key, &ui_session); 171 } 172 }, 173 .close => terminal.requestQuit(), 174 } 175 176 try ui_session.applyAndWritePending(io, allocator, &repo); 177 178 // reconcile navigation: forward to a new page, or back on escape 179 try nav.sync(allocator, &ui_session); 180 181 // the quit button (on the quit tab) asks the host to tear down 182 if (ui_session.quit_requested) terminal.requestQuit(); 183 184 try nav.root.build(allocator, .{ 185 .min_size = .{ .width = null, .height = null }, 186 .max_size = .{ .width = last_size.width, .height = last_size.height }, 187 }, nav.root.getFocus()); 188 _ = try terminal.render(&nav.root, &last_grid, &last_size); 189 } 190 } 191 192 // --------------------------------------------------------------------------- 193 // git path (exec) 194 // --------------------------------------------------------------------------- 195 196 pub const GitService = enum { upload_pack, receive_pack }; 197 198 pub const ParsedGitCommand = struct { 199 service: GitService, 200 dir: []u8, 201 202 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 203 allocator.free(self.dir); 204 } 205 }; 206 207 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 208 const allocator = sess.allocator; 209 const io = sess.io; 210 211 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 212 defer parsed.deinit(allocator); 213 214 const create_if_missing = parsed.service == .receive_pack; 215 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 216 217 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.is_test, handler.repo_root_path, handler.admin_repo_path, parsed.dir, create_if_missing)) { 218 .ok => |p| p, 219 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 220 .not_found => return writeError(sess, "repo not found"), 221 }; 222 defer allocator.free(repo_path); 223 224 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 225 try sess.exit(0); 226 return; 227 } 228 229 if (!create_if_missing) return writeError(sess, "repo not found"); 230 231 // create the on-disk repo for the just-minted event and serve the push 232 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 233 defer repo.deinit(io, allocator); 234 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 235 try sess.exit(0); 236 } 237 238 // serve an existing repo at `repo_path`, or return false if none is there 239 fn serveIfExists( 240 repo_path: []const u8, 241 sess: *ssh.SessionCtx, 242 io: std.Io, 243 allocator: std.mem.Allocator, 244 service: GitService, 245 ) !bool { 246 // a bare open() creates the directory while probing for the repo, so only 247 // attempt it when the path already exists 248 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 249 250 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 251 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 252 error.RepoNotFound => return false, 253 else => |e| return e, 254 }; 255 defer any_repo.deinit(io, allocator); 256 257 switch (any_repo) { 258 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 259 } 260 return true; 261 } 262 263 fn createRepo( 264 comptime repo_opts: rp.RepoOpts(.xit), 265 io: std.Io, 266 allocator: std.mem.Allocator, 267 repo_path: []const u8, 268 ) !rp.Repo(.xit, repo_opts) { 269 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 270 errdefer repo.deinit(io, allocator); 271 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 272 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 273 return repo; 274 } 275 276 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 277 // functions can consume them like any other stream, then run the requested 278 // service 279 fn servePack( 280 comptime repo_opts: rp.RepoOpts(.xit), 281 repo: *rp.Repo(.xit, repo_opts), 282 sess: *ssh.SessionCtx, 283 io: std.Io, 284 allocator: std.mem.Allocator, 285 service: GitService, 286 ) !void { 287 var session_reader_buf: [4096]u8 = undefined; 288 var session_writer_buf: [4096]u8 = undefined; 289 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 290 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 291 292 switch (service) { 293 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 294 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 295 } 296 297 // flush whatever the pack op buffered into our writer adapter 298 session_writer.interface.flush() catch {}; 299 } 300 301 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 302 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 303 defer tokens.deinit(); 304 305 const service_token = tokens.next() orelse return error.InvalidCommand; 306 const dir_token = tokens.next() orelse return error.InvalidCommand; 307 308 const service: GitService = 309 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 310 .upload_pack 311 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 312 .receive_pack 313 else 314 return error.UnsupportedService; 315 316 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 317 } 318 319 // write an error to the client and exit non-zero 320 fn writeError(sess: *ssh.SessionCtx, msg: []const u8) !void { 321 var buf: [256]u8 = undefined; 322 const text = try std.fmt.bufPrint(&buf, "haxy ssh: {s}\n", .{msg}); 323 try sess.writeBytes(text); 324 try sess.exit(1); 325 } 326 327 test "parseGitCommand rejects malformed input" { 328 const allocator = std.testing.allocator; 329 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 330 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 331 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 332 } 333 334 test "parseGitCommand happy paths" { 335 const allocator = std.testing.allocator; 336 337 { 338 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 339 defer parsed.deinit(allocator); 340 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 341 try std.testing.expectEqualStrings("some-repo", parsed.dir); 342 } 343 { 344 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 345 defer parsed.deinit(allocator); 346 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 347 try std.testing.expectEqualStrings("user/proj", parsed.dir); 348 } 349 { 350 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 351 defer parsed.deinit(allocator); 352 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 353 try std.testing.expectEqualStrings("repo", parsed.dir); 354 } 355 } 356