╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
84 defer watchdog_future.cancel(ctx.io); 85 86 var recv_buf: [4096]u8 = undefined; 87 var send_buf: [4096]u8 = undefined; 88 var stream_reader = stream.reader(ctx.io, &recv_buf); 89 var stream_writer = stream.writer(ctx.io, &send_buf); 90 ssh.handleConnection( 91 ctx.io, 92 ctx.allocator, 93 &stream_reader.interface, 94 &stream_writer.interface, 95 ctx.host_key, 96 &idle_state, 97 ctx.session_handler, 98 ) catch |session_err| { 99 serve_common.logError(ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 100 }; 101 } 102 }.h; 103 104 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 105 .io = io, 106 .allocator = allocator, 107 .host_key = host_key, 108 .session_handler = session_handler, 109 .err = err, 110 }, handle); 111 } 112 113 // shut down connections that made no SSH packet progress for a whole 114 // interval. exempt connections (interactive TUIs) end enforcement instead. 115 fn watchdog(io: std.Io, stream: *const std.Io.net.Stream, idle_state: *ssh.IdleState) void { 116 var last_seen: u64 = 0; 117 while (true) { 118 io.sleep(idle_interval, .awake) catch return; // canceled — connection is done 119 if (idle_state.exempt.load(.monotonic)) return; 120 const seen = idle_state.activity.load(.monotonic); 121 if (seen == last_seen) { 122 stream.shutdown(io, .both) catch {}; 123 return; 124 } 125 last_seen = seen; 126 } 127 } 128 129 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 130 // runTui owns the terminal, whose deinit restores the client's screen and 131 // runs as the function unwinds — so any error it returns leaves the TUI torn 132 // down and we can surface the failure on the restored screen before exiting. 133 runTui(handler, sess, pty) catch |err| { 134 serve_common.logError(handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 135 var buf: [256]u8 = undefined; 136 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 137 sess.writeBytes(msg) catch {}; 138 try sess.exit(1); 139 return; 140 }; 141 try sess.exit(0); 142 } 143 144 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 145 const allocator = sess.conn.allocator; 146 const io = sess.conn.io; 147 148 // some clients (notably scripted ssh with no local controlling tty) 149 // allocate a pty without ever sending a non-zero size. fall back to a 150 // conventional 80x24 in that case so render emits something. 151 const effective_pty = ssh.PtySize{ 152 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 153 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 154 }; 155 156 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 157 var session_arena = std.heap.ArenaAllocator.init(allocator); 158 defer session_arena.deinit(); 159 160 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 161 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 162 defer repo.deinit(io, allocator); 163 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 164 ui_session.is_terminal = true; 165 ui_session.web_port = handler.wui_port; 166 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 167 ui_session.io = io; 168 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 169 170 var nav = try ui.Nav.init(allocator, &ui_session); 171 defer nav.deinit(allocator); 172 173 var session_writer_buf: [8192]u8 = undefined; 174 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 175 176 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 177 // flushes, restoring the client's screen. as a function-scoped defer it runs 178 // before runTui returns — on the normal path and on any error — so the 179 // caller can write to the client afterward (and sess.exit can close cleanly). 180 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 181 .width = effective_pty.width_cells, 182 .height = effective_pty.height_cells, 183 }); 184 defer terminal.deinit(); 185 186 var last_size = Size{ .width = 0, .height = 0 }; 187 var last_grid = try Grid.init(allocator, last_size); 188 defer last_grid.deinit(); 189 190 // initial render — user sees the page immediately 191 try nav.root.build(allocator, .{ 192 .min_size = .{ .width = null, .height = null }, 193 .max_size = .{ .width = last_size.width, .height = last_size.height }, 194 }, nav.root.getFocus()); 195 _ = try terminal.render(&nav.root, &last_grid, &last_size); 196 197 // event loop. nextEvent blocks until something interesting arrives; 198 // for each event, rebuild the widget tree and re-render so the user 199 // sees the effect of their input on the same iteration. 200 while (!terminal.shouldQuit()) { 201 const event = try sess.nextEvent(); 202 switch (event) { 203 .data => |payload| { 204 defer allocator.free(payload); 205 try terminal.writeBytes(payload); 206 while (terminal.popKey()) |key| { 207 try ui.inputKey(allocator, &nav.root, key, &ui_session); 208 } 209 }, 210 .resize => |sz| { 211 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 212 while (terminal.popKey()) |key| { 213 try ui.inputKey(allocator, &nav.root, key, &ui_session); 214 } 215 }, 216 .close => terminal.requestQuit(), 217 } 218 219 try ui_session.applyAndWritePending(io, allocator, &repo); 220 221 // pick up data written by other handles so the next navigation 222 // builds its page from a current moment 223 try ui_session.reloadMoment(&repo); 224 225 // reconcile navigation: forward to a new page, or back on escape 226 try nav.sync(allocator, &ui_session); 227 228 // the quit button (on the quit tab) asks the host to tear down 229 if (ui_session.quit_requested) terminal.requestQuit(); 230 231 try nav.root.build(allocator, .{ 232 .min_size = .{ .width = null, .height = null }, 233 .max_size = .{ .width = last_size.width, .height = last_size.height }, 234 }, nav.root.getFocus()); 235 _ = try terminal.render(&nav.root, &last_grid, &last_size); 236 } 237 } 238 239 // --------------------------------------------------------------------------- 240 // git path (exec) 241 // --------------------------------------------------------------------------- 242 243 pub const GitService = enum { upload_pack, receive_pack }; 244 245 pub const ParsedGitCommand = struct { 246 service: GitService, 247 dir: []u8, 248 249 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 250 allocator.free(self.dir); 251 } 252 }; 253 254 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 255 const allocator = sess.conn.allocator; 256 const io = sess.conn.io; 257 258 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 259 defer parsed.deinit(allocator); 260 261 const create_if_missing = parsed.service == .receive_pack; 262 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 263 264 // authenticate pushes: the authenticated key must be registered to the 265 // repo's owner. 266 if (create_if_missing) { 267 const owner_repo = evt.parseOwnerRepoPath(parsed.dir) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 268 if (!try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 269 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 270 } 271 272 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, parsed.dir, create_if_missing)) { 273 .ok => |p| p, 274 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 275 .not_found => return writeError(sess, "repo not found"), 276 }; 277 defer allocator.free(repo_path); 278 279 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 280 try sess.exit(0); 281 return; 282 } 283 284 if (!create_if_missing) return writeError(sess, "repo not found"); 285 286 // create the on-disk repo for the just-minted event and serve the push 287 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 288 defer repo.deinit(io, allocator); 289 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 290 try sess.exit(0); 291 } 292 293 // serve an existing repo at `repo_path`, or return false if none is there 294 fn serveIfExists( 295 repo_path: []const u8, 296 sess: *ssh.SessionCtx, 297 io: std.Io, 298 allocator: std.mem.Allocator, 299 service: GitService, 300 ) !bool { 301 // a bare open() creates the directory while probing for the repo, so only 302 // attempt it when the path already exists 303 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 304 305 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 306 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 307 error.RepoNotFound => return false, 308 else => |e| return e, 309 }; 310 defer any_repo.deinit(io, allocator); 311 312 switch (any_repo) { 313 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 314 } 315 return true; 316 } 317 318 fn createRepo( 319 comptime repo_opts: rp.RepoOpts(.xit), 320 io: std.Io, 321 allocator: std.mem.Allocator, 322 repo_path: []const u8, 323 ) !rp.Repo(.xit, repo_opts) { 324 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 325 errdefer repo.deinit(io, allocator); 326 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 327 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 328 return repo; 329 } 330 331 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 332 // functions can consume them like any other stream, then run the requested 333 // service 334 fn servePack( 335 comptime repo_opts: rp.RepoOpts(.xit), 336 repo: *rp.Repo(.xit, repo_opts), 337 sess: *ssh.SessionCtx, 338 io: std.Io, 339 allocator: std.mem.Allocator, 340 service: GitService, 341 ) !void { 342 var session_reader_buf: [4096]u8 = undefined; 343 var session_writer_buf: [4096]u8 = undefined; 344 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 345 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 346 347 switch (service) { 348 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 349 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 350 } 351 352 // flush whatever the pack op buffered into our writer adapter 353 session_writer.interface.flush() catch {}; 354 } 355 356 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 357 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 358 defer tokens.deinit(); 359 360 const service_token = tokens.next() orelse return error.InvalidCommand; 361 const dir_token = tokens.next() orelse return error.InvalidCommand; 362 363 const service: GitService = 364 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 365 .upload_pack 366 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 367 .receive_pack 368 else 369 return error.UnsupportedService; 370 371 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 372 } 373 374 // true if `fingerprint` matches one of the named user's registered SSH keys 375 fn isKeyAuthorized( 376 io: std.Io, 377 allocator: std.mem.Allocator, 378 admin_repo_path: []const u8, 379 owner_name: []const u8, 380 fingerprint: *const [ssh.fingerprint_len]u8, 381 ) !bool { 382 var arena = std.heap.ArenaAllocator.init(allocator); 383 defer arena.deinit(); 384 385 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 386 387 var it = std.mem.splitScalar(u8, user.ssh_keys, '\n'); 388 while (it.next()) |line| { 389 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 390 if (std.mem.eql(u8, &fp, fingerprint)) return true; 391 } 392 return false; 393 } 394 395 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 396 // blank or not a parseable "<type> <base64> [comment]" entry 397 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 398 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 399 _ = it.next() orelse return null; // key type 400 const blob_b64 = it.next() orelse return null; 401 402 const decoder = std.base64.standard.Decoder; 403 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 404 var blob_buf: [4096]u8 = undefined; 405 if (blob_len > blob_buf.len) return null; 406 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 407 408 return ssh.formatFingerprint(blob_buf[0..blob_len]); 409 } 410 411 // write an error to the client's stderr and exit non-zero. stderr (not stdout) 412 // because the git exec sessions that call this carry the pack protocol on 413 // stdout, where stray text breaks the client's pkt-line parser. 414 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 415 try sess.writeStderr("haxy ssh: " ++ msg ++ "\n"); 416 try sess.exit(1); 417 } 418 419 test "parseGitCommand rejects malformed input" { 420 const allocator = std.testing.allocator; 421 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 422 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 423 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 424 } 425 426 test "parseGitCommand happy paths" { 427 const allocator = std.testing.allocator; 428 429 { 430 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 431 defer parsed.deinit(allocator); 432 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 433 try std.testing.expectEqualStrings("some-repo", parsed.dir); 434 } 435 { 436 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 437 defer parsed.deinit(allocator); 438 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 439 try std.testing.expectEqualStrings("user/proj", parsed.dir); 440 } 441 { 442 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 443 defer parsed.deinit(allocator); 444 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 445 try std.testing.expectEqualStrings("repo", parsed.dir); 446 } 447 } 448