╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
175 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 176 const allocator = sess.conn.allocator; 177 const io = sess.conn.io; 178 179 // some clients (notably scripted ssh with no local controlling tty) 180 // allocate a pty without ever sending a non-zero size. fall back to a 181 // conventional 80x24 in that case so render emits something. 182 const effective_pty = ssh.PtySize{ 183 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 184 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 185 }; 186 187 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 188 var session_arena = std.heap.ArenaAllocator.init(allocator); 189 defer session_arena.deinit(); 190 191 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 192 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 193 defer repo.deinit(io, allocator); 194 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 195 ui_session.is_terminal = true; 196 ui_session.web_port = handler.wui_port; 197 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 198 ui_session.io = io; 199 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 200 201 var nav = try ui.Nav.init(allocator, &ui_session); 202 defer nav.deinit(allocator); 203 204 var session_writer_buf: [8192]u8 = undefined; 205 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 206 207 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 208 // flushes, restoring the client's screen. as a function-scoped defer it runs 209 // before runTui returns — on the normal path and on any error — so the 210 // caller can write to the client afterward (and sess.exit can close cleanly). 211 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 212 .width = effective_pty.width_cells, 213 .height = effective_pty.height_cells, 214 }); 215 defer terminal.deinit(); 216 217 var last_size = Size{ .width = 0, .height = 0 }; 218 var last_grid = try Grid.init(allocator, last_size); 219 defer last_grid.deinit(); 220 221 // initial render — user sees the page immediately 222 try nav.root.build(allocator, .{ 223 .min_size = .{ .width = null, .height = null }, 224 .max_size = .{ .width = last_size.width, .height = last_size.height }, 225 }, nav.root.getFocus()); 226 _ = try terminal.render(&nav.root, &last_grid, &last_size); 227 228 // event loop. nextEvent blocks until something interesting arrives; 229 // for each event, rebuild the widget tree and re-render so the user 230 // sees the effect of their input on the same iteration. 231 while (!terminal.shouldQuit()) { 232 const event = try sess.nextEvent(); 233 switch (event) { 234 .data => |payload| { 235 defer allocator.free(payload); 236 try terminal.writeBytes(payload); 237 while (terminal.popKey()) |key| { 238 try ui.inputKey(allocator, &nav.root, key, &ui_session); 239 } 240 }, 241 .resize => |sz| { 242 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 243 while (terminal.popKey()) |key| { 244 try ui.inputKey(allocator, &nav.root, key, &ui_session); 245 } 246 }, 247 // either way no more input can arrive, so nothing is left to 248 // drive the ui — but on .eof the channel is still open, so the 249 // teardown below still reaches the client. 250 .eof, .close => terminal.requestQuit(), 251 } 252 253 try ui_session.applyAndWritePending(io, allocator, &repo); 254 255 // pick up data written by other handles so the next navigation 256 // builds its page from a current moment 257 try ui_session.reloadMoment(&repo); 258 259 // reconcile navigation: forward to a new page, or back on escape 260 try nav.sync(allocator, &ui_session); 261 262 // the quit button (on the quit tab) asks the host to tear down 263 if (ui_session.quit_requested) terminal.requestQuit(); 264 265 try nav.root.build(allocator, .{ 266 .min_size = .{ .width = null, .height = null }, 267 .max_size = .{ .width = last_size.width, .height = last_size.height }, 268 }, nav.root.getFocus()); 269 _ = try terminal.render(&nav.root, &last_grid, &last_size); 270 } 271 } 272 273 // --------------------------------------------------------------------------- 274 // git path (exec) 275 // --------------------------------------------------------------------------- 276 277 pub const GitService = enum { upload_pack, receive_pack }; 278 279 pub const ParsedGitCommand = struct { 280 service: GitService, 281 dir: []u8, 282 283 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 284 allocator.free(self.dir); 285 } 286 }; 287 288 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 289 const allocator = sess.conn.allocator; 290 const io = sess.conn.io; 291 292 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 293 defer parsed.deinit(allocator); 294 295 const create_if_missing = parsed.service == .receive_pack; 296 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 297 298 // authenticate pushes: the authenticated key must be registered to the 299 // repo's owner. 300 if (create_if_missing) { 301 const owner_repo = evt.parseOwnerRepoPath(parsed.dir) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 302 if (!try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 303 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 304 } 305 306 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, parsed.dir, create_if_missing)) { 307 .ok => |p| p, 308 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 309 .not_found => return writeError(sess, "repo not found"), 310 }; 311 defer allocator.free(repo_path); 312 313 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 314 try sess.exit(0); 315 return; 316 } 317 318 if (!create_if_missing) return writeError(sess, "repo not found"); 319 320 // create the on-disk repo for the just-minted event and serve the push 321 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 322 defer repo.deinit(io, allocator); 323 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 324 try sess.exit(0); 325 } 326 327 // serve an existing repo at `repo_path`, or return false if none is there 328 fn serveIfExists( 329 repo_path: []const u8, 330 sess: *ssh.SessionCtx, 331 io: std.Io, 332 allocator: std.mem.Allocator, 333 service: GitService, 334 ) !bool { 335 // a bare open() creates the directory while probing for the repo, so only 336 // attempt it when the path already exists 337 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 338 339 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 340 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 341 error.RepoNotFound => return false, 342 else => |e| return e, 343 }; 344 defer any_repo.deinit(io, allocator); 345 346 switch (any_repo) { 347 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 348 } 349 return true; 350 } 351 352 fn createRepo( 353 comptime repo_opts: rp.RepoOpts(.xit), 354 io: std.Io, 355 allocator: std.mem.Allocator, 356 repo_path: []const u8, 357 ) !rp.Repo(.xit, repo_opts) { 358 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 359 errdefer repo.deinit(io, allocator); 360 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 361 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 362 return repo; 363 } 364 365 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 366 // functions can consume them like any other stream, then run the requested 367 // service 368 fn servePack( 369 comptime repo_opts: rp.RepoOpts(.xit), 370 repo: *rp.Repo(.xit, repo_opts), 371 sess: *ssh.SessionCtx, 372 io: std.Io, 373 allocator: std.mem.Allocator, 374 service: GitService, 375 ) !void { 376 var session_reader_buf: [4096]u8 = undefined; 377 var session_writer_buf: [4096]u8 = undefined; 378 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 379 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 380 381 switch (service) { 382 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 383 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 384 } 385 386 // flush whatever the pack op buffered into our writer adapter 387 session_writer.interface.flush() catch {}; 388 } 389 390 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 391 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 392 defer tokens.deinit(); 393 394 const service_token = tokens.next() orelse return error.InvalidCommand; 395 const dir_token = tokens.next() orelse return error.InvalidCommand; 396 397 const service: GitService = 398 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 399 .upload_pack 400 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 401 .receive_pack 402 else 403 return error.UnsupportedService; 404 405 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 406 } 407 408 // true if `fingerprint` matches one of the named user's registered SSH keys 409 fn isKeyAuthorized( 410 io: std.Io, 411 allocator: std.mem.Allocator, 412 admin_repo_path: []const u8, 413 owner_name: []const u8, 414 fingerprint: *const [ssh.fingerprint_len]u8, 415 ) !bool { 416 var arena = std.heap.ArenaAllocator.init(allocator); 417 defer arena.deinit(); 418 419 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 420 421 var it = std.mem.splitScalar(u8, user.ssh_keys, '\n'); 422 while (it.next()) |line| { 423 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 424 if (std.mem.eql(u8, &fp, fingerprint)) return true; 425 } 426 return false; 427 } 428 429 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 430 // blank or not a parseable "<type> <base64> [comment]" entry 431 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 432 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 433 _ = it.next() orelse return null; // key type 434 const blob_b64 = it.next() orelse return null; 435 436 const decoder = std.base64.standard.Decoder; 437 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 438 var blob_buf: [4096]u8 = undefined; 439 if (blob_len > blob_buf.len) return null; 440 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 441 442 return ssh.formatFingerprint(blob_buf[0..blob_len]); 443 } 444 445 // write an error to the client's stderr and exit non-zero. stderr (not stdout) 446 // because the git exec sessions that call this carry the pack protocol on 447 // stdout, where stray text breaks the client's pkt-line parser. 448 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 449 try sess.writeStderr("haxy ssh: " ++ msg ++ "\n"); 450 try sess.exit(1); 451 } 452 453 test "parseGitCommand rejects malformed input" { 454 const allocator = std.testing.allocator; 455 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 456 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 457 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 458 } 459 460 test "parseGitCommand happy paths" { 461 const allocator = std.testing.allocator; 462 463 { 464 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 465 defer parsed.deinit(allocator); 466 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 467 try std.testing.expectEqualStrings("some-repo", parsed.dir); 468 } 469 { 470 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 471 defer parsed.deinit(allocator); 472 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 473 try std.testing.expectEqualStrings("user/proj", parsed.dir); 474 } 475 { 476 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 477 defer parsed.deinit(allocator); 478 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 479 try std.testing.expectEqualStrings("repo", parsed.dir); 480 } 481 } 482