╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
20 comptime repo_kind: rp.RepoKind, 21 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 22 io: std.Io, 23 allocator: std.mem.Allocator, 24 cwd_path: []const u8, 25 options: Options, 26 err: *std.Io.Writer, 27 ) !void { 28 // create the data dir 29 30 const data_dir_path = try std.fs.path.resolve(allocator, &.{ cwd_path, options.data_dir }); 31 defer allocator.free(data_dir_path); 32 33 const data_dir = try std.Io.Dir.cwd().createDirPathOpen(io, data_dir_path, .{}); 34 defer data_dir.close(io); 35 36 // create the repos dir 37 38 const repo_root_path = try std.fs.path.resolve(allocator, &.{ data_dir_path, "repos" }); 39 defer allocator.free(repo_root_path); 40 41 try std.Io.Dir.cwd().createDirPath(io, repo_root_path); 42 43 // create http listener 44 45 const http_listen_address = try parseListenAddress(options.http_listen); 46 const http_address = try std.Io.net.IpAddress.parseIp4(http_listen_address.host, http_listen_address.port); 47 var http_server = try http_address.listen(io, .{ .reuse_address = true }); 48 defer http_server.deinit(io); 49 50 try err.print("serving HTTP on {s}, repo root {s}\n", .{ options.http_listen, repo_root_path }); 51 try err.flush(); 52 53 var tasks: std.Io.Group = .init; 54 defer tasks.cancel(io); 55 56 runHttpListener(repo_kind, any_repo_opts, io, allocator, repo_root_path, &http_server, &tasks, err); 57 58 if (options.ui) { 59 runTui(io, allocator, &tasks, err); 60 } 61 62 // create ssh listener 63 64 var ssh_server: ?std.Io.net.Server = null; 65 defer if (ssh_server) |*server| server.deinit(io); 66 67 if (options.ssh_listen) |ssh_listen| { 68 const ssh_listen_address = try parseListenAddress(ssh_listen); 69 const ssh_address = try std.Io.net.IpAddress.parseIp4(ssh_listen_address.host, ssh_listen_address.port); 70 ssh_server = try ssh_address.listen(io, .{ .reuse_address = true }); 71 72 try err.print("serving SSH helper connections on {s}, repo root {s}\n", .{ ssh_listen, repo_root_path }); 73 try err.flush(); 74 75 if (ssh_server) |*server| { 76 runSshListener(repo_kind, any_repo_opts, io, allocator, repo_root_path, server, &tasks, err); 77 } 78 } 79 80 try tasks.await(io); 81 } 82 83 fn runTui( 84 io: std.Io, 85 allocator: std.mem.Allocator, 86 tasks: *std.Io.Group, 87 err: *std.Io.Writer, 88 ) void { 89 const TuiTask = struct { 90 io: std.Io, 91 allocator: std.mem.Allocator, 92 err: *std.Io.Writer, 93 94 fn run(ctx: @This()) void { 95 ui.run(ctx.io, ctx.allocator) catch |ui_err| { 96 logError(ctx.err, "ui failed: {s}\n", .{@errorName(ui_err)}); 97 }; 98 } 99 }; 100 101 tasks.async(io, TuiTask.run, .{TuiTask{ 102 .io = io, 103 .allocator = allocator, 104 .err = err, 105 }}); 106 } 107 108 fn runHttpListener( 109 comptime repo_kind: rp.RepoKind, 110 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 111 io: std.Io, 112 allocator: std.mem.Allocator, 113 repo_root_path: []const u8, 114 net_server: *std.Io.net.Server, 115 tasks: *std.Io.Group, 116 err: *std.Io.Writer, 117 ) void { 118 const Listener = struct { 119 io: std.Io, 120 allocator: std.mem.Allocator, 121 repo_root_path: []const u8, 122 net_server: *std.Io.net.Server, 123 tasks: *std.Io.Group, 124 err: *std.Io.Writer, 125 126 fn run(ctx: @This()) void { 127 while (true) { 128 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 129 logError(ctx.err, "accept failed: {s}\n", .{@errorName(accept_err)}); 130 continue; 131 }; 132 133 const Connection = struct { 134 io: std.Io, 135 allocator: std.mem.Allocator, 136 repo_root_path: []const u8, 137 stream: std.Io.net.Stream, 138 err: *std.Io.Writer, 139 140 fn run(conn: @This()) void { 141 defer conn.stream.close(conn.io); 142 handleHttpConnection(repo_kind, any_repo_opts, conn.io, conn.allocator, conn.repo_root_path, conn.stream, conn.err) catch |request_err| { 143 logError(conn.err, "connection failed: {s}\n", .{@errorName(request_err)}); 144 }; 145 } 146 }; 147 148 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 149 .io = ctx.io, 150 .allocator = ctx.allocator, 151 .repo_root_path = ctx.repo_root_path, 152 .stream = stream, 153 .err = ctx.err, 154 }}); 155 } 156 } 157 }; 158 159 tasks.async(io, Listener.run, .{Listener{ 160 .io = io, 161 .allocator = allocator, 162 .repo_root_path = repo_root_path, 163 .net_server = net_server, 164 .tasks = tasks, 165 .err = err, 166 }}); 167 } 168 169 fn handleHttpConnection( 170 comptime repo_kind: rp.RepoKind, 171 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 172 io: std.Io, 173 allocator: std.mem.Allocator, 174 repo_root_path: []const u8, 175 stream: std.Io.net.Stream, 176 err: *std.Io.Writer, 177 ) !void { 178 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 179 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 180 var conn_br = stream.reader(io, &recv_buffer); 181 var conn_bw = stream.writer(io, &send_buffer); 182 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 183 184 while (http_server.reader.state == .ready) { 185 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 186 error.HttpConnectionClosing => break, 187 error.ReadFailed => break, 188 else => |e| return e, 189 }; 190 191 handleHttpGitRequest(repo_kind, any_repo_opts, io, allocator, repo_root_path, &http_server, &request) catch |request_err| { 192 try err.print("request failed: {s}\n", .{@errorName(request_err)}); 193 try err.flush(); 194 if (http_server.reader.state == .received_head) { 195 http_server.reader.state = .ready; 196 } 197 try writeSimpleResponse(&http_server, 500, "Internal Server Error", "text/plain", @errorName(request_err)); 198 }; 199 try http_server.out.flush(); 200 break; 201 } 202 } 203 204 fn handleHttpGitRequest( 205 comptime repo_kind: rp.RepoKind, 206 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 207 io: std.Io, 208 allocator: std.mem.Allocator, 209 repo_root_path: []const u8, 210 http_server: *std.http.Server, 211 request: *std.http.Server.Request, 212 ) !void { 213 const uri = try std.Uri.parseAfterScheme("", request.head.target); 214 const path = uri.path.percent_encoded; 215 if (path.len == 0 or path[0] != '/') { 216 try writeSimpleResponse(http_server, 400, "Bad Request", "text/plain", "bad path"); 217 return; 218 } 219 220 const handler, const suffix = findRoute(path) orelse { 221 if (http_server.reader.state == .received_head) { 222 http_server.reader.state = .ready; 223 } 224 try writeSimpleResponse(http_server, 404, "Not Found", "text/plain", "not found"); 225 return; 226 }; 227 228 const repo_rel_encoded = path[1 .. path.len - suffix.len]; 229 const repo_rel = try decodeAndValidateRepoPath(allocator, repo_rel_encoded); 230 defer allocator.free(repo_rel); 231 232 const repo_path = try std.fs.path.resolve(allocator, &.{ repo_root_path, repo_rel }); 233 defer allocator.free(repo_path); 234 235 if (!isSubPath(repo_root_path, repo_path)) { 236 if (http_server.reader.state == .received_head) { 237 http_server.reader.state = .ready; 238 } 239 try writeSimpleResponse(http_server, 403, "Forbidden", "text/plain", "forbidden"); 240 return; 241 } 242 243 const request_method = normalizeMethod(request.head.method); 244 const content_type = try allocator.dupe(u8, findHeader(request, "content-type") orelse ""); 245 defer allocator.free(content_type); 246 const has_remote_user = findHeader(request, "authorization") != null; 247 const protocol_version = protocolVersionFromHeader(findHeader(request, "git-protocol")); 248 249 const body = if (request.head.method == .POST) blk: { 250 const reader = try request.readerExpectContinue(&.{}); 251 break :blk try reader.allocRemaining(allocator, .unlimited); 252 } else try allocator.dupe(u8, ""); 253 defer allocator.free(body); 254 255 if (http_server.reader.state == .received_head) { 256 http_server.reader.state = .ready; 257 } 258 259 var body_reader = std.Io.Reader.fixed(body); 260 const create_if_missing = isReceivePack(handler, suffix, uri.query); 261 const http_backend_options = xit.net_server_http_backend.Options{ 262 .request_method = request_method, 263 .handler = handler, 264 .suffix = suffix, 265 .query_string = if (uri.query) |q| q.percent_encoded else "", 266 .content_type = content_type, 267 .has_remote_user = has_remote_user, 268 .protocol_version = protocol_version, 269 }; 270 271 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, create_if_missing, HttpGitService{ 272 .body_reader = &body_reader, 273 .writer = http_server.out, 274 .options = http_backend_options, 275 }); 276 } 277 278 fn findRoute(path: []const u8) ?struct { xit.net_server_http_backend.HandlerKind, []const u8 } { 279 for (&xit.net_server_http_backend.routes) |*route| { 280 if (std.mem.endsWith(u8, path, route.suffix)) { 281 return .{ route.handler, route.suffix }; 282 } 283 } 284 return null; 285 } 286 287 const SshService = enum { 288 upload_pack, 289 receive_pack, 290 }; 291 292 const SshRequest = struct { 293 service: SshService, 294 protocol_version: xit.net_server_common.ProtocolVersion, 295 repo: []const u8, 296 297 fn deinit(self: SshRequest, allocator: std.mem.Allocator) void { 298 allocator.free(self.repo); 299 } 300 }; 301 302 fn runSshListener( 303 comptime repo_kind: rp.RepoKind, 304 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 305 io: std.Io, 306 allocator: std.mem.Allocator, 307 repo_root_path: []const u8, 308 net_server: *std.Io.net.Server, 309 tasks: *std.Io.Group, 310 err: *std.Io.Writer, 311 ) void { 312 const Listener = struct { 313 io: std.Io, 314 allocator: std.mem.Allocator, 315 repo_root_path: []const u8, 316 net_server: *std.Io.net.Server, 317 tasks: *std.Io.Group, 318 err: *std.Io.Writer, 319 320 fn run(ctx: @This()) void { 321 while (true) { 322 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 323 logError(ctx.err, "ssh accept failed: {s}\n", .{@errorName(accept_err)}); 324 continue; 325 }; 326 327 const Connection = struct { 328 io: std.Io, 329 allocator: std.mem.Allocator, 330 repo_root_path: []const u8, 331 stream: std.Io.net.Stream, 332 err: *std.Io.Writer, 333 334 fn run(conn: @This()) void { 335 defer conn.stream.close(conn.io); 336 handleSshGitConnection(repo_kind, any_repo_opts, conn.io, conn.allocator, conn.repo_root_path, conn.stream) catch |request_err| { 337 logError(conn.err, "ssh request failed: {s}\n", .{@errorName(request_err)}); 338 }; 339 } 340 }; 341 342 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 343 .io = ctx.io, 344 .allocator = ctx.allocator, 345 .repo_root_path = ctx.repo_root_path, 346 .stream = stream, 347 .err = ctx.err, 348 }}); 349 } 350 } 351 }; 352 353 tasks.async(io, Listener.run, .{Listener{ 354 .io = io, 355 .allocator = allocator, 356 .repo_root_path = repo_root_path, 357 .net_server = net_server, 358 .tasks = tasks, 359 .err = err, 360 }}); 361 } 362 363 fn handleSshGitConnection( 364 comptime repo_kind: rp.RepoKind, 365 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 366 io: std.Io, 367 allocator: std.mem.Allocator, 368 repo_root_path: []const u8, 369 stream: std.Io.net.Stream, 370 ) !void { 371 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 372 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 373 var reader = stream.reader(io, &recv_buffer); 374 var writer = stream.writer(io, &send_buffer); 375 376 const request = try readSshRequest(allocator, &reader.interface); 377 defer request.deinit(allocator); 378 379 const repo_path = try resolveSshRepoPath(allocator, repo_root_path, request.repo); 380 defer allocator.free(repo_path); 381 382 if (!isSubPath(repo_root_path, repo_path)) return error.Forbidden; 383 384 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, request.service == .receive_pack, SshGitService{ 385 .reader = &reader.interface, 386 .writer = &writer.interface, 387 .request = request, 388 }); 389 } 390 391 fn openRepoAndServe( 392 comptime repo_kind: rp.RepoKind, 393 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 394 io: std.Io, 395 allocator: std.mem.Allocator, 396 repo_path: []const u8, 397 create_if_missing: bool, 398 service: anytype, 399 ) !void { 400 if (any_repo_opts.hash) |hash_kind| { 401 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), io, allocator, repo_path, create_if_missing); 402 defer repo.deinit(io, allocator); 403 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 404 } else { 405 var any_repo = rp.AnyRepo(repo_kind, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 406 error.RepoNotFound => { 407 if (!create_if_missing) return open_err; 408 409 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOpts(), io, allocator, repo_path, true); 410 defer repo.deinit(io, allocator); 411 try service.serve(repo_kind, any_repo_opts.toRepoOpts(), &repo, io, allocator); 412 return; 413 }, 414 else => |e| return e, 415 }; 416 defer any_repo.deinit(io, allocator); 417 418 switch (any_repo) { 419 inline else => |*repo| { 420 try service.serve(repo.self_repo_kind, repo.self_repo_opts, repo, io, allocator); 421 }, 422 } 423 } 424 } 425 426 fn openRepo( 427 comptime repo_kind: rp.RepoKind, 428 comptime repo_opts: rp.RepoOpts(repo_kind), 429 io: std.Io, 430 allocator: std.mem.Allocator, 431 repo_path: []const u8, 432 create_if_missing: bool, 433 ) !rp.Repo(repo_kind, repo_opts) { 434 return rp.Repo(repo_kind, repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 435 error.RepoNotFound => { 436 if (!create_if_missing) return open_err; 437 438 var repo = try rp.Repo(repo_kind, repo_opts).init(io, allocator, .{ .path = repo_path }); 439 errdefer repo.deinit(io, allocator); 440 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 441 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 442 return repo; 443 }, 444 else => |e| return e, 445 }; 446 } 447 448 const HttpGitService = struct { 449 body_reader: *std.Io.Reader, 450 writer: *std.Io.Writer, 451 options: xit.net_server_http_backend.Options, 452 453 fn serve( 454 self: @This(), 455 comptime repo_kind: rp.RepoKind, 456 comptime repo_opts: rp.RepoOpts(repo_kind), 457 repo: *rp.Repo(repo_kind, repo_opts), 458 io: std.Io, 459 allocator: std.mem.Allocator, 460 ) !void { 461 try repo.httpBackend(io, allocator, self.body_reader, self.writer, .http, self.options); 462 } 463 }; 464 465 const SshGitService = struct { 466 reader: *std.Io.Reader, 467 writer: *std.Io.Writer, 468 request: SshRequest, 469 470 fn serve( 471 self: @This(), 472 comptime repo_kind: rp.RepoKind, 473 comptime repo_opts: rp.RepoOpts(repo_kind), 474 repo: *rp.Repo(repo_kind, repo_opts), 475 io: std.Io, 476 allocator: std.mem.Allocator, 477 ) !void { 478 switch (self.request.service) { 479 .upload_pack => try repo.uploadPack(io, allocator, self.reader, self.writer, .{ 480 .protocol_version = self.request.protocol_version, 481 }), 482 .receive_pack => try repo.receivePack(io, allocator, self.reader, self.writer, .{ 483 .protocol_version = self.request.protocol_version, 484 }), 485 } 486 } 487 }; 488 489 fn isReceivePack( 490 handler: xit.net_server_http_backend.HandlerKind, 491 suffix: []const u8, 492 query: ?std.Uri.Component, 493 ) bool { 494 return switch (handler) { 495 .run_service => std.mem.eql(u8, suffix, "/git-receive-pack"), 496 .get_info_refs => if (query) |q| 497 std.mem.startsWith(u8, q.percent_encoded, "service=git-receive-pack") 498 else 499 false, 500 }; 501 } 502 503 fn readSshRequest(allocator: std.mem.Allocator, reader: *std.Io.Reader) !SshRequest { 504 const magic = try readSshPreludeLine(reader); 505 if (!std.mem.eql(u8, magic, "haxy-ssh-helper-v1")) return error.InvalidSshMagic; 506 507 const service_line = try readSshPreludeLine(reader); 508 const service = parseSshService(stripPrefix(service_line, "service=") orelse return error.InvalidSshServiceLine) orelse return error.InvalidSshService; 509 510 const protocol_line = try readSshPreludeLine(reader); 511 const protocol_version = std.meta.stringToEnum( 512 xit.net_server_common.ProtocolVersion, 513 stripPrefix(protocol_line, "protocol=") orelse return error.InvalidSshProtocolLine, 514 ) orelse return error.InvalidSshProtocol; 515 516 const repo_length_line = try readSshPreludeLine(reader); 517 const repo_len = try std.fmt.parseInt(usize, stripPrefix(repo_length_line, "repo-length=") orelse return error.InvalidSshRepoLengthLine, 10); 518 519 const empty_line = try readSshPreludeLine(reader); 520 if (empty_line.len != 0) return error.InvalidSshPreludeTerminator; 521 522 const repo = try reader.readAlloc(allocator, repo_len); 523 errdefer allocator.free(repo); 524 525 return .{ 526 .service = service, 527 .protocol_version = protocol_version, 528 .repo = repo, 529 }; 530 } 531 532 fn readSshPreludeLine(reader: *std.Io.Reader) ![]const u8 { 533 return (try reader.takeDelimiter('\n')) orelse error.InvalidSshHelperRequest; 534 } 535 536 fn parseSshService(value: []const u8) ?SshService { 537 if (std.mem.eql(u8, value, "upload-pack")) return .upload_pack; 538 if (std.mem.eql(u8, value, "receive-pack")) return .receive_pack; 539 return null; 540 } 541 542 fn stripPrefix(value: []const u8, prefix: []const u8) ?[]const u8 { 543 if (!std.mem.startsWith(u8, value, prefix)) return null; 544 return value[prefix.len..]; 545 } 546 547 fn resolveSshRepoPath( 548 allocator: std.mem.Allocator, 549 repo_root_path: []const u8, 550 repo: []const u8, 551 ) ![]const u8 { 552 if (std.fs.path.isAbsolute(repo)) { 553 return try std.fs.path.resolve(allocator, &.{repo}); 554 } 555 return try std.fs.path.resolve(allocator, &.{ repo_root_path, repo }); 556 } 557 558 fn parseListenAddress(value: []const u8) !ListenAddress { 559 const colon = std.mem.lastIndexOfScalar(u8, value, ':') orelse return error.InvalidListenAddress; 560 if (colon == 0 or colon + 1 >= value.len) return error.InvalidListenAddress; 561 const port = try std.fmt.parseInt(u16, value[colon + 1 ..], 10); 562 return .{ .host = value[0..colon], .port = port }; 563 } 564 565 fn decodeAndValidateRepoPath(allocator: std.mem.Allocator, encoded: []const u8) ![]const u8 { 566 if (encoded.len == 0) return error.InvalidRepoPath; 567 568 const mutable = try allocator.dupe(u8, encoded); 569 errdefer allocator.free(mutable); 570 const decoded = std.Uri.percentDecodeInPlace(mutable); 571 572 var iter = std.mem.splitScalar(u8, decoded, '/'); 573 while (iter.next()) |segment| { 574 if (segment.len == 0 or std.mem.eql(u8, segment, ".") or std.mem.eql(u8, segment, "..")) { 575 return error.InvalidRepoPath; 576 } 577 } 578 579 return try allocator.realloc(mutable, decoded.len); 580 } 581 582 fn isSubPath(parent: []const u8, child: []const u8) bool { 583 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 584 if (!std.mem.startsWith(u8, child, parent)) return false; 585 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 586 } 587 588 fn normalizeMethod(method: std.http.Method) std.http.Method { 589 return if (method == .HEAD) .GET else method; 590 } 591 592 fn protocolVersionFromHeader(header: ?[]const u8) xit.net_server_common.ProtocolVersion { 593 const git_protocol = header orelse return .v0; 594 var version: xit.net_server_common.ProtocolVersion = .v0; 595 var iter = std.mem.splitScalar(u8, git_protocol, ':'); 596 while (iter.next()) |entry| { 597 const value = std.mem.trimStart(u8, entry, " "); 598 if (std.mem.startsWith(u8, value, "version=")) { 599 const v = value["version=".len..]; 600 if (std.mem.eql(u8, v, "2")) { 601 version = .v2; 602 } else if (std.mem.eql(u8, v, "1") and version != .v2) { 603 version = .v1; 604 } 605 } 606 } 607 return version; 608 } 609 610 fn findHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 611 var it = request.iterateHeaders(); 612 while (it.next()) |header| { 613 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; 614 } 615 return null; 616 } 617 618 fn writeSimpleResponse( 619 http_server: *std.http.Server, 620 code: u16, 621 message: []const u8, 622 content_type: []const u8, 623 body: []const u8, 624 ) !void { 625 try http_server.out.print( 626 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 627 .{ code, message, content_type, body.len, body }, 628 ); 629 } 630 631 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 632 err.print(fmt, args) catch return; 633 err.flush() catch {}; 634 } 635