╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
205 206 const body = if (request.head.method == .POST) blk: { 207 const reader = try request.readerExpectContinue(&.{}); 208 break :blk try reader.allocRemaining(allocator, .unlimited); 209 } else try allocator.dupe(u8, ""); 210 defer allocator.free(body); 211 212 if (http_server.reader.state == .received_head) { 213 http_server.reader.state = .ready; 214 } 215 216 var body_reader = std.Io.Reader.fixed(body); 217 const create_if_missing = isReceivePack(handler, suffix, uri.query); 218 const http_backend_options = xit.net_server_http_backend.Options{ 219 .request_method = request_method, 220 .handler = handler, 221 .suffix = suffix, 222 .query_string = if (uri.query) |q| q.percent_encoded else "", 223 .content_type = content_type, 224 .has_remote_user = has_remote_user, 225 .protocol_version = protocol_version, 226 }; 227 228 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, create_if_missing, HttpGitService{ 229 .body_reader = &body_reader, 230 .writer = http_server.out, 231 .options = http_backend_options, 232 }); 233 } 234 235 fn findRoute(path: []const u8) ?struct { xit.net_server_http_backend.HandlerKind, []const u8 } { 236 for (&xit.net_server_http_backend.routes) |*route| { 237 if (std.mem.endsWith(u8, path, route.suffix)) { 238 return .{ route.handler, route.suffix }; 239 } 240 } 241 return null; 242 } 243 244 const SshService = enum { 245 upload_pack, 246 receive_pack, 247 }; 248 249 const SshRequest = struct { 250 service: SshService, 251 protocol_version: xit.net_server_common.ProtocolVersion, 252 repo: []const u8, 253 254 fn deinit(self: SshRequest, allocator: std.mem.Allocator) void { 255 allocator.free(self.repo); 256 } 257 }; 258 259 fn runSshListener( 260 comptime repo_kind: rp.RepoKind, 261 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 262 io: std.Io, 263 allocator: std.mem.Allocator, 264 repo_root: []const u8, 265 net_server: *std.Io.net.Server, 266 tasks: *std.Io.Group, 267 err: *std.Io.Writer, 268 ) void { 269 const Listener = struct { 270 io: std.Io, 271 allocator: std.mem.Allocator, 272 repo_root: []const u8, 273 net_server: *std.Io.net.Server, 274 tasks: *std.Io.Group, 275 err: *std.Io.Writer, 276 277 fn run(ctx: @This()) void { 278 while (true) { 279 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 280 logError(ctx.err, "ssh accept failed: {s}\n", .{@errorName(accept_err)}); 281 continue; 282 }; 283 284 const Connection = struct { 285 io: std.Io, 286 allocator: std.mem.Allocator, 287 repo_root: []const u8, 288 stream: std.Io.net.Stream, 289 err: *std.Io.Writer, 290 291 fn run(conn: @This()) void { 292 defer conn.stream.close(conn.io); 293 handleSshGitConnection(repo_kind, any_repo_opts, conn.io, conn.allocator, conn.repo_root, conn.stream) catch |request_err| { 294 logError(conn.err, "ssh request failed: {s}\n", .{@errorName(request_err)}); 295 }; 296 } 297 }; 298 299 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 300 .io = ctx.io, 301 .allocator = ctx.allocator, 302 .repo_root = ctx.repo_root, 303 .stream = stream, 304 .err = ctx.err, 305 }}); 306 } 307 } 308 }; 309 310 tasks.async(io, Listener.run, .{Listener{ 311 .io = io, 312 .allocator = allocator, 313 .repo_root = repo_root, 314 .net_server = net_server, 315 .tasks = tasks, 316 .err = err, 317 }}); 318 } 319 320 fn handleSshGitConnection( 321 comptime repo_kind: rp.RepoKind, 322 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 323 io: std.Io, 324 allocator: std.mem.Allocator, 325 repo_root: []const u8, 326 stream: std.Io.net.Stream, 327 ) !void { 328 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 329 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 330 var reader = stream.reader(io, &recv_buffer); 331 var writer = stream.writer(io, &send_buffer); 332 333 const request = try readSshRequest(allocator, &reader.interface); 334 defer request.deinit(allocator); 335 336 const repo_path = try resolveSshRepoPath(allocator, repo_root, request.repo); 337 defer allocator.free(repo_path); 338 339 if (!isSubPath(repo_root, repo_path)) return error.Forbidden; 340 341 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, request.service == .receive_pack, SshGitService{ 342 .reader = &reader.interface, 343 .writer = &writer.interface, 344 .request = request, 345 }); 346 } 347 348 fn openRepoAndServe( 349 comptime repo_kind: rp.RepoKind, 350 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 351 io: std.Io, 352 allocator: std.mem.Allocator, 353 repo_path: []const u8, 354 create_if_missing: bool, 355 service: anytype, 356 ) !void { 357 if (any_repo_opts.hash) |hash_kind| { 358 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), io, allocator, repo_path, create_if_missing); 359 defer repo.deinit(io, allocator); 360 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 361 } else { 362 var any_repo = rp.AnyRepo(repo_kind, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 363 error.RepoNotFound => { 364 if (!create_if_missing) return open_err; 365 366 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOpts(), io, allocator, repo_path, true); 367 defer repo.deinit(io, allocator); 368 try service.serve(repo_kind, any_repo_opts.toRepoOpts(), &repo, io, allocator); 369 return; 370 }, 371 else => |e| return e, 372 }; 373 defer any_repo.deinit(io, allocator); 374 375 switch (any_repo) { 376 inline else => |*repo| { 377 try service.serve(repo.self_repo_kind, repo.self_repo_opts, repo, io, allocator); 378 }, 379 } 380 } 381 } 382 383 fn openRepo( 384 comptime repo_kind: rp.RepoKind, 385 comptime repo_opts: rp.RepoOpts(repo_kind), 386 io: std.Io, 387 allocator: std.mem.Allocator, 388 repo_path: []const u8, 389 create_if_missing: bool, 390 ) !rp.Repo(repo_kind, repo_opts) { 391 return rp.Repo(repo_kind, repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 392 error.RepoNotFound => { 393 if (!create_if_missing) return open_err; 394 395 var repo = try rp.Repo(repo_kind, repo_opts).init(io, allocator, .{ .path = repo_path }); 396 errdefer repo.deinit(io, allocator); 397 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 398 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 399 return repo; 400 }, 401 else => |e| return e, 402 }; 403 } 404 405 const HttpGitService = struct { 406 body_reader: *std.Io.Reader, 407 writer: *std.Io.Writer, 408 options: xit.net_server_http_backend.Options, 409 410 fn serve( 411 self: @This(), 412 comptime repo_kind: rp.RepoKind, 413 comptime repo_opts: rp.RepoOpts(repo_kind), 414 repo: *rp.Repo(repo_kind, repo_opts), 415 io: std.Io, 416 allocator: std.mem.Allocator, 417 ) !void { 418 try repo.httpBackend(io, allocator, self.body_reader, self.writer, .http, self.options); 419 } 420 }; 421 422 const SshGitService = struct { 423 reader: *std.Io.Reader, 424 writer: *std.Io.Writer, 425 request: SshRequest, 426 427 fn serve( 428 self: @This(), 429 comptime repo_kind: rp.RepoKind, 430 comptime repo_opts: rp.RepoOpts(repo_kind), 431 repo: *rp.Repo(repo_kind, repo_opts), 432 io: std.Io, 433 allocator: std.mem.Allocator, 434 ) !void { 435 switch (self.request.service) { 436 .upload_pack => try repo.uploadPack(io, allocator, self.reader, self.writer, .{ 437 .protocol_version = self.request.protocol_version, 438 }), 439 .receive_pack => try repo.receivePack(io, allocator, self.reader, self.writer, .{ 440 .protocol_version = self.request.protocol_version, 441 }), 442 } 443 } 444 }; 445 446 fn isReceivePack( 447 handler: xit.net_server_http_backend.HandlerKind, 448 suffix: []const u8, 449 query: ?std.Uri.Component, 450 ) bool { 451 return switch (handler) { 452 .run_service => std.mem.eql(u8, suffix, "/git-receive-pack"), 453 .get_info_refs => if (query) |q| 454 std.mem.startsWith(u8, q.percent_encoded, "service=git-receive-pack") 455 else 456 false, 457 }; 458 } 459 460 fn readSshRequest(allocator: std.mem.Allocator, reader: *std.Io.Reader) !SshRequest { 461 const magic = try readSshPreludeLine(reader); 462 if (!std.mem.eql(u8, magic, "haxy-ssh-helper-v1")) return error.InvalidSshMagic; 463 464 const service_line = try readSshPreludeLine(reader); 465 const service = parseSshService(stripPrefix(service_line, "service=") orelse return error.InvalidSshServiceLine) orelse return error.InvalidSshService; 466 467 const protocol_line = try readSshPreludeLine(reader); 468 const protocol_version = std.meta.stringToEnum( 469 xit.net_server_common.ProtocolVersion, 470 stripPrefix(protocol_line, "protocol=") orelse return error.InvalidSshProtocolLine, 471 ) orelse return error.InvalidSshProtocol; 472 473 const repo_length_line = try readSshPreludeLine(reader); 474 const repo_len = try std.fmt.parseInt(usize, stripPrefix(repo_length_line, "repo-length=") orelse return error.InvalidSshRepoLengthLine, 10); 475 476 const empty_line = try readSshPreludeLine(reader); 477 if (empty_line.len != 0) return error.InvalidSshPreludeTerminator; 478 479 const repo = try reader.readAlloc(allocator, repo_len); 480 errdefer allocator.free(repo); 481 482 return .{ 483 .service = service, 484 .protocol_version = protocol_version, 485 .repo = repo, 486 }; 487 } 488 489 fn readSshPreludeLine(reader: *std.Io.Reader) ![]const u8 { 490 return (try reader.takeDelimiter('\n')) orelse error.InvalidSshHelperRequest; 491 } 492 493 fn parseSshService(value: []const u8) ?SshService { 494 if (std.mem.eql(u8, value, "upload-pack")) return .upload_pack; 495 if (std.mem.eql(u8, value, "receive-pack")) return .receive_pack; 496 return null; 497 } 498 499 fn stripPrefix(value: []const u8, prefix: []const u8) ?[]const u8 { 500 if (!std.mem.startsWith(u8, value, prefix)) return null; 501 return value[prefix.len..]; 502 } 503 504 fn resolveSshRepoPath( 505 allocator: std.mem.Allocator, 506 repo_root: []const u8, 507 repo: []const u8, 508 ) ![]const u8 { 509 if (std.fs.path.isAbsolute(repo)) { 510 return try std.fs.path.resolve(allocator, &.{repo}); 511 } 512 return try std.fs.path.resolve(allocator, &.{ repo_root, repo }); 513 } 514 515 fn parseListenAddress(value: []const u8) !ListenAddress { 516 const colon = std.mem.lastIndexOfScalar(u8, value, ':') orelse return error.InvalidListenAddress; 517 if (colon == 0 or colon + 1 >= value.len) return error.InvalidListenAddress; 518 const port = try std.fmt.parseInt(u16, value[colon + 1 ..], 10); 519 return .{ .host = value[0..colon], .port = port }; 520 } 521 522 fn decodeAndValidateRepoPath(allocator: std.mem.Allocator, encoded: []const u8) ![]const u8 { 523 if (encoded.len == 0) return error.InvalidRepoPath; 524 525 const mutable = try allocator.dupe(u8, encoded); 526 errdefer allocator.free(mutable); 527 const decoded = std.Uri.percentDecodeInPlace(mutable); 528 529 var iter = std.mem.splitScalar(u8, decoded, '/'); 530 while (iter.next()) |segment| { 531 if (segment.len == 0 or std.mem.eql(u8, segment, ".") or std.mem.eql(u8, segment, "..")) { 532 return error.InvalidRepoPath; 533 } 534 } 535 536 return try allocator.realloc(mutable, decoded.len); 537 } 538 539 fn isSubPath(parent: []const u8, child: []const u8) bool { 540 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 541 if (!std.mem.startsWith(u8, child, parent)) return false; 542 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 543 } 544 545 fn normalizeMethod(method: std.http.Method) std.http.Method { 546 return if (method == .HEAD) .GET else method; 547 } 548 549 fn protocolVersionFromHeader(header: ?[]const u8) xit.net_server_common.ProtocolVersion { 550 const git_protocol = header orelse return .v0; 551 var version: xit.net_server_common.ProtocolVersion = .v0; 552 var iter = std.mem.splitScalar(u8, git_protocol, ':'); 553 while (iter.next()) |entry| { 554 const value = std.mem.trimStart(u8, entry, " "); 555 if (std.mem.startsWith(u8, value, "version=")) { 556 const v = value["version=".len..]; 557 if (std.mem.eql(u8, v, "2")) { 558 version = .v2; 559 } else if (std.mem.eql(u8, v, "1") and version != .v2) { 560 version = .v1; 561 } 562 } 563 } 564 return version; 565 } 566 567 fn findHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 568 var it = request.iterateHeaders(); 569 while (it.next()) |header| { 570 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; 571 } 572 return null; 573 } 574 575 fn writeSimpleResponse( 576 http_server: *std.http.Server, 577 code: u16, 578 message: []const u8, 579 content_type: []const u8, 580 body: []const u8, 581 ) !void { 582 try http_server.out.print( 583 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 584 .{ code, message, content_type, body.len, body }, 585 ); 586 } 587 588 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 589 err.print(fmt, args) catch return; 590 err.flush() catch {}; 591 } 592