summaryrefslogtreecommitdiffstats
path: root/web/index.php
blob: 77edf9528104f3eaf8b108d8ea3eca5d3f96e327 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php
declare(strict_types=1);

/**
 * zagan.bet download page.
 *
 * Scans ./bin/{gui,client,server} and renders every build it finds, with its
 * version, size and SHA-256. The GPL source link points at the public git
 * repository. No database, no JavaScript, no dependencies.
 *
 * Expected file names (anything else is ignored):
 *
 *   bin/gui/zagan-bet-gui-<version>-<platform>-<arch>[.exe]
 *   bin/gui/zagan-bet-gui-<version>-<platform>-<arch>-install.sh
 *   bin/gui/zagan-bet-gui-<version>-<platform>-<arch>-install.ps1
 *   bin/client/zagan-bet-client-<version>-<platform>-<arch>[.exe]
 *   bin/server/zagan-bet-server-<version>-<platform>-<arch>[.exe]
 *
 * <version> is MAJOR.MINOR.PATCH, <platform> is linux|windows|macos and
 * <arch> is x86_64|i686|aarch64. Example:
 *
 *   bin/gui/zagan-bet-gui-4.3.0-linux-x86_64
 *   bin/client/zagan-bet-client-4.3.0-linux-x86_64
 *
 * SHA-256 values are cached in a JSON file keyed on size and mtime, so a file
 * is only re-read when it changes. The cache lives in the system temp
 * directory by default (the web root is often not writable by the PHP user);
 * set ZAGAN_HASH_CACHE to put it somewhere else.
 */

const KINDS = [
    'gui' => [
        'title' => 'Desktop app',
        'hint' => 'Windows 10 or newer, or a Linux desktop. No terminal needed.',
    ],
    'client' => [
        'title' => 'Client',
        'hint' => 'Needs a terminal of at least 80×24 cells.',
    ],
    'server' => [
        'title' => 'Server',
        'hint' => 'Generates its own TLS identity on first run.',
    ],
];

const PLATFORMS = [
    'linux' => 'Linux',
    'windows' => 'Windows',
    'macos' => 'macOS',
];

const ARCHES = [
    'x86_64' => '64-bit',
    'i686' => '32-bit',
    'aarch64' => 'ARM64',
];

// Newest version first, then 64-bit builds before 32-bit.
const PLATFORM_ORDER = ['linux' => 0, 'windows' => 1, 'macos' => 2];
const ARCH_ORDER = ['x86_64' => 0, 'aarch64' => 1, 'i686' => 2];

function e(?string $value): string
{
    return htmlspecialchars($value ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function human_size(int $bytes): string
{
    if ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 1) . ' MB';
    }
    if ($bytes >= 1024) {
        return number_format($bytes / 1024) . ' KB';
    }
    return $bytes . ' B';
}

/**
 * Hash to use for a published file, reusing the cached value when the file has
 * not changed since it was hashed.
 *
 * A cached hash is valid only when the size and mtime still match and the hash
 * was taken at or after the file's mtime, so a restored or touched file is
 * re-read.
 *
 * @param array{files:array<string,array{size:int,mtime:int,sha256:string,hashed_at:int}>} $cache
 */
function cached_hash(
    string $key,
    string $path,
    int $size,
    int $mtime,
    array &$cache,
    bool &$dirty
): ?string {
    $entry = $cache['files'][$key] ?? null;
    if (
        is_array($entry)
        && ($entry['size'] ?? null) === $size
        && ($entry['mtime'] ?? null) === $mtime
        && (int) ($entry['hashed_at'] ?? 0) >= $mtime
        && isset($entry['sha256'])
        && is_string($entry['sha256'])
        && preg_match('/\A[0-9a-f]{64}\z/', $entry['sha256']) === 1
    ) {
        return $entry['sha256'];
    }

    $hash = hash_file('sha256', $path);
    if ($hash === false) {
        return null;
    }

    $cache['files'][$key] = [
        'size' => $size,
        'mtime' => $mtime,
        'sha256' => $hash,
        'hashed_at' => time(),
    ];
    $dirty = true;

    return $hash;
}

/** @return array{files:array<string,array{size:int,mtime:int,sha256:string,hashed_at:int}>} */
function load_hash_cache(string $path): array
{
    $raw = @file_get_contents($path);
    if ($raw === false || $raw === '') {
        return ['files' => []];
    }
    $decoded = json_decode($raw, true);
    if (!is_array($decoded) || !isset($decoded['files']) || !is_array($decoded['files'])) {
        return ['files' => []];
    }

    return ['files' => $decoded['files']];
}

/**
 * Best effort: a read-only web root, a full disk or a racing writer must never
 * break the page, so failures are ignored and the next request recomputes.
 *
 * @param array{files:array<string,array{size:int,mtime:int,sha256:string,hashed_at:int}>} $cache
 */
