╭ 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.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 .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 switch (draft) { 446 inline else => |*repo| try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }), 447 } 448 } else { 449 const target = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &admin_arena, owner_repo.owner, owner_repo.name)) orelse 450 return writeError(sess, "repo not found"); 451 if (!std.mem.eql(u8, fork_record.event.repo_id, &target.event_id)) return writeError(sess, "patch draft belongs to another repo"); 452 const target_id = std.fmt.bytesToHex(target.event_id, .lower); 453 const target_path = try std.fs.path.join(allocator, &.{ handler.repo_root_path, &target_id }); 454 defer allocator.free(target_path); 455 const author: evt.CommitAuthor = .{ .name = user.event.name, .email = user.event.email }; 456 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 457 switch (draft) { 458 inline else => |*repo| { 459 var target_repo = rp.Repo(.xit, repo.self_repo_opts).open(io, allocator, .{ .path = target_path }) catch 460 return writeError(sess, "repo not found or has the wrong hash"); 461 defer target_repo.deinit(io, allocator); 462 try push.receiveFork(repo.self_repo_opts, io, allocator, repo, &target_repo, &route.id, author, timestamp, reader, writer, handler.err, sess); 463 }, 464 } 465 } 466 } 467 468 // serve an existing repo at `repo_path`, or return false if none is there 469 fn serveIfExists( 470 repo_path: []const u8, 471 repo_root_path: []const u8, 472 reader: *std.Io.Reader, 473 writer: *std.Io.Writer, 474 io: std.Io, 475 allocator: std.mem.Allocator, 476 service: GitService, 477 protocol_version: xit.net_server_common.ProtocolVersion, 478 author: ?evt.CommitAuthor, 479 error_writer: *std.Io.Writer, 480 sess: ?*ssh.SessionCtx, 481 ) !bool { 482 // a bare open() creates the directory while probing for the repo, so only 483 // attempt it when the path already exists 484 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 485 486 var any_repo = rp.AnyRepo(.xit, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 487 error.RepoNotFound => return false, 488 else => |e| return e, 489 }; 490 defer any_repo.deinit(io, allocator); 491 492 switch (any_repo) { 493 inline else => |*repo| try servePack(repo.self_repo_opts, repo, repo_root_path, reader, writer, io, allocator, service, protocol_version, author, error_writer, sess), 494 } 495 return true; 496 } 497 498 fn createRepo( 499 comptime repo_opts: rp.RepoOpts(.xit), 500 io: std.Io, 501 allocator: std.mem.Allocator, 502 repo_path: []const u8, 503 ) !rp.Repo(.xit, repo_opts) { 504 var repo = try rp.Repo(.xit, repo_opts).init(io, allocator, .{ .path = repo_path, .bare = true }); 505 errdefer repo.deinit(io, allocator); 506 try repo.setMergeAlgorithm(io, allocator, .patch); 507 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 508 return repo; 509 } 510 511 fn servePack( 512 comptime repo_opts: rp.RepoOpts(.xit), 513 repo: *rp.Repo(.xit, repo_opts), 514 repo_root_path: []const u8, 515 reader: *std.Io.Reader, 516 writer: *std.Io.Writer, 517 io: std.Io, 518 allocator: std.mem.Allocator, 519 service: GitService, 520 protocol_version: xit.net_server_common.ProtocolVersion, 521 author: ?evt.CommitAuthor, 522 error_writer: *std.Io.Writer, 523 sess: ?*ssh.SessionCtx, 524 ) !void { 525 switch (service) { 526 .upload_pack => try repo.uploadPack(io, allocator, reader, writer, .{ .protocol_version = protocol_version }), 527 .receive_pack => try push.receivePackAndConsume(repo_opts, io, allocator, repo, reader, writer, .{ .protocol_version = protocol_version }, author, repo_root_path, error_writer, sess), 528 } 529 } 530 531 fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 532 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 533 defer tokens.deinit(); 534 535 const service_token = tokens.next() orelse return error.InvalidCommand; 536 const dir_token = tokens.next() orelse return error.InvalidCommand; 537 538 const service: GitService = 539 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 540 .upload_pack 541 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 542 .receive_pack 543 else 544 return error.UnsupportedService; 545 546 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 547 } 548 549 const RepoAuthorization = union(enum) { allowed: ?evt.CommitAuthor, denied, not_found }; 550 551 fn authorizeRepoKey( 552 io: std.Io, 553 arena: *std.heap.ArenaAllocator, 554 admin_repo_path: []const u8, 555 owner_name: []const u8, 556 repo_name: []const u8, 557 service: GitService, 558 fingerprint: *const [ssh.fingerprint_len]u8, 559 ) !RepoAuthorization { 560 const allocator = arena.child_allocator; 561 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 562 error.RepoNotFound => return .not_found, 563 else => |e| return e, 564 }; 565 defer admin.deinit(io, allocator); 566 567 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 568 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, owner_name, repo_name)) orelse { 569 if (service == .upload_pack) return .not_found; 570 const owner = (try evt.User.readByName(io, allocator, admin_repo_path, arena, owner_name)) orelse return .not_found; 571 return if (isKeyInAuthorizedKeys(owner.event.ssh_keys, fingerprint)) 572 .{ .allowed = .{ .name = owner.event.name, .email = owner.event.email } } 573 else 574 .denied; 575 }; 576 577 const min_role: evt.Repo.Role = switch (service) { 578 .upload_pack => .read, 579 .receive_pack => .write, 580 }; 581 // skip the key lookups when the base role is enough 582 if (evt.Repo.roleOf(repo.repo, null).atLeast(min_role)) return .{ .allowed = null }; 583 584 const user = (try repoUserWithKey(moment, arena, repo.repo.event, fingerprint)) orelse return .denied; 585 if (!evt.Repo.roleOf(repo.repo, user.id).atLeast(min_role)) return .denied; 586 return .{ .allowed = user.author }; 587 } 588 589 const UserWithKey = struct { 590 id: [evt.event_id_size]u8, 591 author: evt.CommitAuthor, 592 }; 593 594 // the repo's owner or collaborator holding the key, or null for anyone else 595 fn repoUserWithKey( 596 moment: evt.AdminDB.HashMap(.read_only), 597 arena: *std.heap.ArenaAllocator, 598 repo: evt.Repo, 599 fingerprint: *const [ssh.fingerprint_len]u8, 600 ) !?UserWithKey { 601 if (try userWithKey(moment, arena, repo.user_id, fingerprint)) |user| return user; 602 603 for ([_][]const u8{ repo.owner_user_ids, repo.write_user_ids, repo.read_user_ids }) |user_ids| { 604 var lines = std.mem.tokenizeScalar(u8, user_ids, '\n'); 605 while (lines.next()) |id| { 606 const user_id = try evt.parseEventId(id); 607 if (try userWithKey(moment, arena, &user_id, fingerprint)) |user| return user; 608 } 609 } 610 return null; 611 } 612 613 fn userWithKey( 614 moment: evt.AdminDB.HashMap(.read_only), 615 arena: *std.heap.ArenaAllocator, 616 user_id: []const u8, 617 fingerprint: *const [ssh.fingerprint_len]u8, 618 ) !?UserWithKey { 619 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, user_id)) orelse return null; 620 if (user.removed or !isKeyInAuthorizedKeys(user.event.ssh_keys, fingerprint)) return null; 621 return .{ 622 .id = user_id[0..evt.event_id_size].*, 623 .author = .{ .name = user.event.name, .email = user.event.email }, 624 }; 625 } 626 627 fn isKeyInAuthorizedKeys(ssh_keys: []const u8, fingerprint: *const [ssh.fingerprint_len]u8) bool { 628 var it = std.mem.splitScalar(u8, ssh_keys, '\n'); 629 while (it.next()) |line| { 630 const fp = fingerprintOfAuthorizedKey(line) orelse continue; 631 if (std.mem.eql(u8, &fp, fingerprint)) return true; 632 } 633 return false; 634 } 635 636 // the SHA256 fingerprint of one authorized_keys line, or null if the line is 637 // blank or not a parseable "<type> <base64> [comment]" entry 638 fn fingerprintOfAuthorizedKey(line: []const u8) ?[ssh.fingerprint_len]u8 { 639 var it = std.mem.tokenizeAny(u8, line, " \t\r"); 640 _ = it.next() orelse return null; // key type 641 const blob_b64 = it.next() orelse return null; 642 643 const decoder = std.base64.standard.Decoder; 644 const blob_len = decoder.calcSizeForSlice(blob_b64) catch return null; 645 var blob_buf: [4096]u8 = undefined; 646 if (blob_len > blob_buf.len) return null; 647 decoder.decode(blob_buf[0..blob_len], blob_b64) catch return null; 648 649 return ssh.formatFingerprint(blob_buf[0..blob_len]); 650 } 651 652 fn writeError(sess: *ssh.SessionCtx, comptime msg: []const u8) !void { 653 const body = "ERR haxy ssh: " ++ msg; 654 var packet: [body.len + 4]u8 = undefined; 655 const line = try std.fmt.bufPrint(&packet, "{x:0>4}{s}", .{ packet.len, body }); 656 try sess.writeBytes(line); 657 try sess.exit(1); 658 } 659 660 test "parseGitCommand rejects malformed input" { 661 const allocator = std.testing.allocator; 662 try std.testing.expectError(error.InvalidCommand, parseGitCommand(allocator, "git-upload-pack")); 663 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "ls -la")); 664 try std.testing.expectError(error.UnsupportedService, parseGitCommand(allocator, "git-fake-pack 'repo'")); 665 } 666 667 test "parseGitCommand happy paths" { 668 const allocator = std.testing.allocator; 669 670 { 671 const parsed = try parseGitCommand(allocator, "git-upload-pack 'some-repo'"); 672 defer parsed.deinit(allocator); 673 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 674 try std.testing.expectEqualStrings("some-repo", parsed.dir); 675 } 676 { 677 const parsed = try parseGitCommand(allocator, "git-receive-pack 'user/proj'"); 678 defer parsed.deinit(allocator); 679 try std.testing.expectEqual(GitService.receive_pack, parsed.service); 680 try std.testing.expectEqualStrings("user/proj", parsed.dir); 681 } 682 { 683 const parsed = try parseGitCommand(allocator, "git-upload-pack repo"); 684 defer parsed.deinit(allocator); 685 try std.testing.expectEqual(GitService.upload_pack, parsed.service); 686 try std.testing.expectEqualStrings("repo", parsed.dir); 687 } 688 } 689