╭ serve_http.zig ───────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const evt = @import("./event.zig"); 5 const serve_common = @import("./serve_common.zig"); 6 7 pub fn runListener( 8 comptime repo_kind: rp.RepoKind, 9 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 10 io: std.Io, 11 allocator: std.mem.Allocator, 12 repo_root_path: []const u8, 13 admin_repo_path: []const u8, 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 err: *std.Io.Writer, 24 }; 25 26 const handle = struct { 27 fn h(ctx: Context, stream: std.Io.net.Stream) void { 28 defer stream.close(ctx.io); 29 handleConnection(repo_kind, any_repo_opts, ctx.io, ctx.allocator, ctx.repo_root_path, ctx.admin_repo_path, stream, ctx.err) catch |request_err| { 30 serve_common.logError(ctx.io, ctx.err, "connection failed: {s}\n", .{@errorName(request_err)}); 31 }; 32 } 33 }.h; 34 35 serve_common.runListener(io, net_server, tasks, err, "http", Context{ 36 .io = io, 37 .allocator = allocator, 38 .repo_root_path = repo_root_path, 39 .admin_repo_path = admin_repo_path, 40 .err = err, 41 }, handle); 42 } 43 44 fn handleConnection( 45 comptime repo_kind: rp.RepoKind, 46 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 47 io: std.Io, 48 allocator: std.mem.Allocator, 49 repo_root_path: []const u8, 50 admin_repo_path: []const u8, 51 stream: std.Io.net.Stream, 52 err: *std.Io.Writer, 53 ) !void { 54 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 55 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 56 var conn_br = stream.reader(io, &recv_buffer); 57 var conn_bw = stream.writer(io, &send_buffer); 58 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 59 60 if (http_server.reader.state == .ready) { 61 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 62 error.HttpConnectionClosing => return, 63 error.ReadFailed => return, 64 else => |e| return e, 65 }; 66 67 handleGitRequest(repo_kind, any_repo_opts, io, allocator, repo_root_path, admin_repo_path, &http_server, &request) catch |request_err| { 68 serve_common.logError(io, err, "request failed: {s}\n", .{@errorName(request_err)}); 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 = xit.net_server_common.parseProtocolVersion(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 owner_repo = evt.parseOwnerRepoPath(repo_rel) orelse { 123 if (http_server.reader.state == .received_head) http_server.reader.state = .ready; 124 try writeSimpleResponse(http_server, 400, "Bad Request", "text/plain", "repo path must be <owner>/<repo>"); 125 return; 126 }; 127 const repo_path = blk: { 128 var admin = rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 129 error.RepoNotFound => return error.RepoNotFound, 130 else => |e| return e, 131 }; 132 defer admin.deinit(io, allocator); 133 var arena = std.heap.ArenaAllocator.init(allocator); 134 defer arena.deinit(); 135 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin); 136 const repo = (try evt.Repo.readByOwnerAndName(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, owner_repo.owner, owner_repo.name)) orelse 137 return error.RepoNotFound; 138 if (repo.repo.event.read_access == .private) { 139 if (http_server.reader.state == .received_head) http_server.reader.state = .ready; 140 try writeSimpleResponse(http_server, 403, "Forbidden", "text/plain", "private repos cannot be fetched over HTTP"); 141 return; 142 } 143 const repo_id = std.fmt.bytesToHex(repo.event_id, .lower); 144 break :blk try std.fs.path.join(allocator, &.{ repo_root_path, &repo_id }); 145 }; 146 defer allocator.free(repo_path); 147 148 const body = if (request.head.method == .POST) blk: { 149 const reader = try request.readerExpectContinue(&.{}); 150 break :blk try reader.allocRemaining(allocator, .unlimited); 151 } else try allocator.dupe(u8, ""); 152 defer allocator.free(body); 153 154 if (http_server.reader.state == .received_head) { 155 http_server.reader.state = .ready; 156 } 157 158 var body_reader = std.Io.Reader.fixed(body); 159 const http_backend_options = xit.net_server_http_backend.Options{ 160 .request_method = request_method, 161 .handler = handler, 162 .suffix = suffix, 163 .query_string = if (uri.query) |q| q.percent_encoded else "", 164 .content_type = content_type, 165 .has_remote_user = has_remote_user, 166 .protocol_version = protocol_version, 167 }; 168 169 // serve the existing on-disk repo at its event-id directory; HTTP only 170 // handles fetch/clone, so a missing repo is simply not found 171 if (!try serveIfExists(repo_kind, any_repo_opts, io, allocator, repo_path, GitService{ 172 .body_reader = &body_reader, 173 .writer = http_server.out, 174 .options = http_backend_options, 175 })) return error.RepoNotFound; 176 } 177 178 fn findRoute(path: []const u8) ?struct { xit.net_server_http_backend.HandlerKind, []const u8 } { 179 for (&xit.net_server_http_backend.routes) |*route| { 180 if (std.mem.endsWith(u8, path, route.suffix)) { 181 return .{ route.handler, route.suffix }; 182 } 183 } 184 return null; 185 } 186 187 // serve an existing repo at `repo_path`, or return false if none is there 188 fn serveIfExists( 189 comptime repo_kind: rp.RepoKind, 190 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 191 io: std.Io, 192 allocator: std.mem.Allocator, 193 repo_path: []const u8, 194 service: anytype, 195 ) !bool { 196 // a bare open() creates the directory while probing for the repo, so only 197 // attempt it when the path already exists 198 std.Io.Dir.accessAbsolute(io, repo_path, .{}) catch return false; 199 200 if (any_repo_opts.hash) |hash_kind| { 201 var repo = rp.Repo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind)).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 202 error.RepoNotFound => return false, 203 else => |e| return e, 204 }; 205 defer repo.deinit(io, allocator); 206 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 207 } else { 208 var any_repo = rp.AnyRepo(repo_kind, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 209 error.RepoNotFound => return false, 210 else => |e| return e, 211 }; 212 defer any_repo.deinit(io, allocator); 213 switch (any_repo) { 214 inline else => |*repo| try service.serve(repo.self_repo_kind, repo.self_repo_opts, repo, io, allocator), 215 } 216 } 217 return true; 218 } 219 220 const GitService = struct { 221 body_reader: *std.Io.Reader, 222 writer: *std.Io.Writer, 223 options: xit.net_server_http_backend.Options, 224 225 fn serve( 226 self: @This(), 227 comptime repo_kind: rp.RepoKind, 228 comptime repo_opts: rp.RepoOpts(repo_kind), 229 repo: *rp.Repo(repo_kind, repo_opts), 230 io: std.Io, 231 allocator: std.mem.Allocator, 232 ) !void { 233 try repo.httpBackend(io, allocator, self.body_reader, self.writer, .http, self.options); 234 } 235 }; 236 237 fn isReceivePack( 238 handler: xit.net_server_http_backend.HandlerKind, 239 suffix: []const u8, 240 query: ?std.Uri.Component, 241 ) bool { 242 return switch (handler) { 243 .run_service => std.mem.eql(u8, suffix, "/git-receive-pack"), 244 .get_info_refs => if (query) |q| 245 std.mem.startsWith(u8, q.percent_encoded, "service=git-receive-pack") 246 else 247 false, 248 }; 249 } 250 251 fn decodeAndValidateRepoPath(allocator: std.mem.Allocator, encoded: []const u8) ![]const u8 { 252 if (encoded.len == 0) return error.InvalidRepoPath; 253 254 const mutable = try allocator.dupe(u8, encoded); 255 errdefer allocator.free(mutable); 256 const decoded = std.Uri.percentDecodeInPlace(mutable); 257 258 var iter = std.fs.path.componentIterator(decoded); 259 while (iter.next()) |component| { 260 if (component.name.len == 0 or std.mem.eql(u8, component.name, ".") or std.mem.eql(u8, component.name, "..")) { 261 return error.InvalidRepoPath; 262 } 263 } 264 265 return try allocator.realloc(mutable, decoded.len); 266 } 267 268 fn normalizeMethod(method: std.http.Method) std.http.Method { 269 return if (method == .HEAD) .GET else method; 270 } 271 272 fn findHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 273 var it = request.iterateHeaders(); 274 while (it.next()) |header| { 275 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; 276 } 277 return null; 278 } 279 280 fn writeSimpleResponse( 281 http_server: *std.http.Server, 282 code: u16, 283 message: []const u8, 284 content_type: []const u8, 285 body: []const u8, 286 ) !void { 287 try http_server.out.print( 288 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 289 .{ code, message, content_type, body.len, body }, 290 ); 291 } 292