RU
apps/winzik / src / Cloud / Transfer.php · commit 6576d6f
<?phpnamespace App\Cloud;/** * A song of the cloud coming to this device (the receiving side): written to <target>.part, resumed at the size of * that part after a cut (HTTP Range on the network, the offset on the relay), its SHA-256 checked before it becomes * <target>. The ways, in order: the PC's LanShare (each address it advertised, 1.5 s to answer), then the relay * (CloudLink chunks). App\Cloud\Cloud drives it from the messages of the room. * * States: waiting (asked the PC) | lan | relay | verify | done | offline (the PC is not there) | error. */final class Transfer{    public const CONNECT_TIMEOUT = 1.5;    public const SILENCE = 20.0;    public string $state = 'waiting';    public string $error = '';    public int $received = 0;    public int $size;    /** seconds since anything happened (the relay or the PC silent too long: asked again) */    public float $idle = 0.0;    /** how many times the network way was cut and resumed */    public int $resumes = 0;    public bool $lanFailed = false;    /** started by itself ("Copier automatiquement"), not by the user */    public bool $auto = false;    /** the HTTP status of the last answer of the PC (206: resumed where it was) */    public int $lastStatus = 0;    /** @var list<string> */    private array $urls = [];    private int $url = 0;    /** @var resource|null */    private $socket = null;    private string $phase = '';    private string $head = '';    private float $deadline = 0.0;    private int $expect = 0;    private int $cuts = 0;    /** @param array<string, mixed> $entry the cloud entry (id, sha256, size...) */    public function __construct(public readonly array $entry, public readonly string $target)    {        $this->size = max(0, (int)($entry['size'] ?? 0));        @mkdir(dirname($target), 0777, true);        $this->received = is_file($target . '.part') ? (int)filesize($target . '.part') : 0;    }    public function id(): string    {        return (string)$this->entry['id'];    }    public function progress(): float    {        return $this->size > 0 ? min(1.0, $this->received / $this->size) : 0.0;    }    public function active(): bool    {        return in_array($this->state, ['waiting', 'lan', 'relay', 'verify'], true);    }    // --- the LAN ---------------------------------------------------------------------------------------------------    /** @param list<string> $urls the PC's addresses for this file (http://<private ip>:<port>/f/<token>) */    public function tryLan(array $urls): void    {        $this->urls = array_values(array_filter($urls, fn (string $u) => self::lanUrl($u)));        $this->url = 0;        $this->cuts = 0;        $this->lanFailed = false;        $this->idle = 0.0;        if ($this->urls === []) {            $this->lanFailed = true;            return;        }        $this->state = 'lan';        $this->connect();    }    /** Only http to a private address (never a server of the Internet given by someone else). */    public static function lanUrl(string $url): bool    {        $u = parse_url($url);        return is_array($u) && ($u['scheme'] ?? '') === 'http' && isset($u['host'])            && \JumPHP\Net\HttpServer::isPrivateAddress(trim((string)$u['host'], '[]')) && str_starts_with((string)($u['path'] ?? ''), '/f/');    }    private function connect(): void    {        $this->closeSocket();        $url = $this->urls[$this->url] ?? null;        if ($url === null) {            $this->state = 'waiting';            $this->lanFailed = true;            return;        }        $u = (array)parse_url($url);        $host = trim((string)$u['host'], '[]');        $port = (int)($u['port'] ?? 80);        $target = str_contains($host, ':') ? "[$host]" : $host;        $s = @stream_socket_client("tcp://$target:$port", $no, $err, self::CONNECT_TIMEOUT, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT);        if ($s === false) {            $this->nextUrl();            return;        }        stream_set_blocking($s, false);        $this->socket = $s;        $this->phase = 'connect';        $this->head = '';        $this->deadline = microtime(true) + self::CONNECT_TIMEOUT;        $this->requestLine = 'GET ' . ($u['path'] ?? '/') . " HTTP/1.1\r\nHost: $target:$port\r\nUser-Agent: WinZik\r\nConnection: close\r\n"            . ($this->received > 0 ? 'Range: bytes=' . $this->received . "-\r\n" : '') . "\r\n";    }    private string $requestLine = '';    private function nextUrl(): void    {        $this->closeSocket();        $this->url++;        $this->connect();    }    /** A cut in the middle: the same address again from what is here (Range), 3 times; then the relay. */    private function cut(): void    {        $this->closeSocket();        if (++$this->cuts > 3) {            $this->state = 'waiting';            $this->lanFailed = true;            return;        }        $this->resumes++;        $this->connect();    }    /** Each frame. */    public function poll(float $dt = 0.0): void    {        $this->idle += $dt;        if ($this->state !== 'lan' || $this->socket === null) {            return;        }        $s = $this->socket;        $until = microtime(true) + 0.008;        while ($this->socket !== null && microtime(true) < $until) {      // a step that ends the network way closes the socket            if ($this->phase === 'connect') {                $r = null;                $w = [$s];                $e = null;                if (@stream_select($r, $w, $e, 0) < 1) {                    if (microtime(true) > $this->deadline) {                        $this->nextUrl();                    }                    return;                }                if (@fwrite($s, $this->requestLine) === false) {                    $this->nextUrl();                    return;                }                $this->phase = 'head';                $this->deadline = microtime(true) + 5.0;                continue;            }            $chunk = @fread($s, 262144);            if ($chunk === false || $chunk === '') {                if (feof($s)) {                    $this->phase === 'head' ? $this->nextUrl() : $this->ended();                } elseif ($this->phase === 'head' && microtime(true) > $this->deadline) {                    $this->nextUrl();                } elseif ($this->phase === 'body' && $this->idle > 10.0) {                    $this->cut();                }                return;            }            $this->idle = 0.0;            if ($this->phase === 'head') {                $this->head .= $chunk;                $end = strpos($this->head, "\r\n\r\n");                if ($end === false) {                    if (strlen($this->head) > 16384) {                        $this->nextUrl();                        return;                    }                    continue;                }                $body = (string)substr($this->head, $end + 4);                if (!$this->headers(substr($this->head, 0, $end))) {                    return;                }                $this->phase = 'body';                $chunk = $body;            }            if ($chunk !== '' && !$this->append($chunk)) {                return;            }            if ($this->expect > 0 && $this->received >= $this->expect) {                $this->closeSocket();                $this->verify();                return;            }        }    }    private function headers(string $head): bool    {        $code = preg_match('#^HTTP/\S+\s+(\d{3})#', $head, $m) ? (int)$m[1] : 0;        $length = preg_match('/^content-length:\s*(\d+)/mi', $head, $m) ? (int)$m[1] : -1;        $this->lastStatus = $code;        if ($code === 416 && $this->received >= $this->size && $this->size > 0) {            $this->closeSocket();            $this->verify();        // everything was here already            return false;        }        if ($code === 200 && $this->received > 0) {            $this->truncate();      // the server sends the whole file: from the start        } elseif ($code !== 206 && $code !== 200) {            $this->nextUrl();            return false;        }        $this->expect = $length >= 0 ? $this->received + $length : $this->size;        if ($this->size > 0 && $this->expect > $this->size) {            $this->fail('le fichier envoyé est plus gros que prévu');            return false;        }        return true;    }    private function ended(): void    {        $this->closeSocket();        if ($this->expect > 0 && $this->received < $this->expect) {            $this->cut();            return;        }        $this->verify();    }    // --- the relay -------------------------------------------------------------------------------------------------    public function startRelay(): void    {        $this->closeSocket();        $this->state = 'relay';        $this->idle = 0.0;    }    /** A chunk from the relay: written when it is the next one. @return bool false: not where we are (ask again) */    public function chunk(int $offset, string $bytes): bool    {        if ($this->state !== 'relay') {            return true;        }        $this->idle = 0.0;        if ($offset + strlen($bytes) <= $this->received) {            return true;        // already here (a chunk sent twice)        }        if ($offset !== $this->received) {            return false;        }        return $this->append($bytes);    }    /** The sender says it sent everything. */    public function sent(): void    {        if ($this->state === 'relay') {            $this->verify();        }    }    // --- the file --------------------------------------------------------------------------------------------------    private function append(string $bytes): bool    {        if ($this->size > 0 && $this->received + strlen($bytes) > $this->size) {            $this->fail('le fichier envoyé est plus gros que prévu');            return false;        }        if (@file_put_contents($this->target . '.part', $bytes, FILE_APPEND) !== strlen($bytes)) {            $this->fail('impossible d\'écrire ' . basename($this->target) . ' (disque plein ?)');            return false;        }        $this->received += strlen($bytes);        return true;    }    private function truncate(): void    {        @file_put_contents($this->target . '.part', '');        $this->received = 0;    }    /** The whole file is here: its SHA-256 must be the entry's, else it is thrown away. */    public function verify(): void    {        $this->closeSocket();        $this->state = 'verify';        $part = $this->target . '.part';        $sha = is_file($part) ? (string)hash_file('sha256', $part) : '';        $want = strtolower((string)($this->entry['sha256'] ?? ''));        if ($want !== '' && $sha !== $want) {            @unlink($part);            $this->received = 0;            $this->fail('fichier abîmé pendant la copie (empreinte SHA-256 différente) : réessayez');            return;        }        if ($this->size > 0 && $this->received !== $this->size) {            $this->fail('fichier incomplet');            return;        }        @unlink($this->target);        if (!@rename($part, $this->target)) {            $this->fail('impossible d\'écrire ' . basename($this->target));            return;        }        $this->state = 'done';    }    public function fail(string $message): void    {        $this->closeSocket();        $this->state = 'error';        $this->error = $message;    }    /** The PC is not there: waits for it (the part stays). */    public function offline(): void    {        $this->closeSocket();        $this->state = 'offline';    }    /** Stopped for good: the part file removed. */    public function cancel(): void    {        $this->closeSocket();        @unlink($this->target . '.part');        $this->state = 'error';        $this->error = 'arrêté';    }    private function closeSocket(): void    {        if ($this->socket !== null) {            @fclose($this->socket);            $this->socket = null;        }    }}