╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const push = @import("push.zig"); 3 const xit = @import("xit"); 4 const rp = xit.repo; 5 const xitui = xit.xitui; 6 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 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 const fork = @import("./fork.zig"); 13 14 // listener resource limits. the watchdog gives peers a hard deadline to start 15 // a session, times out non-interactive sessions that stall while we're blocked 16 // on the peer, and bounds the post-CLOSE drain. 17 const max_connections: u32 = 4096; 18 const watchdog_interval = std.Io.Duration.fromSeconds(5); 19 const presession_timeout_ticks: u32 = 6; // 30 seconds 20 const idle_timeout_ticks: u32 = 24; // 120 seconds 21 const close_drain_timeout_ticks: u32 = 2; // 5-10 seconds 22 const escape_timeout: std.Io.Timeout = .{ .duration = .{ .raw = .fromMilliseconds(25), .clock = .awake } }; 23 24 var active_connections: std.atomic.Value(u32) = .init(0); 25 26 const any_repo_opts: rp.AnyRepoOpts(.xit) = .{ .ProgressCtx = *push.PushProgress }; 27 28 pub const SessionHandler = struct { 29 admin_repo_path: []const u8, 30 repo_root_path: []const u8, 31 wui_port: u16, // port the web UI is served on, shown in the TUI footer's url 32 git_http_port: ?u16, 33 git_ssh_port: ?u16, 34 git_ssh_prefix: []const u8, 35 err: *std.Io.Writer, 36 37 /// returning without an exit leaves the protocol layer to send status 0 38 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 39 serve_common.logError(sess.conn.io, self.err, "ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 40 switch (request) { 41 .shell => |pty_maybe| { 42 const pty = pty_maybe orelse { 43 // a shell without a pty has no useful TUI to render; in 44 // openssh client terms this is `ssh -T host`. say so and 45 // exit non-zero. 46 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 47 try sess.exit(1); 48 return; 49 }; 50 sess.exemptFromIdleTimeout(); 51 try runTuiSession(self, sess, pty); 52 }, 53 .exec => |exec| { 54 try runGitSession(self, sess, exec); 55 }, 56 } 57 } 58 }; 59 60 pub fn runListener( 61 io: std.Io, 62 allocator: std.mem.Allocator, 63 host_key: *const ssh.HostKey, 64 session_handler: *const SessionHandler, 65 watchdog: *Watchdog, 66 net_server: *std.Io.net.Server, 67 tasks: *std.Io.Group, 68 err: *std.Io.Writer, 69 ) void { 70 const Context = struct { 71 io: std.Io, 72 allocator: std.mem.Allocator, 73 host_key: *const ssh.HostKey, 74 session_handler: *const SessionHandler, 75 watchdog: *Watchdog, 76 err: *std.Io.Writer, 77 }; 78 79 const handle = struct { 80 fn h(ctx: Context, stream: std.Io.net.Stream) void { 81 defer stream.close(ctx.io); 82 83 const prev_count = active_connections.fetchAdd(1, .acq_rel); 84 defer _ = active_connections.fetchSub(1, .acq_rel); 85 if (prev_count >= max_connections) { 86 serve_common.logError(ctx.io, ctx.err, "ssh: connection limit reached, dropping\n", .{}); 87 return; 88 } 89 90 var connection = Watchdog.Connection{ .stream = &stream }; 91 ctx.watchdog.add(ctx.io, &connection); 92 defer ctx.watchdog.remove(ctx.io, &connection); 93 94 // timed peeks need room for a complete encrypted packet 95 var recv_buf: [ssh.packet_buffer_size]u8 = undefined; 96 var send_buf: [4096]u8 = undefined; 97 var stream_reader = stream.reader(ctx.io, &recv_buf); 98 var stream_writer = stream.writer(ctx.io, &send_buf); 99 ssh.handleConnection( 100 ctx.io, 101 ctx.allocator, 102 &stream_reader.interface, 103 &stream_writer.interface, 104 ctx.host_key, 105 &connection.idle_state, 106 ctx.session_handler, 107 ) catch |session_err| { 108 serve_common.logError(ctx.io, ctx.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 109 }; 110 } 111 }.h; 112 113 // without the watchdog nothing bounds a connection, so don't listen 114 tasks.concurrent(io, Watchdog.run, .{ watchdog, io }) catch |spawn_err| { 115 serve_common.logError(io, err, "ssh: watchdog spawn failed: {s}\n", .{@errorName(spawn_err)}); 116 return; 117 }; 118 119 serve_common.runListener(io, net_server, tasks, err, "ssh", Context{ 120 .io = io, 121 .allocator = allocator, 122 .host_key = host_key, 123 .session_handler = session_handler, 124 .watchdog = watchdog, 125 .err = err, 126 }, handle); 127 } 128 129 /// one task watches every connection. a connection links its entry only 130 /// while it runs, so the watchdog never sees a closed stream. 131 pub const Watchdog = struct { 132 mutex: std.Io.Mutex = .init, 133 connections: std.DoublyLinkedList = .{}, 134 135 const Connection = struct { 136 node: std.DoublyLinkedList.Node = .{}, 137 stream: *const std.Io.net.Stream, 138 idle_state: ssh.IdleState = .{}, 139 // tick state, touched only by the watchdog 140 last_seen: u64 = 0, 141 presession_ticks: u32 = 0, 142 idle_ticks: u32 = 0, 143 closing_ticks: u32 = 0, 144 145 // interactive sessions are exempt only from the idle timeout, so a 146 // stalled teardown can still be broken 147 fn timedOut(self: *Connection) bool { 148 if (self.idle_state.closing.load(.acquire)) { 149 self.closing_ticks += 1; 150 return self.closing_ticks >= close_drain_timeout_ticks; 151 } 152 if (!self.idle_state.session_started.load(.acquire)) { 153 self.presession_ticks += 1; 154 return self.presession_ticks >= presession_timeout_ticks; 155 } 156 if (self.idle_state.exempt.load(.acquire)) return false; 157 158 // our own work between packets is not the peer idling 159 const seen = self.idle_state.activity.load(.acquire); 160 defer self.last_seen = seen; 161 if (self.idle_state.waiting.load(.acquire) and seen == self.last_seen) { 162 self.idle_ticks += 1; 163 } else { 164 self.idle_ticks = 0; 165 } 166 return self.idle_ticks >= idle_timeout_ticks; 167 } 168 }; 169 170 fn add(self: *Watchdog, io: std.Io, connection: *Connection) void { 171 self.mutex.lockUncancelable(io); 172 defer self.mutex.unlock(io); 173 self.connections.append(&connection.node); 174 } 175 176 fn remove(self: *Watchdog, io: std.Io, connection: *Connection) void { 177 self.mutex.lockUncancelable(io); 178 defer self.mutex.unlock(io); 179 self.connections.remove(&connection.node); 180 } 181 182 fn run(self: *Watchdog, io: std.Io) void { 183 while (true) { 184 io.sleep(watchdog_interval, .awake) catch return; 185 self.mutex.lock(io) catch return; 186 defer self.mutex.unlock(io); 187 var node = self.connections.first; 188 while (node) |n| : (node = n.next) { 189 const connection: *Connection = @fieldParentPtr("node", n); 190 if (connection.timedOut()) connection.stream.shutdown(io, .both) catch {}; 191 } 192 } 193 } 194 }; 195 196 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 197 // runTui owns the terminal, whose deinit restores the client's screen and 198 // runs as the function unwinds — so any error it returns leaves the TUI torn 199 // down and we can surface the failure on the restored screen before exiting. 200 runTui(handler, sess, pty) catch |tui_err| { 201 const err = sess.underlyingError(tui_err); 202 serve_common.logError(sess.conn.io, handler.err, "ssh tui session failed: {s}\n", .{@errorName(err)}); 203 var buf: [256]u8 = undefined; 204 const msg = std.fmt.bufPrint(&buf, "haxy ssh: {s}\r\n", .{@errorName(err)}) catch "haxy ssh: internal error\r\n"; 205 sess.writeBytes(msg) catch {}; 206 try sess.exit(1); 207 }; 208 } 209 210 fn runTui(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 211 const allocator = sess.conn.allocator; 212 const io = sess.conn.io; 213 214 // some clients (notably scripted ssh with no local controlling tty) 215 // allocate a pty without ever sending a non-zero size. fall back to a 216 // conventional 80x24 in that case so render emits something. 217 var terminal_size = Size{ 218 .width = if (pty.width_cells == 0) 80 else pty.width_cells, 219 .height = if (pty.height_cells == 0) 24 else pty.height_cells, 220 }; 221 222 // session-lifetime allocations (login, prefs); Nav owns the per-page arenas. 223 var session_arena = std.heap.ArenaAllocator.init(allocator); 224 defer session_arena.deinit(); 225 226 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 227 var repo = try Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 228 defer repo.deinit(io, allocator); 229 var ui_session = try ui.Session.init(&session_arena, &repo, .{}); 230 ui_session.is_terminal = true; 231 ui_session.web_port = handler.wui_port; 232 ui_session.data.git_http_port = handler.git_http_port; 233 ui_session.data.git_ssh_port = handler.git_ssh_port; 234 ui_session.data.git_ssh_prefix = handler.git_ssh_prefix; 235 // let page builders open on-disk repos (sibling "repos" dir of the admin repo) 236 ui_session.io = io; 237 ui_session.repos_dir = try std.fs.path.join(session_arena.allocator(), &.{ std.fs.path.dirname(handler.admin_repo_path) orelse ".", "repos" }); 238 239 var nav = try ui.Nav.init(allocator, &ui_session); 240 defer nav.deinit(allocator); 241 242 var session_writer_buf: [8192]u8 = undefined; 243 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 244 245 // the terminal's deinit writes leave-alt / show-cursor / disable-mouse and 246 // flushes, restoring the client's screen. as a function-scoped defer it runs 247 // before runTui returns — on the normal path and on any error — so the 248 // caller can write to the client afterward (and sess.exit can close cleanly). 249 var terminal_maybe: ?StreamTerminal = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 250 defer if (terminal_maybe) |*terminal| terminal.deinit(); 251 252 // initial render — user sees the page immediately 253 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 254 255 // event loop. nextEvent blocks until something interesting arrives; 256 // for each event, rebuild the widget tree and re-render so the user 257 // sees the effect of their input on the same iteration. 258 event_loop: while (true) { 259 const event = try nextTuiEvent(sess, if (terminal_maybe) |*terminal| terminal else null); 260 if (event) |ev| switch (ev) { 261 .data => |payload| { 262 defer allocator.free(payload); 263 if (terminal_maybe) |*terminal| { 264 try terminal.writeBytes(payload); 265 } else { 266 // the copyable text stays up until enter 267 if (std.mem.indexOfAny(u8, payload, "\r\n") == null) continue; 268 terminal_maybe = try StreamTerminal.init(allocator, &session_writer.interface, terminal_size); 269 } 270 }, 271 .resize => |sz| { 272 terminal_size = .{ .width = sz.width_cells, .height = sz.height_cells }; 273 if (terminal_maybe) |*terminal| terminal.pushResize(terminal_size) else continue; 274 }, 275 .eof, .close => break :event_loop, 276 }; 277 if (terminal_maybe) |*terminal| { 278 while (terminal.popKey()) |key| { 279 try ui.inputKey(allocator, &nav.root, key, &ui_session); 280 } 281 } 282 283 if (ui_session.host_request) |request| { 284 ui_session.host_request = null; 285 switch (request) { 286 .show_copyable_text => |copyable_text| { 287 if (terminal_maybe) |*terminal| terminal.deinit(); 288 terminal_maybe = null; 289 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}); 290 try session_writer.interface.flush(); 291 continue; 292 }, 293 .sync_events => {}, 294 } 295 } 296 297 try ui_session.applyAndWritePending(io, allocator, &repo); 298 299 // pick up data written by other handles so the next navigation 300 // builds its page from a current moment 301 try ui_session.reloadMoment(allocator, &repo); 302 303 // reconcile navigation: forward to a new page, or back on escape 304 try nav.sync(allocator, &ui_session); 305 306 // the quit button (on the quit tab) asks the host to tear down 307 if (ui_session.quit_requested) break :event_loop; 308 309 try nav.root.build(allocator, .{ 310 .min_size = .{ .width = null, .height = null }, 311 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 312 }, nav.root.getFocus()); 313 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 314 } 315 } 316 317 // only a lone ESC needs a deadline; longer CSI/SS3 fragments must remain 318 // buffered until complete. a timeout leaves partial SSH packets in the reader. 319 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 320 if (terminal) |t| { 321 if (t.parser.esc_len == 1) { 322 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 323 defer sess.conn.read_timeout = .none; 324 return sess.nextEvent() catch |err| switch (err) { 325 error.Timeout => { 326 try t.flushEscape(); 327 return null; 328 }, 329 else => return err, 330 }; 331 } 332 } 333 return try sess.nextEvent(); 334 } 335 336 // --------------------------------------------------------------------------- 337 // git path (exec) 338 // --------------------------------------------------------------------------- 339 340 const GitService = enum { upload_pack, receive_pack }; 341 342 const ParsedGitCommand = struct { 343 service: GitService, 344 dir: []u8, 345 346 fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 347 allocator.free(self.dir); 348 } 349 }; 350 351 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, exec: ssh.Request.Exec) !void { 352 const allocator = sess.conn.allocator; 353 const io = sess.conn.io; 354 const protocol_version = xit.net_server_common.parseProtocolVersion(exec.git_protocol); 355 356 // the repo's pack functions consume the channel like any other stream. 357 // whatever they leave buffered is flushed before the exit status goes out. 358 var reader_buf: [4096]u8 = undefined; 359 var writer_buf: [4096]u8 = undefined; 360 var reader = ssh.SessionReader.init(sess, &reader_buf); 361 var writer = ssh.SessionWriter.init(sess, &writer_buf); 362 defer writer.interface.flush() catch {}; 363 364 const parsed = parseGitCommand(allocator, exec.command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 365 defer parsed.deinit(allocator); 366 const path = std.mem.trimStart(u8, parsed.dir, "/"); 367 const fork_prefix = "fork/"; 368 369 if (std.mem.startsWith(u8, path, fork_prefix)) { 370 return runForkSession(handler, sess, path[fork_prefix.len..], parsed.service, protocol_version, &reader.interface, &writer.interface); 371 } 372 373 const repo_prefix = "repo/"; 374 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 375 376 const create_if_missing = parsed.service == .receive_pack; 377 378 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 379 var author_arena = std.heap.ArenaAllocator.init(allocator); 380 defer author_arena.deinit(); 381 const author = switch (try authorizeRepoKey(io, &author_arena, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 382 .allowed => |user| user, 383 .denied => return switch (parsed.service) { 384 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 385 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 386 }, 387 .not_found => return writeError(sess, "repo not found"), 388 }; 389 390 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 391 .ok => |p| p, 392 .invalid => unreachable, // parsed above 393 .not_found => return writeError(sess, "repo not found"), 394 }; 395 defer allocator.free(repo_path); 396 397 if (try serveIfExists(repo_path, handler.repo_root_path, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err)) return; 398 399 if (!create_if_missing) return writeError(sess, "repo not found"); 400 401 // create the on-disk repo for the just-minted event and serve the push 402 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 403 defer repo.deinit(io, allocator); 404 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err); 405 } 406 407 // serve a patch draft: anyone may fetch it, only its author may push to it 408 fn runForkSession( 409 handler: *const SessionHandler, 410 sess: *ssh.SessionCtx, 411 fork_path: []const u8, 412 service: GitService, 413 protocol_version: xit.net_server_common.ProtocolVersion, 414 reader: *std.Io.Reader, 415 writer: *std.Io.Writer, 416 ) !void { 417 const allocator = sess.conn.allocator; 418 const io = sess.conn.io; 419 420 const route = fork.parseRoute(fork_path) orelse return writeError(sess, "invalid fork path"); 421 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 422 423 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 424 defer admin.deinit(io, allocator); 425 var admin_arena = std.heap.ArenaAllocator.init(allocator); 426 defer admin_arena.deinit(); 427 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 428 const fork_id = try evt.parseEventId(&route.id); 429 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 430 return writeError(sess, "patch draft not found"); 431 if (fork_record.removed) return writeError(sess, "patch draft not found"); 432 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 433 return writeError(sess, "invalid patch draft"); 434 if (user.removed) return writeError(sess, "invalid patch draft"); 435 if (service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 436 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 437 438 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 439 defer allocator.free(draft_path); 440 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 441 return writeError(sess, "patch draft not found"); 442 defer draft.deinit(io, allocator); 443 if (service == .upload_pack) { 444 switch (draft) { 445 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }), 446 } 447 } else { 448 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 449 return writeError(sess, "repo not found"); 450 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 451 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 452 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 453 defer allocator.free(target_path); 454 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 455 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 456 switch (draft) { 457 inline else => |*repo| { 458 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 459 return writeError(sess, "repo not found or has the wrong hash"); 460 defer target_repo.deinit(io, allocator); 461 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, reader, writer, handler.err); 462 }, 463 } 464 } 465 } 466 467 // serve an existing repo at `repo_path`, or return false if none is there 468 fn serveIfExists( 469 repo_path: []const u8, 470 repo_root_path: []const u8, 471 reader: *std.Io.Reader, 472 writer: *std.Io.Writer, 473 io: std.Io, 474 allocator: std.mem.Allocator, 475 service: GitService, 476 protocol_version: xit.net_server_common.ProtocolVersion, 477 author: ?evt.CommitAuthor, 478 error_writer: *std.Io.Writer, 479 ) !bool { 480 // a bare open() creates the directory while probing for the repo, so only 481 // attempt it when the path already exists 482 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 483 484 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 485 error.RepoNotFound => return false, 486 else => |e| return e, 487 }; 488 defer any_repo.deinit(io, allocator); 489 490 switch (any_repo) { 491 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, reader, writer, io, allocator, service, protocol_version, author, error_writer), 492 } 493 return true; 494 } 495 496 fn createRepo( 497 comptime repo_opts: rp.RepoOpts(.xit), 498 io: std.Io, 499 allocator: std.mem.Allocator, 500 repo_path: []const u8, 501 ) !rp.Repo(.xit, repo_opts) { 502 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 503 errdefer repo.deinit(io, allocator); 504 try repo.setMergeAlgorithm(io, allocator, .patch); 505 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 506 return repo; 507 } 508 509 fn servePack( 510 comptime repo_opts: rp.RepoOpts(.xit), 511 repo: *rp.Repo(.xit, repo_opts), 512 repo_root_path: []const u8, 513 reader: *std.Io.Reader, 514 writer: *std.Io.Writer, 515 io: std.Io, 516 allocator: std.mem.Allocator, 517 service: GitService, 518 protocol_version: xit.net_server_common.ProtocolVersion, 519 author: ?evt.CommitAuthor, 520 error_writer: *std.Io.Writer, 521 ) !void { 522 switch (service) { 523 .upload_pack => try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }), 524 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, reader, writer, .{ .protocol_version = protocol_version }, author, repo_root_path, error_writer), 525 } 526 } 527 528 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 529 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 530 defer tokens.deinit(); 531 532 const service_token = tokens.next() orelse return error.InvalidCommand; 533 const dir_token = tokens.next() orelse return error.InvalidCommand; 534 535 const service: GitService = 536 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 537 .upload_pack 538 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 539 .receive_pack 540 else 541 return error.UnsupportedService; 542 543 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 544 } 545 546 const RepoAuthorization = union(enum) { allowed: ?evt.CommitAuthor, denied, not_found }; 547 548 fn authorizeRepoKey( 549 io: std.Io, 550 arena: *std.heap.ArenaAllocator, 551 admin_repo_path: []const u8, 552 owner_name: []const u8, 553 repo_name: []const u8, 554 service: GitService, 555 fingerprint: *const [ssh.fingerprint_len]u8, 556 ) !RepoAuthorization { 557 const allocator = arena.child_allocator; 558 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 559 error.RepoNotFound => return .not_found, 560 else => |e| return e, 561 }; 562 defer admin.deinit(io, allocator); 563 564 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 565 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, owner_name, repo_name)) orelse { 566 if (service == .upload_pack) return .not_found; 567 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, arena, owner_name)) orelse return .not_found; 568 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 569 .{ .allowed = .{ .name = owner.event.name, .email = owner.event.email } } 570 else 571 .denied; 572 }; 573 574 const min_role: evt.Repo.Role = switch (service) { 575 .upload_pack => .read, 576 .receive_pack => .write, 577 }; 578 // skip the key lookups when the base role is enough 579 if (evt.Repo.roleOf(repo.repo, null).atLeast(min_role)) return .{ .allowed = null }; 580 581 const user = (try repoUserWithKey(moment, arena, repo.repo.event, fingerprint)) orelse return .denied; 582 if (!evt.Repo.roleOf(repo.repo, user.id).atLeast(min_role)) return .denied; 583 return .{ .allowed = user.author }; 584 } 585 586 const UserWithKey = struct { 587 id: [evt.event_id_size]u8, 588 author: evt.CommitAuthor, 589 }; 590 591 // the repo's owner or collaborator holding the key, or null for anyone else 592 fn repoUserWithKey( 593 moment: evt.AdminDB.HashMap(.read_only), 594 arena: *std.heap.ArenaAllocator, 595 repo: evt.Repo, 596 fingerprint: *const [ssh.fingerprint_len]u8, 597 ) !?UserWithKey { 598 if (try userWithKey(moment, arena, repo.user_id, fingerprint)) |user| return user; 599 600 for ([_][]const u8{ repo.write_user_ids, repo.read_user_ids }) |user_ids| { 601 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 602 while (lines.next()) |id| { 603 const user_id = try evt.parseEventId(id); 604 if (try userWithKey(moment, arena, &user_id, fingerprint)) |user| return user; 605 } 606 } 607 return null; 608 } 609 610 fn userWithKey( 611 moment: evt.AdminDB.HashMap(.read_only), 612 arena: *std.heap.ArenaAllocator, 613 user_id: []const u8, 614 fingerprint: *const [ssh.fingerprint_len]u8, 615 ) !?UserWithKey { 616 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 617 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 618 return .{ 619 .id = user_id[0..evt.event_id_size].*, 620 .author = .{ .name = user.event.name, .email = user.event.email }, 621 }; 622 } 623 624 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 625 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 626 while (it.next()) |line| { 627 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 628 if (std.mem.eql(u8, &fp, fingerprint)) return true; 629 } 630 return false; 631 } 632 633 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 634 // blank or not a parseable "<type> <base64> [comment]" entry 635 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 636 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 637 _ = it.next() orelse return null; // key type 638 const blob_b64 = it.next() orelse return null; 639 640 const decoder = std.base64.standard.Decoder; 641 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 642 var blob_buf: [4096]u8 = undefined; 643 if (blob_len > blob_buf.len) return null; 644 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 645 646 return ssh.formatFingerprint(blob_buf[0..blob_len]); 647 } 648 649 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 650 const body = "ERR haxy ssh: " ++ msg; 651 var packet: [body.len + 4]u8 = undefined; 652 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 653 try sess.writeBytes(line); 654 try sess.exit(1); 655 } 656 657 test "parseGitCommand rejects malformed input" { 658 const allocator = std.testing.allocator; 659 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 660 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 661 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 662 } 663 664 test "parseGitCommand happy paths" { 665 const allocator = std.testing.allocator; 666 667 { 668 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 669 defer parsed.deinit(allocator); 670 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 671 try std.testing.expectEqualStrings("some-repo", parsed.dir); 672 } 673 { 674 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 675 defer parsed.deinit(allocator); 676 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 677 try std.testing.expectEqualStrings("user/proj", parsed.dir); 678 } 679 { 680 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 681 defer parsed.deinit(allocator); 682 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 683 try std.testing.expectEqualStrings("repo", parsed.dir); 684 } 685 } 686