GitHTTPServer.swift (3523B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 #if os(macOS) 3 import Foundation 4 5 /// A real local git "smart HTTP" server, with Basic authentication: a small Python server that hands the 6 /// requests to `git http-backend`, as Apache does on the Subsurface cloud. 7 public final class GitHTTPServer { 8 public let port: Int 9 private let process: Process 10 11 static let script = #""" 12 import base64, os, subprocess, sys 13 from http.server import BaseHTTPRequestHandler, HTTPServer 14 15 ROOT, USER, PASSWORD = sys.argv[1], sys.argv[2], sys.argv[3] 16 EXPECTED = "Basic " + base64.b64encode((USER + ":" + PASSWORD).encode()).decode() 17 18 class Handler(BaseHTTPRequestHandler): 19 protocol_version = "HTTP/1.1" 20 def log_message(self, *args): pass 21 def handle_git(self): 22 if self.headers.get("Authorization") != EXPECTED: 23 body = b"Unauthorized" 24 self.send_response(401) 25 self.send_header("WWW-Authenticate", 'Basic realm="Test"') 26 self.send_header("Content-Length", str(len(body))) 27 self.end_headers() 28 self.wfile.write(body) 29 return 30 path, _, query = self.path.partition("?") 31 length = int(self.headers.get("Content-Length") or 0) 32 data = self.rfile.read(length) if length else b"" 33 env = dict(os.environ, GIT_PROJECT_ROOT=ROOT, GIT_HTTP_EXPORT_ALL="1", PATH_INFO=path, QUERY_STRING=query, 34 REQUEST_METHOD=self.command, CONTENT_TYPE=self.headers.get("Content-Type", ""), 35 CONTENT_LENGTH=str(length), REMOTE_USER=USER, REMOTE_ADDR="127.0.0.1") 36 out = subprocess.run(["git", "http-backend"], input=data, env=env, capture_output=True).stdout 37 head, _, body = out.partition(b"\r\n\r\n") 38 status = 200 39 headers = [] 40 for line in head.split(b"\r\n"): 41 name, _, value = line.decode().partition(": ") 42 if name.lower() == "status": status = int(value.split()[0]) 43 elif name: headers.append((name, value)) 44 self.send_response(status) 45 for name, value in headers: self.send_header(name, value) 46 self.send_header("Content-Length", str(len(body))) 47 self.end_headers() 48 self.wfile.write(body) 49 do_GET = handle_git 50 do_POST = handle_git 51 52 server = HTTPServer(("127.0.0.1", 0), Handler) 53 print(server.server_address[1], flush=True) 54 server.serve_forever() 55 """# 56 57 /// `root` holds the bare repositories served under `/git/…` (root/git/<name>). 58 public init(root: URL, user: String, password: String) throws { 59 let scriptURL = root.appendingPathComponent("server.py") 60 try Data(Self.script.utf8).write(to: scriptURL) 61 process = Process() 62 process.executableURL = URL(fileURLWithPath: "/usr/bin/env") 63 process.arguments = ["python3", scriptURL.path, root.path, user, password] 64 let output = Pipe() 65 process.standardOutput = output 66 process.standardError = FileHandle.nullDevice 67 try process.run() 68 var line = [UInt8]() 69 while let byte = try output.fileHandleForReading.read(upToCount: 1)?.first, byte != 0x0a { line.append(byte) } 70 guard let port = Int(String(decoding: line, as: UTF8.self)) else { 71 process.terminate() 72 throw NSError(domain: "GitHTTPServer", code: 1, userInfo: [NSLocalizedDescriptionKey: "the test server did not start"]) 73 } 74 self.port = port 75 } 76 77 public func stop() { 78 process.terminate() 79 } 80 81 deinit { process.terminate() } 82 } 83 #endif