IT
apps/winzik / src / Cloud / LanShare.php · commit 6576d6f
<?phpnamespace App\Cloud;use JumPHP\Net\HttpRequest;use JumPHP\Net\HttpResponse;use JumPHP\Net\HttpServer;/** * The PC hands a file to a phone of the same network (the fastest way: nothing goes through the Internet). An HTTP * server of the engine (JumPHP\Net\HttpServer, non-blocking, Range) open ONLY while a transfer waits: each file * offered gets a one-time 128-bit token valid 10 minutes (GET /f/<token>: no path ever comes from the address), only * private addresses may ask (RFC 1918, link-local, loopback; the emulator's 10.0.2.2). Closed when no token is left. * Windows asks the user once whether WinZik may receive connections (its firewall): the first send says so. */final class LanShare{    public const TTL = 600.0;    private ?HttpServer $server = null;    /** @var array<string, array{path: string, until: float, entry: string}> */    private array $tokens = [];    /** @var list<string>|null tests: the addresses advertised (null: the computer's own) */    public ?array $addresses = null;    /** @var \Closure(): float */    private \Closure $clock;    /** @param (\Closure(): HttpServer)|null $factory */    public function __construct(private ?\Closure $factory = null, ?\Closure $clock = null)    {        $this->clock = $clock ?? static fn (): float => microtime(true);    }    public static function supported(): bool    {        return HttpServer::isSupported() && getenv('WINZIK_CLOUD_NO_LAN') !== '1';    }    /**     * Offers a file: its URLs on every address of this computer (the phone tries each one), or [] when no server can open.     * @return list<string>     */    public function offer(string $path, string $entry): array    {        if (!self::supported() || !is_file($path)) {            return [];        }        try {            if ($this->server === null || !$this->server->isListening()) {                $this->server = $this->factory !== null ? ($this->factory)() : new HttpServer();                $this->server->allow(fn (string $ip): bool => HttpServer::isPrivateAddress($ip));                $this->server->handle('/f/', fn (HttpRequest $r): ?HttpResponse => $this->serve($r));                $this->server->listen();            }        } catch (\Throwable) {            $this->server = null;            return [];        }        $token = bin2hex(random_bytes(16));        $this->tokens[$token] = ['path' => $path, 'until' => ($this->clock)() + self::TTL, 'entry' => $entry];        $port = (int)$this->server->port();        return array_map(fn (string $ip) => 'http://' . (str_contains($ip, ':') ? "[$ip]" : $ip) . ':' . $port . '/f/' . $token, $this->addresses ?? self::localAddresses());    }    private function serve(HttpRequest $r): ?HttpResponse    {        $token = substr($r->path, 3);        $t = $this->tokens[$token] ?? null;        if ($t === null || $t['until'] < ($this->clock)() || !is_file($t['path'])) {            return null;        }        return HttpResponse::file($t['path'], 'audio/mpeg', ['Cache-Control' => 'no-store']);    }    /** The transfer of an entry ended (or was given up): its tokens are gone. */    public function done(string $entry): void    {        foreach ($this->tokens as $token => $t) {            if ($t['entry'] === $entry) {                unset($this->tokens[$token]);            }        }    }    /** Each frame: the clients served; closed once no token is left (and nobody is still downloading). */    public function poll(): void    {        if ($this->server === null) {            return;        }        $now = ($this->clock)();        $this->tokens = array_filter($this->tokens, fn (array $t) => $t['until'] >= $now);        $this->server->poll();        if ($this->tokens === [] && $this->server->clientCount() === 0) {            $this->close();        }    }    public function isOpen(): bool    {        return $this->server !== null && $this->server->isListening();    }    public function close(): void    {        $this->server?->close();        $this->server = null;        $this->tokens = [];    }    public function stop(): void    {        $this->close();    }    /**     * This computer's private addresses: the one of the way out (a UDP socket "connected" without sending anything)     * and the ones of its name; never the loopback, never a public one.     * @return list<string>     */    public static function localAddresses(): array    {        $ips = [];        $s = @stream_socket_client('udp://10.255.255.255:9', $no, $err, 0.2);        if ($s !== false) {            $name = (string)@stream_socket_get_name($s, false);            fclose($s);            $ip = (string)preg_replace('/:\d+$/', '', $name);            if ($ip !== '') {                $ips[] = $ip;            }        }        $host = @gethostname();        foreach (is_string($host) ? (@gethostbynamel($host) ?: []) : [] as $ip) {            $ips[] = $ip;        }        return array_values(array_unique(array_filter($ips, fn (string $ip) => HttpServer::isPrivateAddress($ip) && !str_starts_with($ip, '127.'))));    }}