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