╭ 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 create_if_missing = isReceivePack(handler, suffix, uri.query); 120 121 // pushing over HTTP is disabled outside test mode; pushes go over SSH 122 if (create_if_missing and !is_test) { 123 if (http_server.reader.state == .received_head) { 124 http_server.reader.state = .ready; 125 } 126 try writeSimpleResponse(http_server, 403, "Forbidden", "text/plain", "push over HTTP is disabled"); 127 return; 128 } 129 130 const body = if (request.head.method == .POST) blk: { 131 const reader = try request.readerExpectContinue(&.{}); 132 break :blk try reader.allocRemaining(allocator, .unlimited); 133 } else try allocator.dupe(u8, ""); 134 defer allocator.free(body); 135 136 if (http_server.reader.state == .received_head) { 137 http_server.reader.state = .ready; 138 } 139 140 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, is_test, repo_root_path, admin_repo_path, repo_rel, create_if_missing)) { 141 .ok => |p| p, 142 .invalid => return writeSimpleResponse(http_server, 400, "Bad Request", "text/plain", "repo path must be <owner>/<repo>"), 143 .not_found => return error.RepoNotFound, 144 }; 145 defer allocator.free(repo_path); 146 147 var body_reader = std.Io.Reader.fixed(body); 148 const http_backend_options = xit.net_server_http_backend.Options{ 149 .request_method = request_method, 150 .handler = handler, 151 .suffix = suffix, 152 .query_string = if (uri.query) |q| q.percent_encoded else "", 153 .content_type = content_type, 154 .has_remote_user = has_remote_user, 155 .protocol_version = protocol_version, 156 }; 157 158 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, create_if_missing, GitService{ 159 .body_reader = &body_reader, 160 .writer = http_server.out, 161 .options = http_backend_options, 162 }); 163 } 164 165 fn findRoute(path: []const u8) ?struct { xit.net_server_http_backend.HandlerKind, []const u8 } { 166 for (&xit.net_server_http_backend.routes) |*route| { 167 if (std.mem.endsWith(u8, path, route.suffix)) { 168 return .{ route.handler, route.suffix }; 169 } 170 } 171 return null; 172 } 173 174 fn openRepoAndServe( 175 comptime repo_kind: rp.RepoKind, 176 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 177 io: std.Io, 178 allocator: std.mem.Allocator, 179 repo_path: []const u8, 180 create_if_missing: bool, 181 service: anytype, 182 ) !void { 183 // serve the existing on-disk repo at its event-id directory 184 if (try serveIfExists(repo_kind, any_repo_opts, io, allocator, repo_path, service)) return; 185 if (!create_if_missing) return error.RepoNotFound; 186 187 // create the on-disk repo for the just-minted event and serve the push 188 if (any_repo_opts.hash) |hash_kind| { 189 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), io, allocator, repo_path, true); 190 defer repo.deinit(io, allocator); 191 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 192 } else { 193 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOpts(), io, allocator, repo_path, true); 194 defer repo.deinit(io, allocator); 195 try service.serve(repo_kind, any_repo_opts.toRepoOpts(), &repo, io, allocator); 196 } 197 } 198 199 // serve an existing repo at `repo_path`, or return false if none is there 200 fn serveIfExists( 201 comptime repo_kind: rp.RepoKind, 202 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 203 io: std.Io, 204 allocator: std.mem.Allocator, 205 repo_path: []const u8, 206 service: anytype, 207 ) !bool { 208 // a bare open() creates the directory while probing for the repo, so only 209 // attempt it when the path already exists 210 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 211 212 if (any_repo_opts.hash) |hash_kind| { 213 var repo = rp.Repo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind)).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 214 error.RepoNotFound => return false, 215 else => |e| return e, 216 }; 217 defer repo.deinit(io, allocator); 218 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 219 } else { 220 var any_repo = rp.AnyRepo(repo_kind, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 221 error.RepoNotFound => return false, 222 else => |e| return e, 223 }; 224 defer any_repo.deinit(io, allocator); 225 switch (any_repo) { 226 inline else => |*repo| try service.serve(repo.self_repo_kind, repo.self_repo_opts, repo, io, allocator), 227 } 228 } 229 return true; 230 } 231 232 fn openRepo( 233 comptime repo_kind: rp.RepoKind, 234 comptime repo_opts: rp.RepoOpts(repo_kind), 235 io: std.Io, 236 allocator: std.mem.Allocator, 237 repo_path: []const u8, 238 create_if_missing: bool, 239 ) !rp.Repo(repo_kind, repo_opts) { 240 return rp.Repo(repo_kind, repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 241 error.RepoNotFound => { 242 if (!create_if_missing) return open_err; 243 244 var repo = try rp.Repo(repo_kind, repo_opts).init(io, allocator, .{ .path = repo_path }); 245 errdefer repo.deinit(io, allocator); 246 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 247 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 248 return repo; 249 }, 250 else => |e| return e, 251 }; 252 } 253 254 const GitService = struct { 255 body_reader: *std.Io.Reader, 256 writer: *std.Io.Writer, 257 options: xit.net_server_http_backend.Options, 258 259 fn serve( 260 self: @This(), 261 comptime repo_kind: rp.RepoKind, 262 comptime repo_opts: rp.RepoOpts(repo_kind), 263 repo: *rp.Repo(repo_kind, repo_opts), 264 io: std.Io, 265 allocator: std.mem.Allocator, 266 ) !void { 267 try repo.httpBackend(io, allocator, self.body_reader, self.writer, .http, self.options); 268 } 269 }; 270 271 fn isReceivePack( 272 handler: xit.net_server_http_backend.HandlerKind, 273 suffix: []const u8, 274 query: ?std.Uri.Component, 275 ) bool { 276 return switch (handler) { 277 .run_service => std.mem.eql(u8, suffix, "/git-receive-pack"), 278 .get_info_refs => if (query) |q| 279 std.mem.startsWith(u8, q.percent_encoded, "service=git-receive-pack") 280 else 281 false, 282 }; 283 } 284 285 fn decodeAndValidateRepoPath(allocator: std.mem.Allocator, encoded: []const u8) ![]const u8 { 286 if (encoded.len == 0) return error.InvalidRepoPath; 287 288 const mutable = try allocator.dupe(u8, encoded); 289 errdefer allocator.free(mutable); 290 const decoded = std.Uri.percentDecodeInPlace(mutable); 291 292 var iter = std.fs.path.componentIterator(decoded); 293 while (iter.next()) |component| { 294 if (component.name.len == 0 or std.mem.eql(u8, component.name, ".") or std.mem.eql(u8, component.name, "..")) { 295 return error.InvalidRepoPath; 296 } 297 } 298 299 return try allocator.realloc(mutable, decoded.len); 300 } 301 302 fn normalizeMethod(method: std.http.Method) std.http.Method { 303 return if (method == .HEAD) .GET else method; 304 } 305 306 fn protocolVersionFromHeader(header: ?[]const u8) xit.net_server_common.ProtocolVersion { 307 const git_protocol = header orelse return .v0; 308 var version: xit.net_server_common.ProtocolVersion = .v0; 309 var iter = std.mem.splitScalar(u8, git_protocol, ':'); 310 while (iter.next()) |entry| { 311 const value = std.mem.trimStart(u8, entry, " "); 312 if (std.mem.startsWith(u8, value, "version=")) { 313 const v = value["version=".len..]; 314 if (std.mem.eql(u8, v, "2")) { 315 version = .v2; 316 } else if (std.mem.eql(u8, v, "1") and version != .v2) { 317 version = .v1; 318 } 319 } 320 } 321 return version; 322 } 323 324 fn findHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 325 var it = request.iterateHeaders(); 326 while (it.next()) |header| { 327 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; 328 } 329 return null; 330 } 331 332 fn writeSimpleResponse( 333 http_server: *std.http.Server, 334 code: u16, 335 message: []const u8, 336 content_type: []const u8, 337 body: []const u8, 338 ) !void { 339 try http_server.out.print( 340 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 341 .{ code, message, content_type, body.len, body }, 342 ); 343 } 344