2023-08-28 08:25:16 +00:00
|
|
|
import argparse
|
2023-10-05 15:03:01 +00:00
|
|
|
import contextlib
|
2023-07-25 11:46:58 +00:00
|
|
|
import json
|
|
|
|
import socket
|
|
|
|
import subprocess
|
|
|
|
import time
|
|
|
|
import urllib.request
|
|
|
|
from contextlib import contextmanager
|
|
|
|
from pathlib import Path
|
|
|
|
from tempfile import TemporaryDirectory
|
|
|
|
from typing import Any, Iterator, Optional
|
|
|
|
|
2023-09-26 15:31:45 +00:00
|
|
|
|
|
|
|
class ClanError(Exception):
|
|
|
|
pass
|
2023-07-26 06:00:07 +00:00
|
|
|
|
2023-07-25 11:46:58 +00:00
|
|
|
|
|
|
|
def try_bind_port(port: int) -> bool:
|
|
|
|
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
with tcp, udp:
|
|
|
|
try:
|
|
|
|
tcp.bind(("127.0.0.1", port))
|
|
|
|
udp.bind(("127.0.0.1", port))
|
|
|
|
return True
|
2023-08-27 08:46:53 +00:00
|
|
|
except OSError:
|
2023-07-25 11:46:58 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def try_connect_port(port: int) -> bool:
|
|
|
|
sock = socket.socket(socket.AF_INET)
|
|
|
|
result = sock.connect_ex(("127.0.0.1", port))
|
|
|
|
sock.close()
|
|
|
|
return result == 0
|
|
|
|
|
|
|
|
|
2023-10-05 15:03:01 +00:00
|
|
|
def find_free_port() -> Optional[int]:
|
|
|
|
"""Find an unused localhost port from 1024-65535 and return it."""
|
|
|
|
with contextlib.closing(socket.socket(type=socket.SOCK_STREAM)) as sock:
|
|
|
|
sock.bind(("127.0.0.1", 0))
|
|
|
|
return sock.getsockname()[1]
|
2023-07-25 11:46:58 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ZerotierController:
|
|
|
|
def __init__(self, port: int, home: Path) -> None:
|
|
|
|
self.port = port
|
|
|
|
self.home = home
|
2023-08-28 08:25:16 +00:00
|
|
|
self.authtoken = (home / "authtoken.secret").read_text()
|
|
|
|
self.secret = (home / "identity.secret").read_text()
|
2023-07-25 11:46:58 +00:00
|
|
|
|
|
|
|
def _http_request(
|
|
|
|
self,
|
|
|
|
path: str,
|
|
|
|
method: str = "GET",
|
|
|
|
headers: dict[str, str] = {},
|
|
|
|
data: Optional[dict[str, Any]] = None,
|
|
|
|
) -> dict[str, Any]:
|
|
|
|
body = None
|
|
|
|
headers = headers.copy()
|
|
|
|
if data is not None:
|
|
|
|
body = json.dumps(data).encode("ascii")
|
|
|
|
headers["Content-Type"] = "application/json"
|
2023-08-28 08:25:16 +00:00
|
|
|
headers["X-ZT1-AUTH"] = self.authtoken
|
2023-07-25 11:46:58 +00:00
|
|
|
url = f"http://127.0.0.1:{self.port}{path}"
|
|
|
|
req = urllib.request.Request(url, headers=headers, method=method, data=body)
|
|
|
|
resp = urllib.request.urlopen(req)
|
|
|
|
return json.load(resp)
|
|
|
|
|
2023-07-28 14:13:25 +00:00
|
|
|
def status(self) -> dict[str, Any]:
|
2023-07-25 11:46:58 +00:00
|
|
|
return self._http_request("/status")
|
|
|
|
|
|
|
|
def create_network(self, data: dict[str, Any] = {}) -> dict[str, Any]:
|
|
|
|
identity = (self.home / "identity.public").read_text()
|
|
|
|
node_id = identity.split(":")[0]
|
|
|
|
return self._http_request(
|
|
|
|
f"/controller/network/{node_id}______", method="POST", data=data
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_network(self, id: str) -> dict[str, Any]:
|
|
|
|
return self._http_request(f"/controller/network/{id}")
|
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def zerotier_controller() -> Iterator[ZerotierController]:
|
|
|
|
# This check could be racy but it's unlikely in practice
|
2023-10-05 15:03:01 +00:00
|
|
|
controller_port = find_free_port()
|
2023-07-26 13:50:27 +00:00
|
|
|
if controller_port is None:
|
|
|
|
raise ClanError("cannot find a free port for zerotier controller")
|
2023-08-26 09:23:15 +00:00
|
|
|
|
2023-07-25 11:46:58 +00:00
|
|
|
with TemporaryDirectory() as d:
|
|
|
|
tempdir = Path(d)
|
|
|
|
home = tempdir / "zerotier-one"
|
|
|
|
home.mkdir()
|
2023-09-26 15:31:45 +00:00
|
|
|
cmd = [
|
|
|
|
"fakeroot",
|
|
|
|
"--",
|
|
|
|
"zerotier-one",
|
|
|
|
f"-p{controller_port}",
|
|
|
|
str(home),
|
|
|
|
]
|
2023-07-25 11:46:58 +00:00
|
|
|
with subprocess.Popen(cmd) as p:
|
|
|
|
try:
|
|
|
|
print(
|
|
|
|
f"wait for controller to be started on 127.0.0.1:{controller_port}...",
|
|
|
|
)
|
|
|
|
while not try_connect_port(controller_port):
|
|
|
|
status = p.poll()
|
|
|
|
if status is not None:
|
2023-07-26 13:50:27 +00:00
|
|
|
raise ClanError(
|
2023-07-25 11:46:58 +00:00
|
|
|
f"zerotier-one has been terminated unexpected with {status}"
|
|
|
|
)
|
|
|
|
time.sleep(0.1)
|
|
|
|
print()
|
|
|
|
|
|
|
|
yield ZerotierController(controller_port, home)
|
|
|
|
finally:
|
2023-10-05 15:09:54 +00:00
|
|
|
p.terminate()
|
2023-07-25 11:46:58 +00:00
|
|
|
p.wait()
|
|
|
|
|
|
|
|
|
|
|
|
# TODO: allow merging more network configuration here
|
2023-08-28 08:25:16 +00:00
|
|
|
def create_network() -> dict:
|
2023-07-25 11:46:58 +00:00
|
|
|
with zerotier_controller() as controller:
|
|
|
|
network = controller.create_network()
|
2023-08-28 08:25:16 +00:00
|
|
|
return {
|
|
|
|
"secret": controller.secret,
|
|
|
|
"networkid": network["nwid"],
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-09-26 15:31:45 +00:00
|
|
|
def main() -> None:
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument("network_id")
|
|
|
|
parser.add_argument("identity_secret")
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
2023-08-28 08:25:16 +00:00
|
|
|
zerotier = create_network()
|
2023-09-26 15:31:45 +00:00
|
|
|
Path(args.network_id).write_text(zerotier["networkid"])
|
|
|
|
Path(args.identity_secret).write_text(zerotier["secret"])
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|