╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const builtin = @import("builtin"); 3 const xit = @import("xit"); 4 const rp = xit.repo; 5 const xitui = xit.xitui; 6 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 7 const Grid = xitui.grid.Grid; 8 const Size = xitui.layout.Size; 9 const ui = @import("./ui.zig"); 10 const ssh = @import("./serve_ssh_protocol.zig"); 11 const evt = @import("./event.zig"); 12 const serve_common = @import("./serve_common.zig"); 13 const fork = @import("./fork.zig"); 14 15 // listener resource limits. the watchdog gives unauthenticated peers a hard 16 // deadline, detects idle non-interactive sessions from protocol progress, and 17 // bounds the post-CLOSE drain. each connection holds two OS threads under 18 // std.Io.Threaded (session + watchdog), so the cap is sized by thread count. 19 const max_connections: u32 = 4096; 20 const watchdog_interval = std.Io.Duration.fromSeconds(5); 21 const preauth_timeout_ticks: u32 = 6; // 30 seconds 22 const idle_timeout_ticks: u32 = 24; // 120 seconds 23 const close_drain_timeout_ticks: u32 = 2; // 5-10 seconds 24 25 var active_connections: std.atomic.Value(u32) = .init(0); 26 27 pub const SessionHandler = struct { 28 admin_repo_path: []const u8, 29 repo_root_path: []const u8, 30 wui_port: u16, // port the web UI is served on, shown in the TUI footer's url 31 clone_http_port: ?u16, 32 clone_ssh_port: ?u16, 33 err: *std.Io.Writer, 34 35 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 36 serve_common.logError(sess.conn.io, self.err, "ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 37 switch (request) { 38 .shell => |pty_maybe| { 39 const pty = pty_maybe orelse { 40 // a shell without a pty has no useful TUI to render; in 41 // openssh client terms this is `ssh -T host`. say so and 42 // exit non-zero. 43 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 44 try sess.exit(1); 45 return; 46 }; 47 sess.exemptFromIdleTimeout(); 48 try runTuiSession(self, sess, pty); 49 }, 50 .exec => |command| { 51 try runGitSession(self, sess, command); 52 }, 53 } 54 } 55 }; 56 57 pub fn runListener( 58 io: std.Io, 59 allocator: std.mem.Allocator, 60 host_key: *const ssh.HostKey, 61 session_handler: *const SessionHandler, 62 net_server: *std.Io.net.Server, 63 tasks: *std.Io.Group, 64 err: *std.Io.Writer, 65 ) void { 66 const Context = struct { 67 io: std.Io, 68 allocator: std.mem.Allocator, 69 host_key: *const ssh.HostKey, 70 session_handler: *const SessionHandler, 71 err: *std.Io.Writer, 72 }; 73 74 const handle = struct { 75 fn h(ctx: Context, stream: std.Io.net.Stream) void { 76 defer stream.close(ctx.io); 77 78 const prev_count = active_connections.fetchAdd(1, .monotonic); 79 defer _ = active_connections.fetchSub(1, .monotonic); 80 if (prev_count >= max_connections) { 81 serve_common.logError(ctx.io, ctx.err, "ssh: connection limit reached, dropping\n", .{}); 82 return; 83 } 84 85 var idle_state = ssh.IdleState{}; 86 var watchdog_future = std.Io.concurrent(ctx.io, watchdog, .{ ctx.io, &stream, &idle_state }) catch |spawn_err| { 87 serve_common.logError(ctx.io, ctx.err, "ssh: watchdog spawn failed: {s}\n", .{@errorName(spawn_err)}); 88 return; 89 }; 90 defer watchdog_future.cancel(ctx.io); 91 92 var recv_buf: [4096]u8 = undefined; 93 var send_buf: [4096]u8 = undefined; 94 var stream_reader = stream.reader(ctx.io, &recv_buf); 95 var stream_writer = stream.writer(ctx.io, &send_buf); 96 ssh.handleConnection( 97 ctx.io, 98 ctx.allocator, 99 &stream_reader.interface, 100 &stream_writer.interface, 101 ctx.host_key, 102 &idle_state, 103 ctx.session_handler, 104 ) catch |session_err| { 105 serve_common.logError(ctx.io, ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 106 }; 107 } 108 }.h; 109 110 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 111 .io = io, 112 .allocator = allocator, 113 .host_key = host_key, 114 .session_handler = session_handler, 115 .err = err, 116 }, handle); 117 } 118 119 // enforce a hard pre-auth deadline, an idle timeout for non-interactive 120 // sessions, and a bounded close drain. interactive sessions are exempt only 121 // from the idle timeout; the watchdog remains available to break a stalled 122 // teardown. 123 fn watchdog(io: std.Io, stream: *const std.Io.net.Stream, idle_state: *ssh.IdleState) void { 124 var last_seen: u64 = 0; 125 var preauth_ticks: u32 = 0; 126 var idle_ticks: u32 = 0; 127 var closing_ticks: u32 = 0; 128 while (true) { 129 io.sleep(watchdog_interval, .awake) catch return; // canceled — connection is done 130 131 if (idle_state.closing.load(.acquire)) { 132 closing_ticks += 1; 133 if (closing_ticks >= close_drain_timeout_ticks) { 134 stream.shutdown(io, .both) catch {}; 135 return; 136 } 137 continue; 138 } 139 140 if (!idle_state.authenticated.load(.acquire)) { 141 preauth_ticks += 1; 142 if (preauth_ticks >= preauth_timeout_ticks) { 143 stream.shutdown(io, .both) catch {}; 144 return; 145 } 146 continue; 147 } 148 149 if (idle_state.exempt.load(.monotonic)) continue; 150 const seen = idle_state.activity.load(.monotonic); 151 if (seen == last_seen) { 152 idle_ticks += 1; 153 if (idle_ticks >= idle_timeout_ticks) { 154 stream.shutdown(io, .both) catch {}; 155 return; 156 } 157 } else { 158 idle_ticks = 0; 159 } 160 last_seen = seen; 161 } 162 } 163 164 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 165 // runTui owns the terminal, whose deinit restores the client's screen and 166 // runs as the function unwinds — so any error it returns leaves the TUI torn 167 // down and we can surface the failure on the restored screen before exiting. 168 runTui(handler, sess, pty) catch |err| { 169 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 170 var buf: [256]u8 = undefined; 171 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 172 sess.writeBytes(msg) catch {}; 173 try sess.exit(1); 174 return; 175 }; 176 try sess.exit(0); 177 } 178 179 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 180 const allocator = sess.conn.allocator; 181 const io = sess.conn.io; 182 183 // some clients (notably scripted ssh with no local controlling tty) 184 // allocate a pty without ever sending a non-zero size. fall back to a 185 // conventional 80x24 in that case so render emits something. 186 const effective_pty = ssh.PtySize{ 187 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 188 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 189 }; 190 191 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 192 var session_arena = std.heap.ArenaAllocator.init(allocator); 193 defer session_arena.deinit(); 194 195 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 196 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 197 defer repo.deinit(io, allocator); 198 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 199 ui_session.is_terminal = true; 200 ui_session.web_port = handler.wui_port; 201 ui_session.data.clone_http_port = handler.clone_http_port; 202 ui_session.data.clone_ssh_port = handler.clone_ssh_port; 203 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 204 ui_session.io = io; 205 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 206 207 var nav = try ui.Nav.init(allocator, &ui_session); 208 defer nav.deinit(allocator); 209 210 var session_writer_buf: [8192]u8 = undefined; 211 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 212 213 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 214 // flushes, restoring the client's screen. as a function-scoped defer it runs 215 // before runTui returns — on the normal path and on any error — so the 216 // caller can write to the client afterward (and sess.exit can close cleanly). 217 var terminal_size = Size{ 218 .width = effective_pty.width_cells, 219 .height = effective_pty.height_cells, 220 }; 221 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 222 defer if (terminal_maybe) |*terminal| terminal.deinit(); 223 224 var last_size = Size{ .width = 0, .height = 0 }; 225 var last_grid = try Grid.init(allocator, last_size); 226 defer last_grid.deinit(); 227 228 // initial render — user sees the page immediately 229 try nav.root.build(allocator, .{ 230 .min_size = .{ .width = null, .height = null }, 231 .max_size = .{ .width = last_size.width, .height = last_size.height }, 232 }, nav.root.getFocus()); 233 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root, &last_grid, &last_size); 234 235 // event loop. nextEvent blocks until something interesting arrives; 236 // for each event, rebuild the widget tree and re-render so the user 237 // sees the effect of their input on the same iteration. 238 event_loop: while (true) { 239 const event = try sess.nextEvent(); 240 if (terminal_maybe) |*terminal| { 241 switch (event) { 242 .data => |payload| { 243 defer allocator.free(payload); 244 try terminal.writeBytes(payload); 245 while (terminal.popKey()) |key| { 246 try ui.inputKey(allocator, &nav.root, key, &ui_session); 247 } 248 }, 249 .resize => |sz| { 250 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 251 terminal.pushResize(terminal_size); 252 while (terminal.popKey()) |key| { 253 try ui.inputKey(allocator, &nav.root, key, &ui_session); 254 } 255 }, 256 .eof, .close => break :event_loop, 257 } 258 } else { 259 switch (event) { 260 .data => |payload| { 261 defer allocator.free(payload); 262 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 263 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 264 last_size = .{ .width = 0, .height = 0 }; 265 }, 266 .resize => |sz| { 267 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 268 continue; 269 }, 270 .eof, .close => break :event_loop, 271 } 272 } 273 274 if (ui_session.host_request) |request| { 275 ui_session.host_request = null; 276 switch (request) { 277 .show_copyable_text => |copyable_text| { 278 if (terminal_maybe) |*terminal| terminal.deinit(); 279 terminal_maybe = null; 280 try session_writer.interface.print("\x1b[2J\x1b[Hcopy the following text and then press enter to go back:\r\n\r\n{s}\r\n", .{copyable_text}); 281 try session_writer.interface.flush(); 282 continue; 283 }, 284 .sync_events => {}, 285 } 286 } 287 288 try ui_session.applyAndWritePending(io, allocator, &repo); 289 290 // pick up data written by other handles so the next navigation 291 // builds its page from a current moment 292 try ui_session.reloadMoment(allocator, &repo); 293 294 // reconcile navigation: forward to a new page, or back on escape 295 try nav.sync(allocator, &ui_session); 296 297 // the quit button (on the quit tab) asks the host to tear down 298 if (ui_session.quit_requested) break :event_loop; 299 300 try nav.root.build(allocator, .{ 301 .min_size = .{ .width = null, .height = null }, 302 .max_size = .{ .width = last_size.width, .height = last_size.height }, 303 }, nav.root.getFocus()); 304 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root, &last_grid, &last_size); 305 } 306 } 307 308 // --------------------------------------------------------------------------- 309 // git path (exec) 310 // --------------------------------------------------------------------------- 311 312 pub const GitService = enum { upload_pack, receive_pack }; 313 314 pub const ParsedGitCommand = struct { 315 service: GitService, 316 dir: []u8, 317 318 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 319 allocator.free(self.dir); 320 } 321 }; 322 323 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 324 const allocator = sess.conn.allocator; 325 const io = sess.conn.io; 326 327 const parsed = parseGitCommand(allocator, command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 328 defer parsed.deinit(allocator); 329 const repo_prefix = "/repo/"; 330 const repo_identity = if (std.mem.startsWith(u8, parsed.dir, repo_prefix)) parsed.dir[repo_prefix.len..] else parsed.dir; 331 332 if (fork.parseRoute(repo_identity)) |route| { 333 if (evt.parseOwnerRepoPath(route.identity) == null) return writeError(sess, "repo path must be <owner>/<repo>"); 334 if (parsed.service == .receive_pack and !xit.ref.validateName(route.target)) return writeError(sess, "invalid target branch"); 335 336 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 337 defer allocator.free(draft_path); 338 var draft = rp.AnyRepo(.xit, .{}).open(io, allocator, .{ .path = draft_path }) catch 339 return writeError(sess, "patch draft not found"); 340 defer draft.deinit(io, allocator); 341 switch (draft) { 342 inline else => |*repo| { 343 const author_maybe = try fork.draftAuthor(repo.self_repo_opts, repo, io, allocator); 344 defer if (author_maybe) |author| allocator.free(author); 345 const author = author_maybe orelse return writeError(sess, "invalid patch draft"); 346 if (builtin.mode != .Debug and !try isKeyAuthorized(io, allocator, handler.admin_repo_path, author, &sess.fingerprint)) 347 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 348 var reader_buf: [4096]u8 = undefined; 349 var writer_buf: [4096]u8 = undefined; 350 var reader = ssh.SessionReader.init(sess, &reader_buf); 351 var writer = ssh.SessionWriter.init(sess, &writer_buf); 352 switch (parsed.service) { 353 .upload_pack => try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{}), 354 .receive_pack => try repo.receivePack(io, allocator, &reader.interface, &writer.interface, .{}), 355 } 356 writer.interface.flush() catch {}; 357 if (parsed.service == .receive_pack) { 358 if (try repo.readRef(io, fork.ref) == null) return writeError(sess, "push HEAD to refs/heads/patch"); 359 try fork.setTarget(repo.self_repo_opts, repo, io, allocator, route.target); 360 } 361 }, 362 } 363 try sess.exit(0); 364 return; 365 } 366 367 const create_if_missing = parsed.service == .receive_pack; 368 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 369 370 // authenticate pushes: the authenticated key must be registered to the 371 // repo's owner. 372 if (create_if_missing) { 373 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 374 if (builtin.mode != .Debug and !try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 375 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 376 } 377 378 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 379 .ok => |p| p, 380 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 381 .not_found => return writeError(sess, "repo not found"), 382 }; 383 defer allocator.free(repo_path); 384 385 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 386 try sess.exit(0); 387 return; 388 } 389 390 if (!create_if_missing) return writeError(sess, "repo not found"); 391 392 // create the on-disk repo for the just-minted event and serve the push 393 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 394 defer repo.deinit(io, allocator); 395 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 396 try sess.exit(0); 397 } 398 399 // serve an existing repo at `repo_path`, or return false if none is there 400 fn serveIfExists( 401 repo_path: []const u8, 402 sess: *ssh.SessionCtx, 403 io: std.Io, 404 allocator: std.mem.Allocator, 405 service: GitService, 406 ) !bool { 407 // a bare open() creates the directory while probing for the repo, so only 408 // attempt it when the path already exists 409 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 410 411 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 412 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 413 error.RepoNotFound => return false, 414 else => |e| return e, 415 }; 416 defer any_repo.deinit(io, allocator); 417 418 switch (any_repo) { 419 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 420 } 421 return true; 422 } 423 424 fn createRepo( 425 comptime repo_opts: rp.RepoOpts(.xit), 426 io: std.Io, 427 allocator: std.mem.Allocator, 428 repo_path: []const u8, 429 ) !rp.Repo(.xit, repo_opts) { 430 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 431 errdefer repo.deinit(io, allocator); 432 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 433 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 434 return repo; 435 } 436 437 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 438 // functions can consume them like any other stream, then run the requested 439 // service 440 fn servePack( 441 comptime repo_opts: rp.RepoOpts(.xit), 442 repo: *rp.Repo(.xit, repo_opts), 443 sess: *ssh.SessionCtx, 444 io: std.Io, 445 allocator: std.mem.Allocator, 446 service: GitService, 447 ) !void { 448 var session_reader_buf: [4096]u8 = undefined; 449 var session_writer_buf: [4096]u8 = undefined; 450 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 451 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 452 453 switch (service) { 454 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 455 .receive_pack => try evt.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}), 456 } 457 458 // flush whatever the pack op buffered into our writer adapter 459 session_writer.interface.flush() catch {}; 460 } 461 462 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 463 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 464 defer tokens.deinit(); 465 466 const service_token = tokens.next() orelse return error.InvalidCommand; 467 const dir_token = tokens.next() orelse return error.InvalidCommand; 468 469 const service: GitService = 470 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 471 .upload_pack 472 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 473 .receive_pack 474 else 475 return error.UnsupportedService; 476 477 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 478 } 479 480 // true if `fingerprint` matches one of the named user's registered SSH keys 481 fn isKeyAuthorized( 482 io: std.Io, 483 allocator: std.mem.Allocator, 484 admin_repo_path: []const u8, 485 owner_name: []const u8, 486 fingerprint: *const [ssh.fingerprint_len]u8, 487 ) !bool { 488 var arena = std.heap.ArenaAllocator.init(allocator); 489 defer arena.deinit(); 490 491 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 492 493 var it = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 494 while (it.next()) |line| { 495 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 496 if (std.mem.eql(u8, &fp, fingerprint)) return true; 497 } 498 return false; 499 } 500 501 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 502 // blank or not a parseable "<type> <base64> [comment]" entry 503 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 504 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 505 _ = it.next() orelse return null; // key type 506 const blob_b64 = it.next() orelse return null; 507 508 const decoder = std.base64.standard.Decoder; 509 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 510 var blob_buf: [4096]u8 = undefined; 511 if (blob_len > blob_buf.len) return null; 512 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 513 514 return ssh.formatFingerprint(blob_buf[0..blob_len]); 515 } 516 517 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 518 const body = "ERR haxy ssh: " ++ msg; 519 var packet: [body.len + 4]u8 = undefined; 520 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 521 try sess.writeBytes(line); 522 try sess.exit(1); 523 } 524 525 test "parseGitCommand rejects malformed input" { 526 const allocator = std.testing.allocator; 527 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 528 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 529 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 530 } 531 532 test "parseGitCommand happy paths" { 533 const allocator = std.testing.allocator; 534 535 { 536 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 537 defer parsed.deinit(allocator); 538 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 539 try std.testing.expectEqualStrings("some-repo", parsed.dir); 540 } 541 { 542 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 543 defer parsed.deinit(allocator); 544 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 545 try std.testing.expectEqualStrings("user/proj", parsed.dir); 546 } 547 { 548 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 549 defer parsed.deinit(allocator); 550 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 551 try std.testing.expectEqualStrings("repo", parsed.dir); 552 } 553 } 554