╭ serve.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 6 pub const Options = struct { 7 http_listen: []const u8, 8 ssh_listen: ?[]const u8, 9 data_dir: []const u8, 10 }; 11 12 const ListenAddress = struct { 13 host: []const u8, 14 port: u16, 15 }; 16 17 pub fn run( 18 comptime repo_kind: rp.RepoKind, 19 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 20 io: std.Io, 21 allocator: std.mem.Allocator, 22 cwd_path: []const u8, 23 options: Options, 24 err: *std.Io.Writer, 25 ) !void { 26 // create the data dir 27 28 const data_dir_path = try std.fs.path.resolve(allocator, &.{ cwd_path, options.data_dir }); 29 defer allocator.free(data_dir_path); 30 31 const data_dir = try std.Io.Dir.cwd().createDirPathOpen(io, data_dir_path, .{}); 32 defer data_dir.close(io); 33 34 // create a db file just as a test for now 35 { 36 const db_file = try data_dir.createFile(io, "db", .{ .truncate = true, .lock = .exclusive, .read = true }); 37 defer db_file.close(io); 38 39 var buffer = std.Io.Writer.Allocating.init(allocator); 40 defer buffer.deinit(); 41 42 const DB = xit.xitdb.Database(.buffered_file, u160); 43 var db = try DB.init(.{ .io = io, .file = db_file, .buffer = &buffer }); 44 45 const db_array = try DB.ArrayList(.read_write).init(db.rootCursor()); 46 try db_array.append(.{ .bytes = "this is a test" }); 47 } 48 49 // create the repos dir 50 51 const repo_root_path = try std.fs.path.resolve(allocator, &.{ data_dir_path, "repos" }); 52 defer allocator.free(repo_root_path); 53 54 try std.Io.Dir.cwd().createDirPath(io, repo_root_path); 55 56 // create http listener 57 58 const http_listen_address = try parseListenAddress(options.http_listen); 59 const http_address = try std.Io.net.IpAddress.parseIp4(http_listen_address.host, http_listen_address.port); 60 var http_server = try http_address.listen(io, .{ .reuse_address = true }); 61 defer http_server.deinit(io); 62 63 try err.print("serving HTTP on {s}, repo root {s}\n", .{ options.http_listen, repo_root_path }); 64 try err.flush(); 65 66 var tasks: std.Io.Group = .init; 67 defer tasks.cancel(io); 68 69 runHttpListener(repo_kind, any_repo_opts, io, allocator, repo_root_path, &http_server, &tasks, err); 70 71 // create ssh listener 72 73 var ssh_server: ?std.Io.net.Server = null; 74 defer if (ssh_server) |*server| server.deinit(io); 75 76 if (options.ssh_listen) |ssh_listen| { 77 const ssh_listen_address = try parseListenAddress(ssh_listen); 78 const ssh_address = try std.Io.net.IpAddress.parseIp4(ssh_listen_address.host, ssh_listen_address.port); 79 ssh_server = try ssh_address.listen(io, .{ .reuse_address = true }); 80 81 try err.print("serving SSH helper connections on {s}, repo root {s}\n", .{ ssh_listen, repo_root_path }); 82 try err.flush(); 83 84 if (ssh_server) |*server| { 85 runSshListener(repo_kind, any_repo_opts, io, allocator, repo_root_path, server, &tasks, err); 86 } 87 } 88 89 try tasks.await(io); 90 } 91 92 fn runHttpListener( 93 comptime repo_kind: rp.RepoKind, 94 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 95 io: std.Io, 96 allocator: std.mem.Allocator, 97 repo_root_path: []const u8, 98 net_server: *std.Io.net.Server, 99 tasks: *std.Io.Group, 100 err: *std.Io.Writer, 101 ) void { 102 const Listener = struct { 103 io: std.Io, 104 allocator: std.mem.Allocator, 105 repo_root_path: []const u8, 106 net_server: *std.Io.net.Server, 107 tasks: *std.Io.Group, 108 err: *std.Io.Writer, 109 110 fn run(ctx: @This()) void { 111 while (true) { 112 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 113 logError(ctx.err, "accept failed: {s}\n", .{@errorName(accept_err)}); 114 continue; 115 }; 116 117 const Connection = struct { 118 io: std.Io, 119 allocator: std.mem.Allocator, 120 repo_root_path: []const u8, 121 stream: std.Io.net.Stream, 122 err: *std.Io.Writer, 123 124 fn run(conn: @This()) void { 125 defer conn.stream.close(conn.io); 126 handleHttpConnection(repo_kind, any_repo_opts, conn.io, conn.allocator, conn.repo_root_path, conn.stream, conn.err) catch |request_err| { 127 logError(conn.err, "connection failed: {s}\n", .{@errorName(request_err)}); 128 }; 129 } 130 }; 131 132 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 133 .io = ctx.io, 134 .allocator = ctx.allocator, 135 .repo_root_path = ctx.repo_root_path, 136 .stream = stream, 137 .err = ctx.err, 138 }}); 139 } 140 } 141 }; 142 143 tasks.async(io, Listener.run, .{Listener{ 144 .io = io, 145 .allocator = allocator, 146 .repo_root_path = repo_root_path, 147 .net_server = net_server, 148 .tasks = tasks, 149 .err = err, 150 }}); 151 } 152 153 fn handleHttpConnection( 154 comptime repo_kind: rp.RepoKind, 155 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 156 io: std.Io, 157 allocator: std.mem.Allocator, 158 repo_root_path: []const u8, 159 stream: std.Io.net.Stream, 160 err: *std.Io.Writer, 161 ) !void { 162 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 163 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 164 var conn_br = stream.reader(io, &recv_buffer); 165 var conn_bw = stream.writer(io, &send_buffer); 166 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 167 168 while (http_server.reader.state == .ready) { 169 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 170 error.HttpConnectionClosing => break, 171 error.ReadFailed => break, 172 else => |e| return e, 173 }; 174 175 handleHttpGitRequest(repo_kind, any_repo_opts, io, allocator, repo_root_path, &http_server, &request) catch |request_err| { 176 try err.print("request failed: {s}\n", .{@errorName(request_err)}); 177 try err.flush(); 178 if (http_server.reader.state == .received_head) { 179 http_server.reader.state = .ready; 180 } 181 try writeSimpleResponse(&http_server, 500, "Internal Server Error", "text/plain", @errorName(request_err)); 182 }; 183 try http_server.out.flush(); 184 break; 185 } 186 } 187 188 fn handleHttpGitRequest( 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_root_path: []const u8, 194 http_server: *std.http.Server, 195 request: *std.http.Server.Request, 196 ) !void { 197 const uri = try std.Uri.parseAfterScheme("", request.head.target); 198 const path = uri.path.percent_encoded; 199 if (path.len == 0 or path[0] != '/') { 200 try writeSimpleResponse(http_server, 400, "Bad Request", "text/plain", "bad path"); 201 return; 202 } 203 204 const handler, const suffix = findRoute(path) orelse { 205 if (http_server.reader.state == .received_head) { 206 http_server.reader.state = .ready; 207 } 208 try writeSimpleResponse(http_server, 404, "Not Found", "text/plain", "not found"); 209 return; 210 }; 211 212 const repo_rel_encoded = path[1 .. path.len - suffix.len]; 213 const repo_rel = try decodeAndValidateRepoPath(allocator, repo_rel_encoded); 214 defer allocator.free(repo_rel); 215 216 const repo_path = try std.fs.path.resolve(allocator, &.{ repo_root_path, repo_rel }); 217 defer allocator.free(repo_path); 218 219 if (!isSubPath(repo_root_path, repo_path)) { 220 if (http_server.reader.state == .received_head) { 221 http_server.reader.state = .ready; 222 } 223 try writeSimpleResponse(http_server, 403, "Forbidden", "text/plain", "forbidden"); 224 return; 225 } 226 227 const request_method = normalizeMethod(request.head.method); 228 const content_type = try allocator.dupe(u8, findHeader(request, "content-type") orelse ""); 229 defer allocator.free(content_type); 230 const has_remote_user = findHeader(request, "authorization") != null; 231 const protocol_version = protocolVersionFromHeader(findHeader(request, "git-protocol")); 232 233 const body = if (request.head.method == .POST) blk: { 234 const reader = try request.readerExpectContinue(&.{}); 235 break :blk try reader.allocRemaining(allocator, .unlimited); 236 } else try allocator.dupe(u8, ""); 237 defer allocator.free(body); 238 239 if (http_server.reader.state == .received_head) { 240 http_server.reader.state = .ready; 241 } 242 243 var body_reader = std.Io.Reader.fixed(body); 244 const create_if_missing = isReceivePack(handler, suffix, uri.query); 245 const http_backend_options = xit.net_server_http_backend.Options{ 246 .request_method = request_method, 247 .handler = handler, 248 .suffix = suffix, 249 .query_string = if (uri.query) |q| q.percent_encoded else "", 250 .content_type = content_type, 251 .has_remote_user = has_remote_user, 252 .protocol_version = protocol_version, 253 }; 254 255 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, create_if_missing, HttpGitService{ 256 .body_reader = &body_reader, 257 .writer = http_server.out, 258 .options = http_backend_options, 259 }); 260 } 261 262 fn findRoute(path: []const u8) ?struct { xit.net_server_http_backend.HandlerKind, []const u8 } { 263 for (&xit.net_server_http_backend.routes) |*route| { 264 if (std.mem.endsWith(u8, path, route.suffix)) { 265 return .{ route.handler, route.suffix }; 266 } 267 } 268 return null; 269 } 270 271 const SshService = enum { 272 upload_pack, 273 receive_pack, 274 }; 275 276 const SshRequest = struct { 277 service: SshService, 278 protocol_version: xit.net_server_common.ProtocolVersion, 279 repo: []const u8, 280 281 fn deinit(self: SshRequest, allocator: std.mem.Allocator) void { 282 allocator.free(self.repo); 283 } 284 }; 285 286 fn runSshListener( 287 comptime repo_kind: rp.RepoKind, 288 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 289 io: std.Io, 290 allocator: std.mem.Allocator, 291 repo_root_path: []const u8, 292 net_server: *std.Io.net.Server, 293 tasks: *std.Io.Group, 294 err: *std.Io.Writer, 295 ) void { 296 const Listener = struct { 297 io: std.Io, 298 allocator: std.mem.Allocator, 299 repo_root_path: []const u8, 300 net_server: *std.Io.net.Server, 301 tasks: *std.Io.Group, 302 err: *std.Io.Writer, 303 304 fn run(ctx: @This()) void { 305 while (true) { 306 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 307 logError(ctx.err, "ssh accept failed: {s}\n", .{@errorName(accept_err)}); 308 continue; 309 }; 310 311 const Connection = struct { 312 io: std.Io, 313 allocator: std.mem.Allocator, 314 repo_root_path: []const u8, 315 stream: std.Io.net.Stream, 316 err: *std.Io.Writer, 317 318 fn run(conn: @This()) void { 319 defer conn.stream.close(conn.io); 320 handleSshGitConnection(repo_kind, any_repo_opts, conn.io, conn.allocator, conn.repo_root_path, conn.stream) catch |request_err| { 321 logError(conn.err, "ssh request failed: {s}\n", .{@errorName(request_err)}); 322 }; 323 } 324 }; 325 326 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 327 .io = ctx.io, 328 .allocator = ctx.allocator, 329 .repo_root_path = ctx.repo_root_path, 330 .stream = stream, 331 .err = ctx.err, 332 }}); 333 } 334 } 335 }; 336 337 tasks.async(io, Listener.run, .{Listener{ 338 .io = io, 339 .allocator = allocator, 340 .repo_root_path = repo_root_path, 341 .net_server = net_server, 342 .tasks = tasks, 343 .err = err, 344 }}); 345 } 346 347 fn handleSshGitConnection( 348 comptime repo_kind: rp.RepoKind, 349 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 350 io: std.Io, 351 allocator: std.mem.Allocator, 352 repo_root_path: []const u8, 353 stream: std.Io.net.Stream, 354 ) !void { 355 var send_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 356 var recv_buffer = [_]u8{0} ** any_repo_opts.net_buffer_size; 357 var reader = stream.reader(io, &recv_buffer); 358 var writer = stream.writer(io, &send_buffer); 359 360 const request = try readSshRequest(allocator, &reader.interface); 361 defer request.deinit(allocator); 362 363 const repo_path = try resolveSshRepoPath(allocator, repo_root_path, request.repo); 364 defer allocator.free(repo_path); 365 366 if (!isSubPath(repo_root_path, repo_path)) return error.Forbidden; 367 368 try openRepoAndServe(repo_kind, any_repo_opts, io, allocator, repo_path, request.service == .receive_pack, SshGitService{ 369 .reader = &reader.interface, 370 .writer = &writer.interface, 371 .request = request, 372 }); 373 } 374 375 fn openRepoAndServe( 376 comptime repo_kind: rp.RepoKind, 377 comptime any_repo_opts: rp.AnyRepoOpts(repo_kind), 378 io: std.Io, 379 allocator: std.mem.Allocator, 380 repo_path: []const u8, 381 create_if_missing: bool, 382 service: anytype, 383 ) !void { 384 if (any_repo_opts.hash) |hash_kind| { 385 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), io, allocator, repo_path, create_if_missing); 386 defer repo.deinit(io, allocator); 387 try service.serve(repo_kind, any_repo_opts.toRepoOptsWithHash(hash_kind), &repo, io, allocator); 388 } else { 389 var any_repo = rp.AnyRepo(repo_kind, any_repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 390 error.RepoNotFound => { 391 if (!create_if_missing) return open_err; 392 393 var repo = try openRepo(repo_kind, any_repo_opts.toRepoOpts(), io, allocator, repo_path, true); 394 defer repo.deinit(io, allocator); 395 try service.serve(repo_kind, any_repo_opts.toRepoOpts(), &repo, io, allocator); 396 return; 397 }, 398 else => |e| return e, 399 }; 400 defer any_repo.deinit(io, allocator); 401 402 switch (any_repo) { 403 inline else => |*repo| { 404 try service.serve(repo.self_repo_kind, repo.self_repo_opts, repo, io, allocator); 405 }, 406 } 407 } 408 } 409 410 fn openRepo( 411 comptime repo_kind: rp.RepoKind, 412 comptime repo_opts: rp.RepoOpts(repo_kind), 413 io: std.Io, 414 allocator: std.mem.Allocator, 415 repo_path: []const u8, 416 create_if_missing: bool, 417 ) !rp.Repo(repo_kind, repo_opts) { 418 return rp.Repo(repo_kind, repo_opts).open(io, allocator, .{ .path = repo_path }) catch |open_err| switch (open_err) { 419 error.RepoNotFound => { 420 if (!create_if_missing) return open_err; 421 422 var repo = try rp.Repo(repo_kind, repo_opts).init(io, allocator, .{ .path = repo_path }); 423 errdefer repo.deinit(io, allocator); 424 try repo.addConfig(io, allocator, .{ .name = "http.receivepack", .value = "true" }); 425 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateinstead" }); 426 return repo; 427 }, 428 else => |e| return e, 429 }; 430 } 431 432 const HttpGitService = struct { 433 body_reader: *std.Io.Reader, 434 writer: *std.Io.Writer, 435 options: xit.net_server_http_backend.Options, 436 437 fn serve( 438 self: @This(), 439 comptime repo_kind: rp.RepoKind, 440 comptime repo_opts: rp.RepoOpts(repo_kind), 441 repo: *rp.Repo(repo_kind, repo_opts), 442 io: std.Io, 443 allocator: std.mem.Allocator, 444 ) !void { 445 try repo.httpBackend(io, allocator, self.body_reader, self.writer, .http, self.options); 446 } 447 }; 448 449 const SshGitService = struct { 450 reader: *std.Io.Reader, 451 writer: *std.Io.Writer, 452 request: SshRequest, 453 454 fn serve( 455 self: @This(), 456 comptime repo_kind: rp.RepoKind, 457 comptime repo_opts: rp.RepoOpts(repo_kind), 458 repo: *rp.Repo(repo_kind, repo_opts), 459 io: std.Io, 460 allocator: std.mem.Allocator, 461 ) !void { 462 switch (self.request.service) { 463 .upload_pack => try repo.uploadPack(io, allocator, self.reader, self.writer, .{ 464 .protocol_version = self.request.protocol_version, 465 }), 466 .receive_pack => try repo.receivePack(io, allocator, self.reader, self.writer, .{ 467 .protocol_version = self.request.protocol_version, 468 }), 469 } 470 } 471 }; 472 473 fn isReceivePack( 474 handler: xit.net_server_http_backend.HandlerKind, 475 suffix: []const u8, 476 query: ?std.Uri.Component, 477 ) bool { 478 return switch (handler) { 479 .run_service => std.mem.eql(u8, suffix, "/git-receive-pack"), 480 .get_info_refs => if (query) |q| 481 std.mem.startsWith(u8, q.percent_encoded, "service=git-receive-pack") 482 else 483 false, 484 }; 485 } 486 487 fn readSshRequest(allocator: std.mem.Allocator, reader: *std.Io.Reader) !SshRequest { 488 const magic = try readSshPreludeLine(reader); 489 if (!std.mem.eql(u8, magic, "haxy-ssh-helper-v1")) return error.InvalidSshMagic; 490 491 const service_line = try readSshPreludeLine(reader); 492 const service = parseSshService(stripPrefix(service_line, "service=") orelse return error.InvalidSshServiceLine) orelse return error.InvalidSshService; 493 494 const protocol_line = try readSshPreludeLine(reader); 495 const protocol_version = std.meta.stringToEnum( 496 xit.net_server_common.ProtocolVersion, 497 stripPrefix(protocol_line, "protocol=") orelse return error.InvalidSshProtocolLine, 498 ) orelse return error.InvalidSshProtocol; 499 500 const repo_length_line = try readSshPreludeLine(reader); 501 const repo_len = try std.fmt.parseInt(usize, stripPrefix(repo_length_line, "repo-length=") orelse return error.InvalidSshRepoLengthLine, 10); 502 503 const empty_line = try readSshPreludeLine(reader); 504 if (empty_line.len != 0) return error.InvalidSshPreludeTerminator; 505 506 const repo = try reader.readAlloc(allocator, repo_len); 507 errdefer allocator.free(repo); 508 509 return .{ 510 .service = service, 511 .protocol_version = protocol_version, 512 .repo = repo, 513 }; 514 } 515 516 fn readSshPreludeLine(reader: *std.Io.Reader) ![]const u8 { 517 return (try reader.takeDelimiter('\n')) orelse error.InvalidSshHelperRequest; 518 } 519 520 fn parseSshService(value: []const u8) ?SshService { 521 if (std.mem.eql(u8, value, "upload-pack")) return .upload_pack; 522 if (std.mem.eql(u8, value, "receive-pack")) return .receive_pack; 523 return null; 524 } 525 526 fn stripPrefix(value: []const u8, prefix: []const u8) ?[]const u8 { 527 if (!std.mem.startsWith(u8, value, prefix)) return null; 528 return value[prefix.len..]; 529 } 530 531 fn resolveSshRepoPath( 532 allocator: std.mem.Allocator, 533 repo_root_path: []const u8, 534 repo: []const u8, 535 ) ![]const u8 { 536 if (std.fs.path.isAbsolute(repo)) { 537 return try std.fs.path.resolve(allocator, &.{repo}); 538 } 539 return try std.fs.path.resolve(allocator, &.{ repo_root_path, repo }); 540 } 541 542 fn parseListenAddress(value: []const u8) !ListenAddress { 543 const colon = std.mem.lastIndexOfScalar(u8, value, ':') orelse return error.InvalidListenAddress; 544 if (colon == 0 or colon + 1 >= value.len) return error.InvalidListenAddress; 545 const port = try std.fmt.parseInt(u16, value[colon + 1 ..], 10); 546 return .{ .host = value[0..colon], .port = port }; 547 } 548 549 fn decodeAndValidateRepoPath(allocator: std.mem.Allocator, encoded: []const u8) ![]const u8 { 550 if (encoded.len == 0) return error.InvalidRepoPath; 551 552 const mutable = try allocator.dupe(u8, encoded); 553 errdefer allocator.free(mutable); 554 const decoded = std.Uri.percentDecodeInPlace(mutable); 555 556 var iter = std.mem.splitScalar(u8, decoded, '/'); 557 while (iter.next()) |segment| { 558 if (segment.len == 0 or std.mem.eql(u8, segment, ".") or std.mem.eql(u8, segment, "..")) { 559 return error.InvalidRepoPath; 560 } 561 } 562 563 return try allocator.realloc(mutable, decoded.len); 564 } 565 566 fn isSubPath(parent: []const u8, child: []const u8) bool { 567 if (std.mem.eql(u8, parent, std.fs.path.sep_str)) return std.fs.path.isAbsolute(child); 568 if (!std.mem.startsWith(u8, child, parent)) return false; 569 return child.len == parent.len or child[parent.len] == std.fs.path.sep; 570 } 571 572 fn normalizeMethod(method: std.http.Method) std.http.Method { 573 return if (method == .HEAD) .GET else method; 574 } 575 576 fn protocolVersionFromHeader(header: ?[]const u8) xit.net_server_common.ProtocolVersion { 577 const git_protocol = header orelse return .v0; 578 var version: xit.net_server_common.ProtocolVersion = .v0; 579 var iter = std.mem.splitScalar(u8, git_protocol, ':'); 580 while (iter.next()) |entry| { 581 const value = std.mem.trimStart(u8, entry, " "); 582 if (std.mem.startsWith(u8, value, "version=")) { 583 const v = value["version=".len..]; 584 if (std.mem.eql(u8, v, "2")) { 585 version = .v2; 586 } else if (std.mem.eql(u8, v, "1") and version != .v2) { 587 version = .v1; 588 } 589 } 590 } 591 return version; 592 } 593 594 fn findHeader(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 595 var it = request.iterateHeaders(); 596 while (it.next()) |header| { 597 if (std.ascii.eqlIgnoreCase(header.name, name)) return header.value; 598 } 599 return null; 600 } 601 602 fn writeSimpleResponse( 603 http_server: *std.http.Server, 604 code: u16, 605 message: []const u8, 606 content_type: []const u8, 607 body: []const u8, 608 ) !void { 609 try http_server.out.print( 610 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 611 .{ code, message, content_type, body.len, body }, 612 ); 613 } 614 615 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 616 err.print(fmt, args) catch return; 617 err.flush() catch {}; 618 } 619