╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
174 175 fn handleHttpConnection( 176 comptime repo_kind: rp.RepoKind, 177 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 178 io: std.Io, 179 allocator: std.mem.Allocator, 180 repo_root_path: []const u8, 181 stream: std.Io.net.Stream, 182 err: *std.Io.Writer, 183 ) !void { 184 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 185 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 186 var conn_br = stream.reader(io, &recv_buffer); 187 var conn_bw = stream.writer(io, &send_buffer); 188 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 189 190 while (http_server.reader.state == .ready) { 191 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 192 error.HttpConnectionClosing => break, 193 error.ReadFailed => break, 194 else => |e| return e, 195 }; 196 197 handleHttpGitRequest(repo_kind, any_repo_opts, io, allocator, repo_root_path, &http_server, &request) catch |request_err| { 198 try err.print("request failed: {s}\n", .{@errorName(request_err)}); 199 try err.flush(); 200 if (http_server.reader.state == .received_head) { 201 http_server.reader.state = .ready; 202 } 203 try writeSimpleResponse(&http_server, 500, "Internal Server Error", "text/plain", @errorName(request_err)); 204 }; 205 try http_server.out.flush(); 206 break; 207 } 208 } 209 210 fn handleHttpGitRequest( 211 comptime repo_kind: rp.RepoKind, 212 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 213 io: std.Io, 214 allocator: std.mem.Allocator, 215 repo_root_path: []const u8, 216 http_server: *std.http.Server, 217 request: *std.http.Server.Request, 218 ) !void { 219 const uri = try std.Uri.parseAfterScheme("", request.head.target); 220 const path = uri.path.percent_encoded; 221 if (path.len == 0 or path[0] != '/') { 222 try writeSimpleResponse(http_server, 400, "Bad Request", "text/plain", "bad path"); 223 return; 224 } 225 226 const handler, const suffix = findRoute(path) orelse { 227 if (http_server.reader.state == .received_head) { 228 http_server.reader.state = .ready; 229 } 230 try writeSimpleResponse(http_server, 404, "Not Found", "text/plain", "not found"); 231 return; 232 }; 233 234 const repo_rel_encoded = path[1 .. path.len - suffix.len]; 235 const repo_rel = try decodeAndValidateRepoPath(allocator, repo_rel_encoded); 236 defer allocator.free(repo_rel); 237 238 const repo_path = try std.fs.path.resolve(allocator, &.{ repo_root_path, repo_rel }); 239 defer allocator.free(repo_path); 240 241 if (!isSubPath(repo_root_path, repo_path)) { 242 if (http_server.reader.state == .received_head) { 243 http_server.reader.state = .ready; 244 } 245 try writeSimpleResponse(http_server, 403, "Forbidden", "text/plain", "forbidden"); 246 return; 247 } 248 249 const request_method = normalizeMethod(request.head.method); 250 const content_type = try allocator.dupe(u8, findHeader(request, "content-type") orelse ""); 251 defer allocator.free(content_type); 252 const has_remote_user = findHeader(request, "authorization") != null; 253 const protocol_version = protocolVersionFromHeader(findHeader(request, "git-protocol")); 254 255 const body = if (request.head.method == .POST) blk: { 256 const reader = try request.readerExpectContinue(&.{}); 257 break :blk try reader.allocRemaining(allocator, .unlimited); 258 } else try allocator.dupe(u8, ""); 259 defer allocator.free(body); 260 261 if (http_server.reader.state == .received_head) { 262 http_server.reader.state = .ready; 263 } 264 265 var body_reader = std.Io.Reader.fixed(body); 266 const create_if_missing = isReceivePack(handler, suffix, uri.query); 267 const http_backend_options = xit.net_server_http_backend.Options{ 268 .request_method = request_method, 269 .handler = handler, 270 .suffix = suffix, 271 .query_string = if (uri.query) |q| q.percent_encoded else "", 272 .content_type = content_type, 273 .has_remote_user = has_remote_user, 274 .protocol_version = protocol_version, 275 }; 276 277 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, create_if_missing, HttpGitService{ 278 .body_reader = &body_reader, 279 .writer = http_server.out, 280 .options = http_backend_options, 281 }); 282 } 283 284 fn findRoute(path: []const u8) ?struct { xit.net_server_http_backend.HandlerKind, []const u8 } { 285 for (&xit.net_server_http_backend.routes) |*route| { 286 if (std.mem.endsWith(u8, path, route.suffix)) { 287 return .{ route.handler, route.suffix }; 288 } 289 } 290 return null; 291 } 292 293 fn runSshListener( 294 io: std.Io, 295 allocator: std.mem.Allocator, 296 host_key: *const serve_ssh_protocol.HostKey, 297 session_handler: *const serve_ssh.SessionHandler, 298 net_server: *std.Io.net.Server, 299 tasks: *std.Io.Group, 300 err: *std.Io.Writer, 301 ) void { 302 const Listener = struct { 303 io: std.Io, 304 allocator: std.mem.Allocator, 305 host_key: *const serve_ssh_protocol.HostKey, 306 session_handler: *const serve_ssh.SessionHandler, 307 net_server: *std.Io.net.Server, 308 tasks: *std.Io.Group, 309 err: *std.Io.Writer, 310 311 fn run(ctx: @This()) void { 312 while (true) { 313 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 314 if (accept_err == error.Canceled) return; 315 logError(ctx.err, "ssh accept failed: {s}\n", .{@errorName(accept_err)}); 316 continue; 317 }; 318 319 const Connection = struct { 320 io: std.Io, 321 allocator: std.mem.Allocator, 322 host_key: *const serve_ssh_protocol.HostKey, 323 session_handler: *const serve_ssh.SessionHandler, 324 stream: std.Io.net.Stream, 325 err: *std.Io.Writer, 326 327 fn run(conn: @This()) void { 328 defer conn.stream.close(conn.io); 329 var recv_buf: [4096]u8 = undefined; 330 var send_buf: [4096]u8 = undefined; 331 var stream_reader = conn.stream.reader(conn.io, &recv_buf); 332 var stream_writer = conn.stream.writer(conn.io, &send_buf); 333 serve_ssh_protocol.handleConnection( 334 conn.io, 335 conn.allocator, 336 &stream_reader.interface, 337 &stream_writer.interface, 338 conn.host_key, 339 conn.session_handler, 340 ) catch |session_err| { 341 logError(conn.err, "ssh session failed: {s}\n", .{@errorName(session_err)}); 342 }; 343 } 344 }; 345 346 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 347 .io = ctx.io, 348 .allocator = ctx.allocator, 349 .host_key = ctx.host_key, 350 .session_handler = ctx.session_handler, 351 .stream = stream, 352 .err = ctx.err, 353 }}); 354 } 355 } 356 }; 357 358 tasks.async(io, Listener.run, .{Listener{ 359 .io = io, 360 .allocator = allocator, 361 .host_key = host_key, 362 .session_handler = session_handler, 363 .net_server = net_server, 364 .tasks = tasks, 365 .err = err, 366 }}); 367 } 368 369 fn openRepoAndServe( 370 comptime repo_kind: rp.RepoKind, 371 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 372 io: std.Io, 373 allocator: std.mem.Allocator, 374 repo_path: []const u8, 375 create_if_missing: bool, 376 service: anytype, 377 ) !void { 378 if (any_repo_opts.hash) |hash_kind| { 379 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), io, allocator, repo_path, create_if_missing); 380 defer repo.deinit(io, allocator); 381 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 382 } else { 383 var any_repo = rp.AnyRepo(repo_kind, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 384 error.RepoNotFound => { 385 if (!create_if_missing) return open_err; 386 387 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOpts(), io, allocator, repo_path, true); 388 defer repo.deinit(io, allocator); 389 try service.serve(repo_kind, any_repo_opts.toRepoOpts(), &repo, io, allocator); 390 return; 391 }, 392 else => |e| return e, 393 }; 394 defer any_repo.deinit(io, allocator); 395 396 switch (any_repo) { 397 inline else => |*repo| { 398 try service.serve(repo.self_repo_kind, repo.self_repo_opts, repo, io, allocator); 399 }, 400 } 401 } 402 } 403 404 fn openRepo( 405 comptime repo_kind: rp.RepoKind, 406 comptime repo_opts: rp.RepoOpts(repo_kind), 407 io: std.Io, 408 allocator: std.mem.Allocator, 409 repo_path: []const u8, 410 create_if_missing: bool, 411 ) !rp.Repo(repo_kind, repo_opts) { 412 return rp.Repo(repo_kind, repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 413 error.RepoNotFound => { 414 if (!create_if_missing) return open_err; 415 416 var repo = try rp.Repo(repo_kind, repo_opts).init(io, allocator, .{ .path = repo_path }); 417 errdefer repo.deinit(io, allocator); 418 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 419 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 420 return repo; 421 }, 422 else => |e| return e, 423 }; 424 } 425 426 const HttpGitService = struct { 427 body_reader: *std.Io.Reader, 428 writer: *std.Io.Writer, 429 options: xit.net_server_http_backend.Options, 430 431 fn serve( 432 self: @This(), 433 comptime repo_kind: rp.RepoKind, 434 comptime repo_opts: rp.RepoOpts(repo_kind), 435 repo: *rp.Repo(repo_kind, repo_opts), 436 io: std.Io, 437 allocator: std.mem.Allocator, 438 ) !void { 439 try repo.httpBackend(io, allocator, self.body_reader, self.writer, .http, self.options); 440 } 441 }; 442 443 fn isReceivePack( 444 handler: xit.net_server_http_backend.HandlerKind, 445 suffix: []const u8, 446 query: ?std.Uri.Component, 447 ) bool { 448 return switch (handler) { 449 .run_service => std.mem.eql(u8, suffix, "/git-receive-pack"), 450 .get_info_refs => if (query) |q| 451 std.mem.startsWith(u8, q.percent_encoded, "service=git-receive-pack") 452 else 453 false, 454 }; 455 } 456 457 fn parseListenAddress(value: []const u8) !ListenAddress { 458 const colon = std.mem.lastIndexOfScalar(u8, value, ':') orelse return error.InvalidListenAddress; 459 if (colon == 0 or colon + 1 >= value.len) return error.InvalidListenAddress; 460 const port = try std.fmt.parseInt(u16, value[colon + 1 ..], 10); 461 return .{ .host = value[0..colon], .port = port }; 462 } 463 464 fn decodeAndValidateRepoPath(allocator: std.mem.Allocator, encoded: []const u8) ![]const u8 { 465 if (encoded.len == 0) return error.InvalidRepoPath; 466 467 const mutable = try allocator.dupe(u8, encoded); 468 errdefer allocator.free(mutable); 469 const decoded = std.Uri.percentDecodeInPlace(mutable); 470 471 var iter = std.fs.path.componentIterator(decoded); 472 while (iter.next()) |component| { 473 if (component.name.len == 0 or std.mem.eql(u8, component.name, ".") or std.mem.eql(u8, component.name, "..")) { 474 return error.InvalidRepoPath; 475 } 476 } 477 478 return try allocator.realloc(mutable, decoded.len); 479 } 480 481 fn isSubPath(parent: []const u8, child: []const u8) bool { 482 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 483 if (!std.mem.startsWith(u8, child, parent)) return false; 484 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 485 } 486 487 fn normalizeMethod(method: std.http.Method) std.http.Method { 488 return if (method == .HEAD) .GET else method; 489 } 490 491 fn protocolVersionFromHeader(header: ?[]const u8) xit.net_server_common.ProtocolVersion { 492 const git_protocol = header orelse return .v0; 493 var version: xit.net_server_common.ProtocolVersion = .v0; 494 var iter = std.mem.splitScalar(u8, git_protocol, ':'); 495 while (iter.next()) |entry| { 496 const value = std.mem.trimStart(u8, entry, " "); 497 if (std.mem.startsWith(u8, value, "version=")) { 498 const v = value["version=".len..]; 499 if (std.mem.eql(u8, v, "2")) { 500 version = .v2; 501 } else if (std.mem.eql(u8, v, "1") and version != .v2) { 502 version = .v1; 503 } 504 } 505 } 506 return version; 507 } 508 509 fn findHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 510 var it = request.iterateHeaders(); 511 while (it.next()) |header| { 512 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; 513 } 514 return null; 515 } 516 517 fn writeSimpleResponse( 518 http_server: *std.http.Server, 519 code: u16, 520 message: []const u8, 521 content_type: []const u8, 522 body: []const u8, 523 ) !void { 524 try http_server.out.print( 525 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 526 .{ code, message, content_type, body.len, body }, 527 ); 528 } 529 530 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 531 err.print(fmt, args) catch return; 532 err.flush() catch {}; 533 } 534