╭ serve_http.zig ───────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const serve_common = @import("./serve_common.zig"); 5 6 pub fn runListener( 7 comptime repo_kind: rp.RepoKind, 8 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 9 io: std.Io, 10 allocator: std.mem.Allocator, 11 repo_root_path: []const u8, 12 admin_repo_path: []const u8, 13 is_test: bool, 14 net_server: *std.Io.net.Server, 15 tasks: *std.Io.Group, 16 err: *std.Io.Writer, 17 ) void { 18 const Context = struct { 19 io: std.Io, 20 allocator: std.mem.Allocator, 21 repo_root_path: []const u8, 22 admin_repo_path: []const u8, 23 is_test: bool, 24 err: *std.Io.Writer, 25 }; 26 27 const handle = struct { 28 fn h(ctx: Context, stream: std.Io.net.Stream) void { 29 defer stream.close(ctx.io); 30 handleConnection(repo_kind, any_repo_opts, ctx.io, ctx.allocator, ctx.repo_root_path, ctx.admin_repo_path, ctx.is_test, stream, ctx.err) catch |request_err| { 31 serve_common.logError(ctx.err, "connection failed: {s}\n", .{@errorName(request_err)}); 32 }; 33 } 34 }.h; 35 36 serve_common.runListener(io, net_server, tasks, err, "http", Context{ 37 .io = io, 38 .allocator = allocator, 39 .repo_root_path = repo_root_path, 40 .admin_repo_path = admin_repo_path, 41 .is_test = is_test, 42 .err = err, 43 }, handle); 44 } 45 46 fn handleConnection( 47 comptime repo_kind: rp.RepoKind, 48 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 49 io: std.Io, 50 allocator: std.mem.Allocator, 51 repo_root_path: []const u8, 52 admin_repo_path: []const u8, 53 is_test: bool, 54 stream: std.Io.net.Stream, 55 err: *std.Io.Writer, 56 ) !void { 57 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 58 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 59 var conn_br = stream.reader(io, &recv_buffer); 60 var conn_bw = stream.writer(io, &send_buffer); 61 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 62 63 while (http_server.reader.state == .ready) { 64 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 65 error.HttpConnectionClosing => break, 66 error.ReadFailed => break, 67 else => |e| return e, 68 }; 69 70 handleGitRequest(repo_kind, any_repo_opts, io, allocator, repo_root_path, admin_repo_path, is_test, &http_server, &request) catch |request_err| { 71 try err.print("request failed: {s}\n", .{@errorName(request_err)}); 72 try err.flush(); 73 if (http_server.reader.state == .received_head) { 74 http_server.reader.state = .ready; 75 } 76 try writeSimpleResponse(&http_server, 500, "Internal Server Error", "text/plain", @errorName(request_err)); 77 }; 78 try http_server.out.flush(); 79 break; 80 } 81 } 82 83 fn handleGitRequest( 84 comptime repo_kind: rp.RepoKind, 85 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 86 io: std.Io, 87 allocator: std.mem.Allocator, 88 repo_root_path: []const u8, 89 admin_repo_path: []const u8, 90 is_test: bool, 91 http_server: *std.http.Server, 92 request: *std.http.Server.Request, 93 ) !void { 94 const uri = try std.Uri.parseAfterScheme("", request.head.target); 95 const path = uri.path.percent_encoded; 96 if (path.len == 0 or path[0] != '/') { 97 try writeSimpleResponse(http_server, 400, "Bad Request", "text/plain", "bad path"); 98 return; 99 } 100 101 const handler, const suffix = findRoute(path) orelse { 102 if (http_server.reader.state == .received_head) { 103 http_server.reader.state = .ready; 104 } 105 try writeSimpleResponse(http_server, 404, "Not Found", "text/plain", "not found"); 106 return; 107 }; 108 109 const repo_rel_encoded = path[1 .. path.len - suffix.len]; 110 const repo_rel = try decodeAndValidateRepoPath(allocator, repo_rel_encoded); 111 defer allocator.free(repo_rel); 112 113 const request_method = normalizeMethod(request.head.method); 114 const content_type = try allocator.dupe(u8, findHeader(request, "content-type") orelse ""); 115 defer allocator.free(content_type); 116 const has_remote_user = findHeader(request, "authorization") != null; 117 const protocol_version = protocolVersionFromHeader(findHeader(request, "git-protocol")); 118 119 const body = if (request.head.method == .POST) blk: { 120 const reader = try request.readerExpectContinue(&.{}); 121 break :blk try reader.allocRemaining(allocator, .unlimited); 122 } else try allocator.dupe(u8, ""); 123 defer allocator.free(body); 124 125 if (http_server.reader.state == .received_head) { 126 http_server.reader.state = .ready; 127 } 128 129 const create_if_missing = isReceivePack(handler, suffix, uri.query); 130 131 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, is_test, repo_root_path, admin_repo_path, repo_rel, create_if_missing)) { 132 .ok => |p| p, 133 .invalid => return writeSimpleResponse(http_server, 400, "Bad Request", "text/plain", "repo path must be <owner>/<repo>"), 134 .not_found => return error.RepoNotFound, 135 }; 136 defer allocator.free(repo_path); 137 138 var body_reader = std.Io.Reader.fixed(body); 139 const http_backend_options = xit.net_server_http_backend.Options{ 140 .request_method = request_method, 141 .handler = handler, 142 .suffix = suffix, 143 .query_string = if (uri.query) |q| q.percent_encoded else "", 144 .content_type = content_type, 145 .has_remote_user = has_remote_user, 146 .protocol_version = protocol_version, 147 }; 148 149 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, create_if_missing, GitService{ 150 .body_reader = &body_reader, 151 .writer = http_server.out, 152 .options = http_backend_options, 153 }); 154 } 155 156 fn findRoute(path: []const u8) ?struct { xit.net_server_http_backend.HandlerKind, []const u8 } { 157 for (&xit.net_server_http_backend.routes) |*route| { 158 if (std.mem.endsWith(u8, path, route.suffix)) { 159 return .{ route.handler, route.suffix }; 160 } 161 } 162 return null; 163 } 164 165 fn openRepoAndServe( 166 comptime repo_kind: rp.RepoKind, 167 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 168 io: std.Io, 169 allocator: std.mem.Allocator, 170 repo_path: []const u8, 171 create_if_missing: bool, 172 service: anytype, 173 ) !void { 174 // serve the existing on-disk repo at its event-id directory 175 if (try serveIfExists(repo_kind, any_repo_opts, io, allocator, repo_path, service)) return; 176 if (!create_if_missing) return error.RepoNotFound; 177 178 // create the on-disk repo for the just-minted event and serve the push 179 if (any_repo_opts.hash) |hash_kind| { 180 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), io, allocator, repo_path, true); 181 defer repo.deinit(io, allocator); 182 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 183 } else { 184 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOpts(), io, allocator, repo_path, true); 185 defer repo.deinit(io, allocator); 186 try service.serve(repo_kind, any_repo_opts.toRepoOpts(), &repo, io, allocator); 187 } 188 } 189 190 // serve an existing repo at `repo_path`, or return false if none is there 191 fn serveIfExists( 192 comptime repo_kind: rp.RepoKind, 193 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 194 io: std.Io, 195 allocator: std.mem.Allocator, 196 repo_path: []const u8, 197 service: anytype, 198 ) !bool { 199 // a bare open() creates the directory while probing for the repo, so only 200 // attempt it when the path already exists 201 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 202 203 if (any_repo_opts.hash) |hash_kind| { 204 var repo = rp.Repo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind)).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 205 error.RepoNotFound => return false, 206 else => |e| return e, 207 }; 208 defer repo.deinit(io, allocator); 209 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 210 } else { 211 var any_repo = rp.AnyRepo(repo_kind, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 212 error.RepoNotFound => return false, 213 else => |e| return e, 214 }; 215 defer any_repo.deinit(io, allocator); 216 switch (any_repo) { 217 inline else => |*repo| try service.serve(repo.self_repo_kind, repo.self_repo_opts, repo, io, allocator), 218 } 219 } 220 return true; 221 } 222 223 fn openRepo( 224 comptime repo_kind: rp.RepoKind, 225 comptime repo_opts: rp.RepoOpts(repo_kind), 226 io: std.Io, 227 allocator: std.mem.Allocator, 228 repo_path: []const u8, 229 create_if_missing: bool, 230 ) !rp.Repo(repo_kind, repo_opts) { 231 return rp.Repo(repo_kind, repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 232 error.RepoNotFound => { 233 if (!create_if_missing) return open_err; 234 235 var repo = try rp.Repo(repo_kind, repo_opts).init(io, allocator, .{ .path = repo_path }); 236 errdefer repo.deinit(io, allocator); 237 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 238 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 239 return repo; 240 }, 241 else => |e| return e, 242 }; 243 } 244 245 const GitService = struct { 246 body_reader: *std.Io.Reader, 247 writer: *std.Io.Writer, 248 options: xit.net_server_http_backend.Options, 249 250 fn serve( 251 self: @This(), 252 comptime repo_kind: rp.RepoKind, 253 comptime repo_opts: rp.RepoOpts(repo_kind), 254 repo: *rp.Repo(repo_kind, repo_opts), 255 io: std.Io, 256 allocator: std.mem.Allocator, 257 ) !void { 258 try repo.httpBackend(io, allocator, self.body_reader, self.writer, .http, self.options); 259 } 260 }; 261 262 fn isReceivePack( 263 handler: xit.net_server_http_backend.HandlerKind, 264 suffix: []const u8, 265 query: ?std.Uri.Component, 266 ) bool { 267 return switch (handler) { 268 .run_service => std.mem.eql(u8, suffix, "/git-receive-pack"), 269 .get_info_refs => if (query) |q| 270 std.mem.startsWith(u8, q.percent_encoded, "service=git-receive-pack") 271 else 272 false, 273 }; 274 } 275 276 fn decodeAndValidateRepoPath(allocator: std.mem.Allocator, encoded: []const u8) ![]const u8 { 277 if (encoded.len == 0) return error.InvalidRepoPath; 278 279 const mutable = try allocator.dupe(u8, encoded); 280 errdefer allocator.free(mutable); 281 const decoded = std.Uri.percentDecodeInPlace(mutable); 282 283 var iter = std.fs.path.componentIterator(decoded); 284 while (iter.next()) |component| { 285 if (component.name.len == 0 or std.mem.eql(u8, component.name, ".") or std.mem.eql(u8, component.name, "..")) { 286 return error.InvalidRepoPath; 287 } 288 } 289 290 return try allocator.realloc(mutable, decoded.len); 291 } 292 293 fn normalizeMethod(method: std.http.Method) std.http.Method { 294 return if (method == .HEAD) .GET else method; 295 } 296 297 fn protocolVersionFromHeader(header: ?[]const u8) xit.net_server_common.ProtocolVersion { 298 const git_protocol = header orelse return .v0; 299 var version: xit.net_server_common.ProtocolVersion = .v0; 300 var iter = std.mem.splitScalar(u8, git_protocol, ':'); 301 while (iter.next()) |entry| { 302 const value = std.mem.trimStart(u8, entry, " "); 303 if (std.mem.startsWith(u8, value, "version=")) { 304 const v = value["version=".len..]; 305 if (std.mem.eql(u8, v, "2")) { 306 version = .v2; 307 } else if (std.mem.eql(u8, v, "1") and version != .v2) { 308 version = .v1; 309 } 310 } 311 } 312 return version; 313 } 314 315 fn findHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 316 var it = request.iterateHeaders(); 317 while (it.next()) |header| { 318 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; 319 } 320 return null; 321 } 322 323 fn writeSimpleResponse( 324 http_server: *std.http.Server, 325 code: u16, 326 message: []const u8, 327 content_type: []const u8, 328 body: []const u8, 329 ) !void { 330 try http_server.out.print( 331 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 332 .{ code, message, content_type, body.len, body }, 333 ); 334 } 335