╭ 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 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse 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 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 337 defer admin.deinit(io, allocator); 338 var admin_arena = std.heap.ArenaAllocator.init(allocator); 339 defer admin_arena.deinit(); 340 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 341 const fork_id = try evt.parseEventId(&route.id); 342 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 343 return writeError(sess, "patch draft not found"); 344 if (fork_record.removed) return writeError(sess, "patch draft not found"); 345 const target_repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 346 return writeError(sess, "repo not found"); 347 if (!std.mem.eql(u8, fork_record.event.repo_id, &target_repo.event_id)) return writeError(sess, "patch draft belongs to another repo"); 348 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 349 return writeError(sess, "invalid patch draft"); 350 if (user.removed) return writeError(sess, "invalid patch draft"); 351 if (builtin.mode != .Debug and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 352 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 353 354 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 355 defer allocator.free(draft_path); 356 var draft = rp.AnyRepo(.xit, .{}).open(io, allocator, .{ .path = draft_path }) catch 357 return writeError(sess, "patch draft not found"); 358 defer draft.deinit(io, allocator); 359 switch (draft) { 360 inline else => |*repo| { 361 var reader_buf: [4096]u8 = undefined; 362 var writer_buf: [4096]u8 = undefined; 363 var reader = ssh.SessionReader.init(sess, &reader_buf); 364 var writer = ssh.SessionWriter.init(sess, &writer_buf); 365 switch (parsed.service) { 366 .upload_pack => try repo.uploadPack(io, allocator, &reader.interface, &writer.interface, .{}), 367 .receive_pack => try repo.receivePack(io, allocator, &reader.interface, &writer.interface, .{}), 368 } 369 writer.interface.flush() catch {}; 370 if (parsed.service == .receive_pack) { 371 const source_oid = (try repo.readRef(io, fork.ref)) orelse return writeError(sess, "push HEAD to refs/heads/patch"); 372 try fork.recordPush(io, allocator, &admin, &route.id, route.target, &source_oid, .{ 373 .name = user.event.name, 374 .email = user.event.email, 375 }, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 376 } 377 }, 378 } 379 try sess.exit(0); 380 return; 381 } 382 383 const create_if_missing = parsed.service == .receive_pack; 384 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 385 386 // authenticate pushes: the authenticated key must be registered to the 387 // repo's owner. 388 if (create_if_missing) { 389 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 390 if (builtin.mode != .Debug and !try isKeyAuthorized(io, allocator, handler.admin_repo_path, owner_repo.owner, &sess.fingerprint)) 391 return writeError(sess, "unauthorized: this SSH key is not registered to the repo owner"); 392 } 393 394 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 395 .ok => |p| p, 396 .invalid => return writeError(sess, "repo path must be <owner>/<repo>"), 397 .not_found => return writeError(sess, "repo not found"), 398 }; 399 defer allocator.free(repo_path); 400 401 if (try serveIfExists(repo_path, sess, io, allocator, parsed.service)) { 402 try sess.exit(0); 403 return; 404 } 405 406 if (!create_if_missing) return writeError(sess, "repo not found"); 407 408 // create the on-disk repo for the just-minted event and serve the push 409 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 410 defer repo.deinit(io, allocator); 411 try servePack(repo.self_repo_opts, &repo, sess, io, allocator, parsed.service); 412 try sess.exit(0); 413 } 414 415 // serve an existing repo at `repo_path`, or return false if none is there 416 fn serveIfExists( 417 repo_path: []const u8, 418 sess: *ssh.SessionCtx, 419 io: std.Io, 420 allocator: std.mem.Allocator, 421 service: GitService, 422 ) !bool { 423 // a bare open() creates the directory while probing for the repo, so only 424 // attempt it when the path already exists 425 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 426 427 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{}; 428 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 429 error.RepoNotFound => return false, 430 else => |e| return e, 431 }; 432 defer any_repo.deinit(io, allocator); 433 434 switch (any_repo) { 435 inline else => |*repo| try servePack(repo.self_repo_opts, repo, sess, io, allocator, service), 436 } 437 return true; 438 } 439 440 fn createRepo( 441 comptime repo_opts: rp.RepoOpts(.xit), 442 io: std.Io, 443 allocator: std.mem.Allocator, 444 repo_path: []const u8, 445 ) !rp.Repo(.xit, repo_opts) { 446 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path }); 447 errdefer repo.deinit(io, allocator); 448 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 449 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 450 return repo; 451 } 452 453 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's pack 454 // functions can consume them like any other stream, then run the requested 455 // service 456 fn servePack( 457 comptime repo_opts: rp.RepoOpts(.xit), 458 repo: *rp.Repo(.xit, repo_opts), 459 sess: *ssh.SessionCtx, 460 io: std.Io, 461 allocator: std.mem.Allocator, 462 service: GitService, 463 ) !void { 464 var session_reader_buf: [4096]u8 = undefined; 465 var session_writer_buf: [4096]u8 = undefined; 466 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 467 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 468 469 switch (service) { 470 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 471 .receive_pack => try evt.receivePackAndConsume(repo_opts, io, allocator, repo, &session_reader.interface, &session_writer.interface, .{}), 472 } 473 474 // flush whatever the pack op buffered into our writer adapter 475 session_writer.interface.flush() catch {}; 476 } 477 478 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 479 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 480 defer tokens.deinit(); 481 482 const service_token = tokens.next() orelse return error.InvalidCommand; 483 const dir_token = tokens.next() orelse return error.InvalidCommand; 484 485 const service: GitService = 486 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 487 .upload_pack 488 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 489 .receive_pack 490 else 491 return error.UnsupportedService; 492 493 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 494 } 495 496 // true if `fingerprint` matches one of the named user's registered SSH keys 497 fn isKeyAuthorized( 498 io: std.Io, 499 allocator: std.mem.Allocator, 500 admin_repo_path: []const u8, 501 owner_name: []const u8, 502 fingerprint: *const [ssh.fingerprint_len]u8, 503 ) !bool { 504 var arena = std.heap.ArenaAllocator.init(allocator); 505 defer arena.deinit(); 506 507 const user = (try evt.User.readByName(io, allocator, admin_repo_path, &arena, owner_name)) orelse return false; 508 509 return isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint); 510 } 511 512 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 513 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 514 while (it.next()) |line| { 515 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 516 if (std.mem.eql(u8, &fp, fingerprint)) return true; 517 } 518 return false; 519 } 520 521 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 522 // blank or not a parseable "<type> <base64> [comment]" entry 523 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 524 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 525 _ = it.next() orelse return null; // key type 526 const blob_b64 = it.next() orelse return null; 527 528 const decoder = std.base64.standard.Decoder; 529 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 530 var blob_buf: [4096]u8 = undefined; 531 if (blob_len > blob_buf.len) return null; 532 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 533 534 return ssh.formatFingerprint(blob_buf[0..blob_len]); 535 } 536 537 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 538 const body = "ERR haxy ssh: " ++ msg; 539 var packet: [body.len + 4]u8 = undefined; 540 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 541 try sess.writeBytes(line); 542 try sess.exit(1); 543 } 544 545 test "parseGitCommand rejects malformed input" { 546 const allocator = std.testing.allocator; 547 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 548 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 549 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 550 } 551 552 test "parseGitCommand happy paths" { 553 const allocator = std.testing.allocator; 554 555 { 556 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 557 defer parsed.deinit(allocator); 558 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 559 try std.testing.expectEqualStrings("some-repo", parsed.dir); 560 } 561 { 562 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 563 defer parsed.deinit(allocator); 564 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 565 try std.testing.expectEqualStrings("user/proj", parsed.dir); 566 } 567 { 568 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 569 defer parsed.deinit(allocator); 570 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 571 try std.testing.expectEqualStrings("repo", parsed.dir); 572 } 573 } 574