function save_hash_cache(string $path, array $cache): void
{
    $json = json_encode($cache, JSON_UNESCAPED_SLASHES);
    if ($json === false) {
        return;
    }
    $directory = dirname($path);
    $temporary = @tempnam($directory, '.zagan-hashes-');
    if ($temporary === false) {
        return;
    }
    if (@file_put_contents($temporary, $json, LOCK_EX) === false || !@rename($temporary, $path)) {
        @unlink($temporary);
    }
}

/**
 * @return array{version:string,platform:string,arch:string,file:string,size:int,mtime:int,sha256:string}|null
 */
function read_release(
    string $kind,
    string $directory,
    string $entry,
    array &$cache,
    bool &$dirty
): ?array {
    $pattern = '/^zagan-bet-' . preg_quote($kind, '/')
        . '-v?(\d+\.\d+\.\d+)-([a-z]+)-([a-z0-9_]+)(-install\.sh|-install\.ps1|\.exe)?$/i';
    if (preg_match($pattern, $entry, $matches) !== 1) {
        return null;
    }

    $realDirectory = realpath($directory);
    $real = realpath($directory . '/' . $entry);
    if ($realDirectory === false || $real === false) {
        return null;
    }
    // Never serve anything that resolves outside the published directory.
    if (!str_starts_with($real, $realDirectory . DIRECTORY_SEPARATOR)) {
        return null;
    }
    if (!is_file($real)) {
        return null;
    }

    $size = filesize($real);
    $mtime = filemtime($real);
    if ($size === false || $mtime === false) {
        return null;
    }

    $hash = cached_hash($kind . '/' . $entry, $real, $size, $mtime, $cache, $dirty);
    if ($hash === null) {
        return null;
    }

    $suffix = strtolower($matches[4] ?? '');
    $variant = str_starts_with($suffix, '-install.') ? 'installer' : 'binary';

    return [
        'version' => $matches[1],
        'platform' => strtolower($matches[2]),
        'arch' => strtolower($matches[3]),
        'variant' => $variant,
        'file' => $entry,
        'size' => $size,
        'mtime' => $mtime,
        'sha256' => $hash,
    ];
}

$base = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
if ($base === '.' || $base === '/') {
    $base = '';
}

$cachePath = getenv('ZAGAN_HASH_CACHE');
if (!is_string($cachePath) || $cachePath === '') {
    $cachePath = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR)
        . DIRECTORY_SEPARATOR . 'zagan-bet-hashes-'
        . substr(hash('sha256', __DIR__), 0, 16) . '.json';
}
$cache = load_hash_cache($cachePath);
$cacheDirty = false;
$seen = [];

$releases = [];
$newest = 0;

foreach (KINDS as $kind => $meta) {
    $found = [];
    $directory = __DIR__ . '/bin/' . $kind;

    if (is_dir($directory)) {
        $entries = scandir($directory);
        if ($entries !== false) {
            foreach ($entries as $entry) {
                if ($entry === '.' || $entry === '..') {
                    continue;
                }
                $release = read_release($kind, $directory, $entry, $cache, $cacheDirty);
                if ($release === null) {
                    continue;
                }
                $seen[$kind . '/' . $entry] = true;
                $release['href'] = $base . '/bin/' . $kind . '/' . rawurlencode($release['file']);
                $found[] = $release;
                $newest = max($newest, $release['mtime']);
            }
        }
    }

    usort($found, static function (array $a, array $b): int {
        $byVersion = version_compare($b['version'], $a['version']);
        if ($byVersion !== 0) {
            return $byVersion;
        }
        $byPlatform = (PLATFORM_ORDER[$a['platform']] ?? 9) <=> (PLATFORM_ORDER[$b['platform']] ?? 9);
        if ($byPlatform !== 0) {
            return $byPlatform;
        }
        $byArch = (ARCH_ORDER[$a['arch']] ?? 9) <=> (ARCH_ORDER[$b['arch']] ?? 9);
        if ($byArch !== 0) {
            return $byArch;
        }
        $byVariant = ($a['variant'] === 'installer' ? 1 : 0) <=> ($b['variant'] === 'installer' ? 1 : 0);
        if ($byVariant !== 0) {
            return $byVariant;
        }
        return strcmp($a['file'], $b['file']);
    });

    $releases[$kind] = $found;
}

