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