from pathlib import Path import csv, datetime, json, os, socket, socketserver, struct, subprocess, tempfile, threading B = Path(__file__).resolve().parent now = lambda: datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') started = now() records, events = [], [] def exact(s, n): out = b'' while len(out) < n: chunk = s.recv(n - len(out)) if not chunk: raise EOFError() out += chunk return out with tempfile.TemporaryDirectory(prefix='git-socks-probe-') as temp: root = Path(temp) env = {k:v for k,v in os.environ.items() if k.lower() not in ['http_proxy','https_proxy','all_proxy','no_proxy'] and not k.startswith('GIT_')} env.update(GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT='0', NO_PROXY='bypass.invalid', GIT_AUTHOR_NAME='Local Probe', GIT_AUTHOR_EMAIL='probe@example.invalid', GIT_COMMITTER_NAME='Local Probe', GIT_COMMITTER_EMAIL='probe@example.invalid') def git(args, input=None): return subprocess.check_output(['git', *args], env=env, input=input, stderr=subprocess.PIPE) repo = str(root / 'repo.git') git(['init','--bare','--initial-branch=main',repo]) tree = git(['--git-dir='+repo,'hash-object','-t','tree','--stdin'], b'').decode().strip() oid = git(['--git-dir='+repo,'commit-tree',tree], b'Local fixture only\n').decode().strip() git(['--git-dir='+repo,'update-ref','refs/heads/main',oid]) class Handler(socketserver.BaseRequestHandler): def handle(self): s=self.request; s.settimeout(8) try: ver,n=exact(s,2); methods=exact(s,n) assert ver==5 and 0 in methods s.sendall(b'\x05\x00') ver,cmd,res,atyp=exact(s,4) if atyp==3: host=exact(s,exact(s,1)[0]).decode() elif atyp==1: host=socket.inet_ntop(socket.AF_INET,exact(s,4)) elif atyp==4: host=socket.inet_ntop(socket.AF_INET6,exact(s,16)) else: raise ValueError(atyp) port=struct.unpack('!H',exact(s,2))[0] event={'atyp':atyp,'host':host,'port':port}; events.append(event) s.sendall(b'\x05\x00\x00\x01\x7f\x00\x00\x01\x00\x50') request=b'' while b'\r\n\r\n' not in request: request+=exact(s,1) method,path,_=request.split(b'\r\n',1)[0].decode().split(' ') path,_,query=path.partition('?') assert method=='GET' and path=='/repo.git/info/refs' cgi=dict(env,GIT_PROJECT_ROOT=str(root),GIT_HTTP_EXPORT_ALL='1',REQUEST_METHOD=method,PATH_INFO=path,QUERY_STRING=query) response=subprocess.check_output(['git','http-backend'],env=cgi) headers,body=response.split(b'\r\n\r\n',1) s.sendall(b'HTTP/1.1 200 OK\r\n'+headers+b'\r\nContent-Length: '+str(len(body)).encode()+b'\r\nConnection: close\r\n\r\n'+body) event['advertised_ref']=oid except Exception as e: events.append({'error':repr(e)}) class Server(socketserver.ThreadingTCPServer): allow_reuse_address=True daemon_threads=True with Server(('127.0.0.1',0),Handler) as server: thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start() port=server.server_address[1] for case in ['remote_dns','local_dns','url_override']: for round in [1,2,3]: remote='http://localhost/repo.git' if case=='local_dns' else 'http://repo.invalid/repo.git' proxy=('socks5' if case=='local_dns' else 'socks5h')+f'://127.0.0.1:{port}' args=['git','-c','protocol.version=0','-c','http.version=HTTP/1.1'] if case=='url_override': args+=['-c','http.proxy=socks5h://127.0.0.1:1','-c','http.http://repo.invalid/.proxy='+proxy] else: args+=['-c','http.proxy='+proxy] args+=['ls-remote',remote,'refs/heads/main'] before=len(events) result=subprocess.run(args,env=env,text=True,encoding='utf-8',errors='replace',capture_output=True,timeout=15) captured=events[before:] assert result.returncode==0 and result.stdout.strip()==oid+'\trefs/heads/main', (case,result.stderr,captured) assert len(captured)==1 and captured[0]['atyp'] in ([1,4] if case=='local_dns' else [3]) records.append({'case':case,'round':round,'argv':args,'returncode':result.returncode,'stdout':result.stdout,'stderr':result.stderr,'events':captured}) server.shutdown();thread.join() data={'started':started,'ended':now(),'git':git(['--version']).decode().strip(),'fixture_ref':oid, 'method':'Windows Git ls-remote via local SOCKS responder and local git http-backend, protocol v0, HTTP only. No external DNS/relay, TLS, SSH, clone, push, LFS or submodules.', 'records':records} (B/'git-run.json').write_text(json.dumps(data,indent=2)+'\n',encoding='utf-8') with (B/'git-run.csv').open('w',newline='',encoding='utf-8') as f: w=csv.writer(f);w.writerow(['case','round','exitcode','address_type','requested_host','ref']) for r in records:w.writerow([r['case'],r['round'],r['returncode'],r['events'][0]['atyp'],r['events'][0]['host'],r['stdout'].strip()]) print(json.dumps({'runs':len(records),'git':data['git'],'ended':data['ended']}))