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