╭ serve_ssh.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 //! haxy-side dispatcher for SSH sessions served by serve_ssh_protocol. 2 //! routes shell + pty-req → StreamTerminal (TUI), exec git-upload-pack / 3 //! git-receive-pack → repo.uploadPack / repo.receivePack (git). 4 5 const std = @import("std"); 6 const xit = @import("xit"); 7 const rp = xit.repo; 8 const xitui = xit.xitui; 9 const StreamTerminal = xitui.stream_terminal.StreamTerminal; 10 const Grid = xitui.grid.Grid; 11 const Size = xitui.layout.Size; 12 const ui = @import("./ui.zig"); 13 const ssh = @import("./serve_ssh_protocol.zig"); 14 15 pub const SessionHandler = struct { 16 admin_repo_path: []const u8, 17 repo_root_path: []const u8, 18 19 pub fn handleSession(self: *const SessionHandler, sess: *ssh.SessionCtx, request: ssh.Request) !void { 20 std.debug.print("ssh session: kind={s} key={s}\n", .{ @tagName(request), sess.fingerprint }); 21 switch (request) { 22 .shell => |pty_maybe| { 23 const pty = pty_maybe orelse { 24 // a shell without a pty has no useful TUI to render; in 25 // openssh client terms this is `ssh -T host`. say so and 26 // exit non-zero. 27 try sess.writeBytes("haxy ssh: this server only serves the TUI when a pty is allocated (use a normal `ssh` invocation).\r\n"); 28 try sess.exit(1); 29 return; 30 }; 31 try runTuiSession(self, sess, pty); 32 }, 33 .exec => |command| { 34 try runGitSession(self, sess, command); 35 }, 36 } 37 } 38 }; 39 40 fn runTuiSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, pty: ssh.PtySize) !void { 41 const allocator = sess.allocator; 42 const io = sess.io; 43 44 // some clients (notably scripted ssh with no local controlling tty) 45 // allocate a pty without ever sending a non-zero size. fall back to a 46 // conventional 80x24 in that case so render emits something. 47 const effective_pty = ssh.PtySize{ 48 .width_cells = if (pty.width_cells == 0) 80 else pty.width_cells, 49 .height_cells = if (pty.height_cells == 0) 24 else pty.height_cells, 50 }; 51 52 // build the UsersAndRepos page in a session-scoped arena. same fallback 53 // pattern as web.zig — if the admin repo doesn't exist yet, render an 54 // empty page rather than refusing the connection. 55 var page_arena = std.heap.ArenaAllocator.init(allocator); 56 defer page_arena.deinit(); 57 58 const repo_opts: rp.RepoOpts(.xit) = .{}; 59 const Repo = rp.Repo(.xit, repo_opts); 60 var repo_or_err = Repo.open(io, allocator, .{ .path = handler.admin_repo_path }); 61 const page: ui.Page = if (repo_or_err) |*repo| blk: { 62 defer repo.deinit(io, allocator); 63 break :blk .{ .users_and_repos = try .init(repo_opts, &page_arena, repo) }; 64 } else |_| .{ .users_and_repos = .empty() }; 65 66 var root = try ui.initRoot(allocator, &page); 67 defer root.deinit(); 68 69 // terminal and its writer adapter live in a nested block so the deinit 70 // (which writes leave-alt / show-cursor / disable-mouse to the channel) 71 // fires BEFORE sess.exit closes the channel. otherwise the client's 72 // terminal is left in alt-screen mode after disconnect. 73 { 74 var session_writer_buf: [8192]u8 = undefined; 75 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 76 77 var terminal = try StreamTerminal.init(allocator, &session_writer.interface, .{ 78 .width = effective_pty.width_cells, 79 .height = effective_pty.height_cells, 80 }); 81 defer terminal.deinit(); 82 83 var last_size = Size{ .width = 0, .height = 0 }; 84 var last_grid = try Grid.init(allocator, last_size); 85 defer last_grid.deinit(); 86 87 // initial render — user sees the page immediately 88 try root.build(.{ 89 .min_size = .{ .width = null, .height = null }, 90 .max_size = .{ .width = last_size.width, .height = last_size.height }, 91 }, root.getFocus()); 92 _ = try terminal.render(&root, &last_grid, &last_size); 93 94 // event loop. nextEvent blocks until something interesting arrives; 95 // for each event, rebuild the widget tree and re-render so the user 96 // sees the effect of their input on the same iteration. 97 while (!terminal.shouldQuit()) { 98 const event = try sess.nextEvent(); 99 switch (event) { 100 .data => |payload| { 101 defer allocator.free(payload); 102 try terminal.writeBytes(payload); 103 while (terminal.popKey()) |key| { 104 try ui.inputKey(&root, key, &terminal); 105 } 106 }, 107 .resize => |sz| { 108 terminal.pushResize(.{ .width = sz.width_cells, .height = sz.height_cells }); 109 while (terminal.popKey()) |key| { 110 try ui.inputKey(&root, key, &terminal); 111 } 112 }, 113 .close => terminal.requestQuit(), 114 } 115 116 try root.build(.{ 117 .min_size = .{ .width = null, .height = null }, 118 .max_size = .{ .width = last_size.width, .height = last_size.height }, 119 }, root.getFocus()); 120 _ = try terminal.render(&root, &last_grid, &last_size); 121 } 122 } 123 124 try sess.exit(0); 125 } 126 127 // --------------------------------------------------------------------------- 128 // git path (exec) 129 // --------------------------------------------------------------------------- 130 131 pub const GitService = enum { upload_pack, receive_pack }; 132 133 pub const ParsedGitCommand = struct { 134 service: GitService, 135 dir: []u8, 136 137 pub fn deinit(self: ParsedGitCommand, allocator: std.mem.Allocator) void { 138 allocator.free(self.dir); 139 } 140 }; 141 142 fn runGitSession(handler: *const SessionHandler, sess: *ssh.SessionCtx, command: []const u8) !void { 143 const allocator = sess.allocator; 144 const io = sess.io; 145 146 const parsed = parseGitCommand(allocator, command) catch { 147 try writeError(sess, "unsupported command (expected git-upload-pack or git-receive-pack)"); 148 try sess.exit(1); 149 return; 150 }; 151 defer parsed.deinit(allocator); 152 153 const repo_path = try resolveRepoPath(allocator, handler.repo_root_path, parsed.dir); 154 defer allocator.free(repo_path); 155 156 if (!isSubPath(handler.repo_root_path, repo_path)) { 157 try writeError(sess, "forbidden path"); 158 try sess.exit(1); 159 return; 160 } 161 162 const repo_opts: rp.RepoOpts(.xit) = .{}; 163 const Repo = rp.Repo(.xit, repo_opts); 164 const create_if_missing = parsed.service == .receive_pack; 165 166 var repo = openOrCreate(Repo, io, allocator, repo_path, create_if_missing) catch |err| switch (err) { 167 error.RepoNotFound => { 168 try writeError(sess, "repo not found"); 169 try sess.exit(1); 170 return; 171 }, 172 else => |e| return e, 173 }; 174 defer repo.deinit(io, allocator); 175 176 // wrap the channel I/O in std.Io.Reader/Writer adapters so the repo's 177 // pack functions can consume them like any other stream. 178 var session_reader_buf: [4096]u8 = undefined; 179 var session_writer_buf: [4096]u8 = undefined; 180 var session_reader = ssh.SessionReader.init(sess, &session_reader_buf); 181 var session_writer = ssh.SessionWriter.init(sess, &session_writer_buf); 182 183 switch (parsed.service) { 184 .upload_pack => try repo.uploadPack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 185 .receive_pack => try repo.receivePack(io, allocator, &session_reader.interface, &session_writer.interface, .{}), 186 } 187 188 // flush whatever the pack op buffered into our writer adapter 189 session_writer.interface.flush() catch {}; 190 191 try sess.exit(0); 192 } 193 194 fn openOrCreate( 195 comptime Repo: type, 196 io: std.Io, 197 allocator: std.mem.Allocator, 198 repo_path: []const u8, 199 create_if_missing: bool, 200 ) !Repo { 201 return Repo.open(io, allocator, .{ .path = repo_path }) catch |err| switch (err) { 202 error.RepoNotFound => { 203 if (!create_if_missing) return err; 204 var repo = try Repo.init(io, allocator, .{ .path = repo_path }); 205 errdefer repo.deinit(io, allocator); 206 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 207 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 208 return repo; 209 }, 210 else => |e| return e, 211 }; 212 } 213 214 pub fn parseGitCommand(allocator: std.mem.Allocator, command: []const u8) !ParsedGitCommand { 215 var tokens = try std.process.Args.IteratorGeneral(.{ .single_quotes = true }).init(allocator, command); 216 defer tokens.deinit(); 217 218 const service_token = tokens.next() orelse return error.InvalidCommand; 219 const dir_token = tokens.next() orelse return error.InvalidCommand; 220 221 const service: GitService = 222 if (std.mem.eql(u8, service_token, "git-upload-pack") or std.mem.eql(u8, service_token, "upload-pack")) 223 .upload_pack 224 else if (std.mem.eql(u8, service_token, "git-receive-pack") or std.mem.eql(u8, service_token, "receive-pack")) 225 .receive_pack 226 else 227 return error.UnsupportedService; 228 229 return .{ .service = service, .dir = try allocator.dupe(u8, dir_token) }; 230 } 231 232 fn resolveRepoPath(allocator: std.mem.Allocator, repo_root_path: []const u8, dir: []const u8) ![]const u8 { 233 if (std.fs.path.isAbsolute(dir)) return try std.fs.path.resolve(allocator, &.{dir}); 234 return try std.fs.path.resolve(allocator, &.{ repo_root_path, dir }); 235 } 236 237 pub fn isSubPath(parent: []const u8, child: []const u8) bool { 238 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 239 if (!std.mem.startsWith(u8, child, parent)) return false; 240 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 241 } 242 243 fn writeError(sess: *ssh.SessionCtx, msg: []const u8) !void { 244 var buf: [256]u8 = undefined; 245 const text = try std.fmt.bufPrint(&buf, "haxy ssh: {s}\n", .{msg}); 246 try sess.writeBytes(text); 247 } 248