// Drop cache entries for files that are no longer published.
foreach (array_keys($cache['files']) as $key) {
    if (!isset($seen[$key])) {
        unset($cache['files'][$key]);
        $cacheDirty = true;
    }
}
if ($cacheDirty) {
    save_hash_cache($cachePath, $cache);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>żagań.bet</title>
<meta name="description" content="Official zagan.bet desktop app, terminal client and server downloads.">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'">
</head>
<body>

<h1>żagań.bet</h1>
<p>Official desktop app, terminal client and server builds.</p>
<?php if ($newest > 0): ?>
<p>Builds published <?= e(gmdate('j M Y H:i', $newest)) ?> UTC.</p>
<?php endif; ?>

<h2>Desktop app</h2>
<p>Windows 10 or newer, or a Linux desktop. No terminal needed.</p>
<?php $guiBinaries = array_values(array_filter($releases['gui'], static fn (array $r): bool => $r['variant'] === 'binary')); ?>
<?php $guiInstallers = array_values(array_filter($releases['gui'], static fn (array $r): bool => $r['variant'] === 'installer')); ?>
<?php if ($guiBinaries === []): ?>
<p>Nothing published yet.</p>
<?php else: ?>
<ul>
<?php foreach ($guiBinaries as $release): ?>
<li><a href="<?= e($release['href']) ?>" download><?= e(PLATFORMS[$release['platform']] ?? ucfirst($release['platform'])) ?> <?= e($release['arch']) ?><?php if (isset(ARCHES[$release['arch']])): ?> (<?= e(ARCHES[$release['arch']]) ?>)<?php endif; ?> v<?= e($release['version']) ?> — <?= e(human_size($release['size'])) ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php if ($guiInstallers !== []): ?>
<h3>Installers</h3>
<p>The installer checks the download, installs Zagan-Bet for your user and adds it to your programs. Run it next to a downloaded app, or on its own to fetch one.</p>
<ul>
<?php foreach ($guiInstallers as $release): ?>
<li><a href="<?= e($release['href']) ?>" download><?= e(PLATFORMS[$release['platform']] ?? ucfirst($release['platform'])) ?> <?= e($release['arch']) ?> installer (<?= str_ends_with($release['file'], '.ps1') ? 'PowerShell' : 'bash' ?>) v<?= e($release['version']) ?> — <?= e(human_size($release['size'])) ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

<h2>Terminal client</h2>
<p>Needs a terminal of at least 80×24 cells.</p>
<?php if ($releases['client'] === []): ?>
<p>Nothing published yet.</p>
<?php else: ?>
<ul>
<?php foreach ($releases['client'] as $release): ?>
<li><a href="<?= e($release['href']) ?>" download><?= e(PLATFORMS[$release['platform']] ?? ucfirst($release['platform'])) ?> <?= e($release['arch']) ?><?php if (isset(ARCHES[$release['arch']])): ?> (<?= e(ARCHES[$release['arch']]) ?>)<?php endif; ?> v<?= e($release['version']) ?> — <?= e(human_size($release['size'])) ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

<h2>Server</h2>
<p>Generates its own TLS identity on first run.</p>
<?php if ($releases['server'] === []): ?>
<p>Nothing published yet.</p>
<?php else: ?>
<ul>
<?php foreach ($releases['server'] as $release): ?>
<li><a href="<?= e($release['href']) ?>" download><?= e(PLATFORMS[$release['platform']] ?? ucfirst($release['platform'])) ?> <?= e($release['arch']) ?><?php if (isset(ARCHES[$release['arch']])): ?> (<?= e(ARCHES[$release['arch']]) ?>)<?php endif; ?> v<?= e($release['version']) ?> — <?= e(human_size($release['size'])) ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

<?php $all = array_merge($releases['gui'], $releases['client'], $releases['server']); ?>
<?php if ($all !== []): ?>
<h2>SHA-256</h2>
<p>On Linux use <code>sha256sum &lt;file&gt;</code>. On Windows use <code>Get-FileHash &lt;file&gt;</code>.</p>
<p>Then simply check if the checksum matches with your file.</p>
<pre><?php
$sums = '';
foreach ($all as $release) {
    $sums .= $release['sha256'] . '  ' . $release['file'] . "\n";
}
echo e($sums);
?></pre>
<?php endif; ?>

<h2>Source</h2>
<p>Zagan-Bet is free software under the GNU GPL v3 or later. The source for these builds is at <a href="https://git.2137697.xyz/zagan-bet.git">https://git.2137697.xyz/zagan-bet.git</a>.</p>

<h2>Running it</h2>
<p>Desktop app on Linux:</p>
<pre><code>chmod +x zagan-bet-gui-*-linux-x86_64-install.sh
./zagan-bet-gui-*-linux-x86_64-install.sh</code></pre>
<p>Desktop app on Windows (PowerShell):</p>
<pre><code>powershell -ExecutionPolicy Bypass -File .\zagan-bet-gui-*-windows-x86_64-install.ps1</code></pre>
<p>The installers verify the SHA-256 before installing. You can also run the downloaded app directly.</p>
<p>Terminal client:</p>
<pre><code>chmod +x &lt;downloaded-client&gt;
./&lt;downloaded-client&gt;</code></pre>
<p>Server, first run creates <code>identity.p12</code>, <code>key.pem</code> and <code>cert.pem</code>:</p>
<pre><code>chmod +x &lt;downloaded-server&gt;
./&lt;downloaded-server&gt; --init
./&lt;downloaded-server&gt; -i 0.0.0.0 -p 11525</code></pre>

<p>Terminal client on Windows: run the <code>.exe</code> from Windows Terminal or another real terminal.</p>
<p>Run <code>help</code> inside the terminal client; the server binary supports <code>--help</code>.</p>
</body>
</html>