#!/usr/bin/env python3 """Manage a temporary HTTPS tunnel for this project's HTTP entry point.""" import fcntl,os,re,shutil,signal,socket,subprocess,sys,time,urllib.request from pathlib import Path ROOT=Path(__file__).resolve().parents[1] STATE=ROOT/'.local';STATE.mkdir(exist_ok=True) PID=STATE/'share.pid';URL=STATE/'share.url';origin='http://127.0.0.1:18085' def running(): if not PID.exists():return None try:pid=int(PID.read_text()) except ValueError:return None command=subprocess.run(['ps','-p',str(pid),'-o','command='],capture_output=True,text=True).stdout return pid if 'cloudflared tunnel' in command and '--url '+origin in command else None with (STATE/'share.lock').open('w') as lock: fcntl.flock(lock,fcntl.LOCK_EX) pid=running() if '--stop' in sys.argv: if pid: os.kill(pid,signal.SIGTERM) for _ in range(50): if not running():break time.sleep(.1) else: try:os.kill(pid,signal.SIGKILL) except ProcessLookupError:pass PID.unlink(missing_ok=True);URL.unlink(missing_ok=True) print('Внешний доступ отключён. Localhost продолжает работать.');raise SystemExit if pid: print(URL.read_text().strip() if URL.exists() else 'Туннель запущен, ссылка ещё создаётся.');raise SystemExit binary=shutil.which('cloudflared') if not binary:raise SystemExit('Установите cloudflared: brew install cloudflared') try:urllib.request.urlopen(origin+'/health/ready',timeout=5).close() except Exception:raise SystemExit('Сначала запустите мессенджер: make up') URL.unlink(missing_ok=True) (STATE/'share.log').unlink(missing_ok=True) with (STATE/'share.log').open('w') as log: edge=socket.gethostbyname('region1.v2.argotunnel.com') process=subprocess.Popen([binary,'tunnel','--no-autoupdate','--protocol','http2','--edge',edge+':7844','--url',origin],stdout=log,stderr=subprocess.STDOUT,start_new_session=True,env={**os.environ,'GODEBUG':'netdns=cgo'}) PID.write_text(str(process.pid));PID.chmod(0o600) deadline=time.monotonic()+120 while time.monotonic()