╭ 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 = *serve_common.SidebandProgress }; 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 .undo => |target| ui.Repo.Undo.handleRequest(allocator, &ui_session, target), 295 } 296 } 297 298 try ui_session.applyAndWritePending(io, allocator, &repo); 299 300 // pick up data written by other handles so the next navigation 301 // builds its page from a current moment 302 try ui_session.reloadMoment(allocator, &repo); 303 304 // reconcile navigation: forward to a new page, or back on escape 305 try nav.sync(allocator, &ui_session); 306 307 // the quit button (on the quit tab) asks the host to tear down 308 if (ui_session.quit_requested) break :event_loop; 309 310 try nav.root.build(allocator, .{ 311 .min_size = .{ .width = null, .height = null }, 312 .max_size = .{ .width = terminal_size.width, .height = terminal_size.height }, 313 }, nav.root.getFocus()); 314 if (terminal_maybe) |*terminal| _ = try terminal.render(&nav.root); 315 } 316 } 317 318 // only a lone ESC needs a deadline; longer CSI/SS3 fragments must remain 319 // buffered until complete. a timeout leaves partial SSH packets in the reader. 320 pub fn nextTuiEvent(sess: *ssh.SessionCtx, terminal: ?*StreamTerminal) !?ssh.Event { 321 if (terminal) |t| { 322 if (t.parser.esc_len == 1) { 323 sess.conn.read_timeout = escape_timeout.toDeadline(sess.conn.io); 324 defer sess.conn.read_timeout = .none; 325 return sess.nextEvent() catch |err| switch (err) { 326 error.Timeout => { 327 try t.flushEscape(); 328 return null; 329 }, 330 else => return err, 331 }; 332 } 333 } 334 return try sess.nextEvent(); 335 } 336 337 // --------------------------------------------------------------------------- 338 // git path (exec) 339 // --------------------------------------------------------------------------- 340 341 const GitService = enum { upload_pack, receive_pack }; 342 343 const ParsedGitCommand = struct { 344 service: GitService, 345 dir: []u8, 346 347 fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 348 allocator.free(self.dir); 349 } 350 }; 351 352 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, exec: ssh.Request.Exec) !void { 353 const allocator = sess.conn.allocator; 354 const io = sess.conn.io; 355 const protocol_version = xit.net_server_common.parseProtocolVersion(exec.git_protocol); 356 357 // the repo's pack functions consume the channel like any other stream. 358 // whatever they leave buffered is flushed before the exit status goes out. 359 var reader_buf: [4096]u8 = undefined; 360 var writer_buf: [4096]u8 = undefined; 361 var reader = ssh.SessionReader.init(sess, &reader_buf); 362 var writer = ssh.SessionWriter.init(sess, &writer_buf); 363 defer writer.interface.flush() catch {}; 364 365 const parsed = parseGitCommand(allocator, exec.command) catch return writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 366 defer parsed.deinit(allocator); 367 const path = std.mem.trimStart(u8, parsed.dir, "/"); 368 const fork_prefix = "fork/"; 369 370 if (std.mem.startsWith(u8, path, fork_prefix)) { 371 return runForkSession(handler, sess, path[fork_prefix.len..], parsed.service, protocol_version, &reader.interface, &writer.interface); 372 } 373 374 const repo_prefix = "repo/"; 375 const repo_identity = if (std.mem.startsWith(u8, path, repo_prefix)) path[repo_prefix.len..] else path; 376 377 const create_if_missing = parsed.service == .receive_pack; 378 379 const owner_repo = evt.parseOwnerRepoPath(repo_identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 380 var author_arena = std.heap.ArenaAllocator.init(allocator); 381 defer author_arena.deinit(); 382 const author = switch (try authorizeRepoKey(io, &author_arena, handler.admin_repo_path, owner_repo.owner, owner_repo.name, parsed.service, &sess.fingerprint)) { 383 .allowed => |user| user, 384 .denied => return switch (parsed.service) { 385 .upload_pack => writeError(sess, "unauthorized: this SSH key cannot read this repo"), 386 .receive_pack => writeError(sess, "unauthorized: this SSH key cannot push to this repo"), 387 }, 388 .not_found => return writeError(sess, "repo not found"), 389 }; 390 391 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, handler.repo_root_path, handler.admin_repo_path, repo_identity, create_if_missing)) { 392 .ok => |p| p, 393 .invalid => unreachable, // parsed above 394 .not_found => return writeError(sess, "repo not found"), 395 }; 396 defer allocator.free(repo_path); 397 398 if (try serveIfExists(repo_path, handler.repo_root_path, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err, sess)) return; 399 400 if (!create_if_missing) return writeError(sess, "repo not found"); 401 402 // create the on-disk repo for the just-minted event and serve the push 403 var repo = try createRepo(any_repo_opts.toRepoOpts(), io, allocator, repo_path); 404 defer repo.deinit(io, allocator); 405 try servePack(repo.self_repo_opts, &repo, handler.repo_root_path, &reader.interface, &writer.interface, io, allocator, parsed.service, protocol_version, author, handler.err, sess); 406 } 407 408 // serve a patch draft: anyone may fetch it, only its author may push to it 409 fn runForkSession( 410 handler: *const SessionHandler, 411 sess: *ssh.SessionCtx, 412 fork_path: []const u8, 413 service: GitService, 414 protocol_version: xit.net_server_common.ProtocolVersion, 415 reader: *std.Io.Reader, 416 writer: *std.Io.Writer, 417 ) !void { 418 const allocator = sess.conn.allocator; 419 const io = sess.conn.io; 420 421 const route = fork.parseRoute(fork_path) orelse return writeError(sess, "invalid fork path"); 422 const owner_repo = evt.parseOwnerRepoPath(route.identity) orelse return writeError(sess, "repo path must be <owner>/<repo>"); 423 424 var admin = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = handler.admin_repo_path }); 425 defer admin.deinit(io, allocator); 426 var admin_arena = std.heap.ArenaAllocator.init(allocator); 427 defer admin_arena.deinit(); 428 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 429 const fork_id = try evt.parseEventId(&route.id); 430 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, &fork_id)) orelse 431 return writeError(sess, "patch draft not found"); 432 if (fork_record.removed) return writeError(sess, "patch draft not found"); 433 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, fork_record.event.user_id)) orelse 434 return writeError(sess, "invalid patch draft"); 435 if (user.removed) return writeError(sess, "invalid patch draft"); 436 if (service == .receive_pack and !isKeyInAuthorizedKeys(user.event.ssh_keys, &sess.fingerprint)) 437 return writeError(sess, "unauthorized: this SSH key is not registered to the patch author"); 438 439 const draft_path = try fork.forkPath(allocator, handler.repo_root_path, &route.id); 440 defer allocator.free(draft_path); 441 var draft = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = draft_path }) catch 442 return writeError(sess, "patch draft not found"); 443 defer draft.deinit(io, allocator); 444 if (service == .upload_pack) { 445 var progress = serve_common.SidebandProgress{ .writer = writer, .sess = sess }; 446 switch (draft) { 447 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &progress), 448 } 449 } else { 450 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 451 return writeError(sess, "repo not found"); 452 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 453 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 454 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 455 defer allocator.free(target_path); 456 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 457 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 458 switch (draft) { 459 inline else => |*repo| { 460 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 461 return writeError(sess, "repo not found or has the wrong hash"); 462 defer target_repo.deinit(io, allocator); 463 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, reader, writer, handler.err, sess); 464 }, 465 } 466 } 467 } 468 469 // serve an existing repo at `repo_path`, or return false if none is there 470 fn serveIfExists( 471 repo_path: []const u8, 472 repo_root_path: []const u8, 473 reader: *std.Io.Reader, 474 writer: *std.Io.Writer, 475 io: std.Io, 476 allocator: std.mem.Allocator, 477 service: GitService, 478 protocol_version: xit.net_server_common.ProtocolVersion, 479 author: ?evt.CommitAuthor, 480 error_writer: *std.Io.Writer, 481 sess: ?*ssh.SessionCtx, 482 ) !bool { 483 // a bare open() creates the directory while probing for the repo, so only 484 // attempt it when the path already exists 485 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 486 487 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 488 error.RepoNotFound => return false, 489 else => |e| return e, 490 }; 491 defer any_repo.deinit(io, allocator); 492 493 switch (any_repo) { 494 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, reader, writer, io, allocator, service, protocol_version, author, error_writer, sess), 495 } 496 return true; 497 } 498 499 fn createRepo( 500 comptime repo_opts: rp.RepoOpts(.xit), 501 io: std.Io, 502 allocator: std.mem.Allocator, 503 repo_path: []const u8, 504 ) !rp.Repo(.xit, repo_opts) { 505 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 506 errdefer repo.deinit(io, allocator); 507 try repo.setMergeAlgorithm(io, allocator, .patch); 508 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 509 return repo; 510 } 511 512 fn servePack( 513 comptime repo_opts: rp.RepoOpts(.xit), 514 repo: *rp.Repo(.xit, repo_opts), 515 repo_root_path: []const u8, 516 reader: *std.Io.Reader, 517 writer: *std.Io.Writer, 518 io: std.Io, 519 allocator: std.mem.Allocator, 520 service: GitService, 521 protocol_version: xit.net_server_common.ProtocolVersion, 522 author: ?evt.CommitAuthor, 523 error_writer: *std.Io.Writer, 524 sess: ?*ssh.SessionCtx, 525 ) !void { 526 switch (service) { 527 .upload_pack => { 528 var progress = serve_common.SidebandProgress{ .writer = writer, .sess = sess }; 529 try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }, &progress); 530 }, 531 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, reader, writer, .{ .protocol_version = protocol_version }, author, repo_root_path, error_writer, sess), 532 } 533 } 534 535 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 536 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 537 defer tokens.deinit(); 538 539 const service_token = tokens.next() orelse return error.InvalidCommand; 540 const dir_token = tokens.next() orelse return error.InvalidCommand; 541 542 const service: GitService = 543 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 544 .upload_pack 545 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 546 .receive_pack 547 else 548 return error.UnsupportedService; 549 550 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 551 } 552 553 const RepoAuthorization = union(enum) { allowed: ?evt.CommitAuthor, denied, not_found }; 554 555 fn authorizeRepoKey( 556 io: std.Io, 557 arena: *std.heap.ArenaAllocator, 558 admin_repo_path: []const u8, 559 owner_name: []const u8, 560 repo_name: []const u8, 561 service: GitService, 562 fingerprint: *const [ssh.fingerprint_len]u8, 563 ) !RepoAuthorization { 564 const allocator = arena.child_allocator; 565 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 566 error.RepoNotFound => return .not_found, 567 else => |e| return e, 568 }; 569 defer admin.deinit(io, allocator); 570 571 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 572 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, owner_name, repo_name)) orelse { 573 if (service == .upload_pack) return .not_found; 574 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, arena, owner_name)) orelse return .not_found; 575 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 576 .{ .allowed = .{ .name = owner.event.name, .email = owner.event.email } } 577 else 578 .denied; 579 }; 580 581 const min_role: evt.Repo.Role = switch (service) { 582 .upload_pack => .read, 583 .receive_pack => .write, 584 }; 585 // skip the key lookups when the base role is enough 586 if (evt.Repo.roleOf(repo.repo, null).atLeast(min_role)) return .{ .allowed = null }; 587 588 const user = (try repoUserWithKey(moment, arena, repo.repo.event, fingerprint)) orelse return .denied; 589 if (!evt.Repo.roleOf(repo.repo, user.id).atLeast(min_role)) return .denied; 590 return .{ .allowed = user.author }; 591 } 592 593 const UserWithKey = struct { 594 id: [evt.event_id_size]u8, 595 author: evt.CommitAuthor, 596 }; 597 598 // the repo's owner or collaborator holding the key, or null for anyone else 599 fn repoUserWithKey( 600 moment: evt.AdminDB.HashMap(.read_only), 601 arena: *std.heap.ArenaAllocator, 602 repo: evt.Repo, 603 fingerprint: *const [ssh.fingerprint_len]u8, 604 ) !?UserWithKey { 605 if (try userWithKey(moment, arena, repo.user_id, fingerprint)) |user| return user; 606 607 for ([_][]const u8{ repo.owner_user_ids, repo.write_user_ids, repo.read_user_ids }) |user_ids| { 608 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 609 while (lines.next()) |id| { 610 const user_id = try evt.parseEventId(id); 611 if (try userWithKey(moment, arena, &user_id, fingerprint)) |user| return user; 612 } 613 } 614 return null; 615 } 616 617 fn userWithKey( 618 moment: evt.AdminDB.HashMap(.read_only), 619 arena: *std.heap.ArenaAllocator, 620 user_id: []const u8, 621 fingerprint: *const [ssh.fingerprint_len]u8, 622 ) !?UserWithKey { 623 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 624 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 625 return .{ 626 .id = user_id[0..evt.event_id_size].*, 627 .author = .{ .name = user.event.name, .email = user.event.email }, 628 }; 629 } 630 631 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 632 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 633 while (it.next()) |line| { 634 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 635 if (std.mem.eql(u8, &fp, fingerprint)) return true; 636 } 637 return false; 638 } 639 640 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 641 // blank or not a parseable "<type> <base64> [comment]" entry 642 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 643 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 644 _ = it.next() orelse return null; // key type 645 const blob_b64 = it.next() orelse return null; 646 647 const decoder = std.base64.standard.Decoder; 648 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 649 var blob_buf: [4096]u8 = undefined; 650 if (blob_len > blob_buf.len) return null; 651 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 652 653 return ssh.formatFingerprint(blob_buf[0..blob_len]); 654 } 655 656 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 657 const body = "ERR haxy ssh: " ++ msg; 658 var packet: [body.len + 4]u8 = undefined; 659 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 660 try sess.writeBytes(line); 661 try sess.exit(1); 662 } 663 664 test "parseGitCommand rejects malformed input" { 665 const allocator = std.testing.allocator; 666 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 667 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 668 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 669 } 670 671 test "parseGitCommand happy paths" { 672 const allocator = std.testing.allocator; 673 674 { 675 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 676 defer parsed.deinit(allocator); 677 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 678 try std.testing.expectEqualStrings("some-repo", parsed.dir); 679 } 680 { 681 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 682 defer parsed.deinit(allocator); 683 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 684 try std.testing.expectEqualStrings("user/proj", parsed.dir); 685 } 686 { 687 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 688 defer parsed.deinit(allocator); 689 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 690 try std.testing.expectEqualStrings("repo", parsed.dir); 691 } 692 } 693