-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapi.php
More file actions
1898 lines (1622 loc) · 63.7 KB
/
api.php
File metadata and controls
1898 lines (1622 loc) · 63.7 KB
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// Client's endpoint for matters outside of a particular HeroWO game: obtaining list of maps, creating a new multi-player game, etc. Serves client's requests. Starts a Server-Sent Events server ("meta-server" in relation to HeroWO Node "servers").
//
// You may include api.php as a library but do not call do_...() functions
// in this case.
$keepCWD = true;
$apiTakeOver = count(get_included_files()) < 2;
require_once __DIR__.'/core.php';
spl_autoload_register(function ($class) {
if (ltrim($class, 'A..Za..z0..9\\') === '' and !strncmp('Phiws\\', $class, 6)) {
require_once __DIR__.'/Phiws/'.strtr($class, '\\', '/').'.php';
}
});
// We could require databank/core.php but we only need this constant and it's
// better to keep code of databank and game client separate in case they do
// have to be separated in the future (e.g. to move to another repository).
preg_match('~^ const FORMAT_VERSION = (\\d+);~mu',
file_get_contents(__DIR__.'/databank/core.php'), $match);
define('FORMAT_VERSION', (int) $match[1]);
// api.php supports two interfaces: HTTP and CLI.
define('CLI', !strncmp(PHP_SAPI, 'cli', 3));
//Phiws\Logger::defaultMinLevel('info');
//Phiws\Loggers\InMemory::$dumpOnShutdown = true;
$dpp = new Phiws\Plugins\DataProcessorPicker;
$dpp->proc(Phiws\DataProcessors\BufferAndTrigger::class)->whenIsText();
Phiws\BaseTunnel::globalPlugins([new Phiws\Plugins\UserAgent, $dpp]);
// For HeroWO, GoingAway is a normal termination but Phiws treats
// non-NormalClosure as a warning (BaseTunnel->sendClose()), spamming in the log.
class Drop extends Phiws\StatusCodes\NormalClosure {
const CODE = Phiws\StatusCodes\GoingAway::CODE;
const TEXT = Phiws\StatusCodes\GoingAway::TEXT;
}
class PublicException extends Exception {}
// Called if api.php is the main script invoked by HTTP or CLI, not as library.
function apiTakeOver(array $argv) {
try {
if (CLI) {
define('ADMIN', true);
$do = $argv[1] ?? '';
$request = json_decode($argv[2] ?? '[]', true);
if (!is_array($request) and is_file($file = __DIR__.'/noXXXep/noXXXep.php')) {
try {
include_once $file;
$request = json_decode(noXXXep::extractJSON($argv[2]), true);
} catch (Throwable $e) {}
}
if (!is_array($request)) {
throw new Exception("Cannot parse arguments $argv[2]: ".json_last_error_msg());
}
} else {
$request = $_REQUEST;
$do = $request['do'] ?? null;
unset($request['do']);
define('ADMIN', isset($request['admin']) and hash_equals(keyValue('admin'), $request['admin']));
unset($request['admin']);
header('Content-Type: text/plain; charset=utf-8');
// No reason to support preflighted requests.
header('Access-Control-Allow-Origin: *');
}
function_exists($func = "do_$do") or $func = 'do_help';
$json = $func($request);
if ($json !== null) {
header('Content-Type: application/json; charset=utf-8');
echo encodeJsonLine($json);
}
} catch (Throwable $e) {
$public = $e instanceof PublicException;
$code = $public ? $e->getCode() ?: 400 : 500;
http_response_code($code);
if ($admin = (defined('ADMIN') and ADMIN) or $public) {
$admin or $e = $e->getMessage();
// We don't know which Content-Type was emitted so making it HTML-safe,
// at the same time allowing better human readability in case it's plain/text.
CLI ? fwrite(STDERR, $e.PHP_EOL) : print("<pre>\n".str_replace('<', '<', $e));
} else {
try {
mailAdmin('apiex', get_class($e).' in api.php', $e);
} catch (Throwable $e) {}
}
}
$code = http_response_code();
if (CLI) {
if ($code >= 200 and $code < 300) {
$code > 200 and fwrite(STDERR, 'Exit code: '.$code.PHP_EOL);
$code = 0;
}
exit($code);
} elseif ((!$code or $code === 200) and !headers_sent() and !ob_get_length()) {
http_response_code(204);
}
}
// Returns value for configuration parameter $key.
function keyValue($key) {
global $keyValueOverrides;
$res = $keyValueOverrides[$key] ?? null;
if (isset($res)) {
return $res;
}
$key = pdo()->quote($key);
$res = pdo("SELECT value FROM keyValues WHERE `key` = $key");
if (!$res) {
throw new Exception("Undefined keyValues key: $key");
}
return $res->value;
}
// Common CSS styles for HTML pages generated by api.php.
function apiStylesheet() {
return <<<CSS
body { background: #fafafa; font-family: sans-serif; }
.hi, mark { background: orange; }
.lo, th { background: #eee; }
/* For td.hi color the border so adjacent td.lo's outline looks nicer. */
.hi { border-color: orange; }
.lo { outline: 0.06em solid orange; outline-offset: -0.06em; }
table { margin: 1em 0; background: white; border-collapse: collapse; }
th, td { border: .06em solid #ddd; padding: .25em .5em; }
CSS;
}
// Fails if $path doesn't exist.
function realpathOrFail($path) {
if ($path = realpath($path)) {
return $path;
} else {
throw new Exception("Path does not exist: $path");
}
}
// Returns array with info about a map uploaded using maps.php (in particular, statistics like last play time).
//
// $mapPath must be safe. Does not clear stat/realpath caches.
//
// Trivia: PHP has 3 types of caches relevant to our cause: stat() cache
// (per-request; affects functions like include and filemtime()), "realpath"
// cache (per-process; affects the same file functions; holds only 'is_dir' and
// 'realpath' values as seen in realpath_cache_get()) and opcache (per-process;
// affects include).
//
// Do opcache_invalidate() before reading data *.php files (upload.php).
// Do clearstatcache() before reading attributes of a file whose attributes
// were already read during this request. Ignore realpath cache for simplicity
// because we do not expect symlinks among our data files.
//
// Thankfully, opcache_invalidate() does not rely on stat cache so there's no need
// to clearstatcache() before calling it even if the file's time has changed.
function uploadInfo($mapPath) {
$file = "$mapPath/upload.php";
// Doesn't want canonicalized path, unlike clearstatcache().
function_exists('opcache_invalidate') and opcache_invalidate($file);
try {
return include $file;
} catch (Throwable $e) {}
}
// Connects to the database holding api.php configuration and other stuff.
function pdo($query = null) {
static $pdo;
static $driver;
if (!$pdo) {
// This file needs to be created for every installation. For development and
// (very) small servers, zero-configuration SQLite database is the best
// choice (but ensure this file cannot be downloaded via the web server!).
//
// <?php return new PDO('sqlite:/var/herowo.sqlite');
//
// If you experience lockups (such as do=watchdog pausing when you are
// browsing do=dashboard), switch to a proper engine of your choice.
// HeroWO's SQL usage is rudimentary and easily portable, albeit there is
// no such thing as standard SQL.
//
// <?php return new PDO('mysql:host=localhost;dbname=herowo');
//
// You can also override some `keyValues` such as based on request data:
//
// $keyValueOverrides['production'] = $_SERVER['HTTP_HEADER'] ...;
//
// Note: CWD inside this script may have arbitrary value.
$pdo = require __DIR__.'/api-db.php';
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$driver = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
$driver === 'sqlite' and $pdo->exec('PRAGMA foreign_keys = ON');
// Known keyValues keys:
// - admin - the ?admin=SECRET value
// - path - HeroWO WebSocket server -path (e.g. "v1")
// - sseURL - space-separated public-facing URLs of meta-servers' EventSource;
// relative; any valid URL (allows https://, ?query, etc.)
// - maps - path to the directory with HeroWO maps, relative to __DIR__;
// on Windows, must not resolve to a drive root ("C:\") because it will
// have "\" appended, breaking our realpath detection ("C:\\");
// map folders will have upload.php files that the webserver should
// not serve to clients
// - mapsURL - space-separated public URL prefixes, relative;
// use multiple to load-balance (client receives one depending on IP)
// - databanks - like maps but points to the directory with db-ver/*.json
// - databanksURL - space-separated public URL prefixes; relative
// - databank - subfolder in databanks|URL; for converting maps and for MainMenu
// - apiURL - public URL to api.php; relative
// - production - 1 = online server for end users; 0 = local development
// machine; -1 = online server for modders; both 0 and -1 allow custom
// modules, use non-minified build, etc. but 0 additionally preloads
// databank styles (see index.php)
//
// "Relative" URLs are relative to folder URL of api.php/index.php/maps.php.
//
// On the webserver's side, enable gzip on sseURL, mapsURL and databanksURL. Brotli
// gives better compression but may be slower. For mapsURL/databanksURL,
// enable CORS via A-C-A-O if they are not on index.php's domain.
// databanksURL is also used for static files (DEF-PNG, etc.); they don't
// require CORS except for audio files (if WebAudio is used) and
// $databanksURL/$databank/herowo.min.js (due to <script crossorigin>).
//
// It is worth placing maps and databanks folders onto a transparently
// compressing FS since they consist of very large JSONs that can be
// compressed down to <5%. BTRFS and ZFS are good options:
//
// mount -o compress-force=zstd /dev/$btrfs /var/herowo/maps
//
// Use compsize to see compression statistics. If zstd is unavailable or
// slow, try lzo (its compression ratio is about 2X worse than zstd's).
//
// If you have many duplicate maps (possibly because users upload them),
// see if deduplication helps (it may have no or negative effect because
// of inflated file meta-data). BTRFS only supports on-demand deduplication;
// you can cron duperemove to trigger it:
//
// duperemove -rd /var/herowo/maps
//
// If you allow map uploads (maps.php), set PHP's sys_temp_dir to a similar
// FS, or to a ZRAM disk if you have a lot of RAM:
//
// modprobe zram
// zramctl -f -s 8G
// mkfs.xfs /dev/zram0
// mount /dev/zram0 /var/herowo/tmp
//
// Run zramctl to see disk info. Note: ZRAM won't allow writing files whose
// total uncompressed size is more than -s bytes. In other words, -s is not
// the limit on RAM used. On the other hand, BTRFS' limit is expectedly
// calculated from compressed size (i.e. actually stored blocks on disk).
//
// Rarely accessed maps (backups) can be converted to a binary format. For
// example, CBOR takes 25% of non-pretty printed JSON. Compressing CBOR is
// also advantageous (gzip gives 80% of the same compressed JSON).
$INSERT_OR_IGNORE = pdo('INSERT OR IGNORE');
$RANDOM_SECRET = pdo('RANDOM SECRET');
$AUTOINCREMENT = pdo('AUTOINCREMENT');
$sql = <<<SQL
CREATE TABLE IF NOT EXISTS keyValues (
`key` VARCHAR(50) NOT NULL PRIMARY KEY,
value TEXT
);
$INSERT_OR_IGNORE INTO keyValues (`key`, value)
VALUES
("admin", $RANDOM_SECRET),
("path", "v1"),
("sseURL", "http://127.0.0.1:8080"),
("maps", "maps"),
("mapsURL", "maps/"),
("databanks", "databanks"),
("databanksURL", "databanks/"),
("databank", "sod"),
("apiURL", "api.php"),
("production", 0);
CREATE TABLE IF NOT EXISTS secrets (
target VARCHAR(50) NOT NULL,
id VARCHAR(50) NOT NULL,
secret TEXT NOT NULL,
algorithm TEXT,
tagLength INT,
PRIMARY KEY (target, id)
);
CREATE TABLE IF NOT EXISTS servers (
id VARCHAR(50) NOT NULL PRIMARY KEY,
secret TEXT NOT NULL,
maxMemory INT NOT NULL,
accepting INT,
host VARCHAR(250) NOT NULL,
port INT NOT NULL,
secure INT,
serverStatsTime REAL,
totalClients INT,
lingering INT,
connected INT,
special INT,
pending INT,
lobby INT,
games INT,
memory INT,
pid INT,
uptime INT,
UNIQUE (host, port)
);
CREATE TABLE IF NOT EXISTS lobby (
server VARCHAR(50) NOT NULL,
pin VARCHAR(50) NOT NULL,
context TEXT NOT NULL,
time INT NOT NULL,
PRIMARY KEY (server, pin)
);
CREATE TABLE IF NOT EXISTS chat (
rowid $AUTOINCREMENT,
data MEDIUMTEXT NOT NULL
);
SQL;
// With SQLite, exec() works with semicolon-separated statements but I'm not
// sure how portable it is with other drivers.
foreach (explode(';', $sql) as $sql) {
trim($sql) and $pdo->exec($sql);
}
}
static $tokens = [
'INSERT OR IGNORE' => [
'sqlite' => 'INSERT OR IGNORE',
'mysql' => 'INSERT IGNORE',
],
'INSERT OR REPLACE' => [
'sqlite' => 'INSERT OR REPLACE',
'mysql' => 'REPLACE',
],
'RANDOM SECRET' => [
'sqlite' => 'HEX(RANDOMBLOB(8))',
'mysql' => 'HEX(RANDOM_BYTES(8))',
],
'AUTOINCREMENT' => [
'sqlite' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
'mysql' => 'INT AUTO_INCREMENT PRIMARY KEY',
],
];
if ($query === null) {
return $pdo;
} elseif ($token = $tokens[$query] ?? null) {
return $token[$driver];
} else {
$stmt = $pdo->query($query);
$res = $stmt->fetchObject();
$stmt->closeCursor();
return $res;
}
}
function do_help(array $request) {
$dos = [];
foreach (get_defined_functions()['user'] as $func) {
strncmp($func, 'do_', 3) or $dos[] = substr($func, 3);
}
sort($dos);
$dos = join(PHP_EOL.' ', $dos);
http_response_code(405);
echo <<<HELP
php api.php ACTION [ '{"arg": "uments"}' ]
http://.../api.php?admin=SECRET&do=ACTION&arg=uments
Known ACTION's:
$dos
HELP;
if (ADMIN) {
$secret = keyValue('admin');
echo "\n\nSECRET = $secret";
}
if (CLI and !strncasecmp(PHP_OS, 'win', 3)) {
echo "\n\nMake sure to triple \"s in Windows CLI (tailing \" is optional):";
echo "\n", ' php api.php keyValue "{"""newAdmin""": """SECRET"""}"';
}
if (is_file(__DIR__.'/noXXXep/noXXXep.php')) {
echo "\n\nAlternative syntax available (noXXXep's Easy JSON):";
echo "\n", ' php api.php keyValue "{newAdmin: SECRET}"';
}
echo PHP_EOL;
}
function do_mail(array $request) {
if (!ADMIN) {
throw new PublicException('Admin only.', 403);
}
mailAdmin($request['id'] ?? 'api', $request['title'] ?? 'api.php mail', $request['body']);
}
// [ {"set": "val", "set2": ...} ]
//
// Use the "newAdmin" key to change the ?admin's secret.
function do_keyValue(array $request) {
if (!ADMIN) {
throw new PublicException('Admin only.', 403);
}
if (isset($request['newAdmin'])) {
$request['admin'] = $request['newAdmin'];
unset($request['newAdmin']);
}
if ($request) {
$sql = [];
foreach ($request as $key => $value) {
$sql[] = ' ('.pdo()->quote($key).', '.pdo()->quote($value).')';
}
$sql = pdo('INSERT OR REPLACE')." INTO keyValues (`key`, value) VALUES ".join(',', $sql);
pdo()->exec($sql);
}
$query = pdo()->query('SELECT `key`, value FROM keyValues ORDER BY `key`');
while ($row = $query->fetchObject()) {
printf('%20s %s= %s%s',
$row->key,
array_key_exists($row->key, $request) ? ':' : ' ',
$row->value,
PHP_EOL);
}
}
// php api.php server {"id": "erathia", "secret": "H0tA", "maxMemory": 64, "host": "1.2.3.4"}
//
// api.php?do=server&admin=c001b00b5&id=erathia&accepting=1
function do_server(array $request) {
if (!ADMIN) {
throw new PublicException('Admin only.', 403);
}
if ($request) {
// PDO casts execute() arguments to strings (PARAM_STR) so false becomes ''.
// Most engines won't convert it to INT and will error (except SQLite which
// will simply store '' as a string).
isset($request['accepting']) and $request['accepting'] *= 1;
isset($request['secure']) and $request['secure'] *= 1;
$exists = pdo('SELECT 1 FROM servers WHERE id = '.pdo()->quote($request['id']));
if ($exists) {
$values = array_intersect_key($request, array_flip(['secret', 'maxMemory', 'accepting', 'host', 'port', 'secure']));
$fields = join(', ', preg_replace('/$/', ' = ?', array_keys($values)));
$stmt = pdo()->prepare("UPDATE servers SET $fields WHERE id = ?");
$stmt->execute(array_merge(array_values($values), [$request['id']]));
$stmt->closeCursor();
} else {
$request += ['port' => 8081, 'accepting' => -1];
$request += ['secure' => (int) ($request['port'] === 443)];
$stmt = pdo()->prepare('INSERT INTO servers (id, secret, maxMemory, accepting, host, port, secure) VALUES (?, ?, ?, ?, ?, ?, ?)');
$stmt->execute([$request['id'], $request['secret'], $request['maxMemory'], $request['accepting'], $request['host'], $request['port'], $request['secure']]);
$stmt->closeCursor();
http_response_code(201);
}
}
$query = pdo()->query('SELECT * FROM servers ORDER BY id');
while ($row = $query->fetchObject()) {
printf('%-15s %s %3s: up=%s mem=%d/%dM conn=%d lobby=%d games=%d PID=%d %s',
$row->id,
[-1 => '#', '-', '+'][$row->accepting],
($diff = microtime(true) - $row->serverStatsTime) > 3600 ? round($diff / 3600).'h' : round($diff),
$row->uptime > 12 * 3600 ? round($row->uptime / 3600 / 24).'d' : round($row->uptime / 3600, 1).'h',
$row->memory,
$row->maxMemory,
$row->connected,
$row->lobby,
$row->games,
$row->pid,
PHP_EOL);
printf('%18s %s%s',
wss($row),
$row->secret,
PHP_EOL);
}
}
// [ {"target": "save|replay", "id": "20220411", "secret": "abc..."} ]
function do_secret(array $request) {
if (!ADMIN) {
throw new PublicException('Admin only.', 403);
}
if ($request) {
$algo = $request['algorithm'] ?? ($request['target'] === 'replay' ? 'sha256' : 'aes-256-gcm');
if (!strncasecmp($algo, 'aes', 3) and strlen($request['secret']) !== $len = openssl_cipher_iv_length($algo)) {
throw new Exception("secret must be exactly $len bytes for $algo, not ".strlen($request['secret']));
}
$stmt = pdo()->prepare(pdo('INSERT OR REPLACE').' INTO secrets (target, id, secret, algorithm, tagLength) VALUES (?, ?, ?, ?, ?)');
$stmt->execute([$request['target'], $request['id'], $request['secret'], $algo, $request['tagLength'] ?? 16]);
$stmt->closeCursor();
}
$query = pdo()->query('SELECT * FROM secrets ORDER BY target, id');
while ($row = $query->fetchObject()) {
printf('%-8s %10s %s= %-32s (%s, tag %d)%s',
$row->target,
$row->id,
($row->target === ($request['target'] ?? '') and $row->id === $request['id'])
? ':' : ' ',
$row->secret,
$row->algorithm,
$row->tagLength,
PHP_EOL);
}
}
class JsonrpcException extends Exception {}
abstract class JsonrpcData extends Phiws\StatefulPlugin {
const LOGIN = 1;
static function request($cx, $id, $method, array $params = []) {
$jsonrpc = '2.0';
$data = compact('jsonrpc', 'method', 'params');
isset($id) and $data['id'] = $id;
$cx and $cx->queueJsonData($data);
return $data;
}
function events() {
return ['bufferedFrameComplete'];
}
function bufferedFrameComplete($cx, $applicationData = null, $extensionData = null) {
$resp = json_decode($applicationData->readAll());
$this->request($cx, null, 'ack', ['id' => $resp->id]);
if (($resp->event ?? null) === 'jsonrpc') {
$batch = is_array($resp->data) ? $resp->data : [$resp->data];
foreach ($batch as $data) {
if (($data->jsonrpc ?? null) !== '2.0') {
throw new JsonrpcException('Bad jsonrpc value: '.($data->jsonrpc ?? null));
}
if (property_exists($data, 'error')) {
throw new JsonrpcException($data->error->message ?? 'Unspecified error.', $data->error->code ?? 0);
}
}
$this->jsonrpcBatch($cx, $batch);
}
}
// Is allowed to throw.
//
// Members in $batch were validated for JSON-RPC format and lack of 'error'.
// They may go in any order, not necessary in the original request's order.
protected function jsonrpcBatch($cx, array $batch) {
foreach ($batch as $data) {
switch ($data->id) {
default:
$this->jsonrpc($cx, $data->id, $data->result);
case static::LOGIN: // commonly used so handled in the base class
}
}
}
// Is allowed to throw.
abstract protected function jsonrpc($cx, $id, $result);
}
// Returns fully-qualified URL of the WebSocket $server (row from servers table).
function wss(stdClass $server) {
return sprintf('%s://%s:%d/%s',
$server->secure ? 'wss' : 'ws',
$server->host,
$server->port,
keyValue('path'));
}
// Returns a new Phiws\Client instance connected to $server (row from servers table).
function connectTo(stdClass $server) {
$addr = new Phiws\ServerAddress($server->host, $server->port);
$addr->secure($server->secure);
$addr->path(keyValue('path'));
$client = new Phiws\Client;
// Subject to minLevel().
CLI and $client->logger()->echoMode(true);
$client->connect($addr);
return $client;
}
// crontab -e
// @daily /bin/bash -c 'php /.../api.php dashboard | sendmail root@localhost'
function do_dashboard(array $request) {
if (!ADMIN) {
throw new PublicException('Admin only.', 403);
}
$loHiClass = function ($value, $min, $max = PHP_INT_MAX) {
return $value < $min ? 'lo' : ($value > $max ? 'hi' : null);
};
$loHi = function ($value) use ($loHiClass) {
return ' class="'.$loHiClass(...func_get_args()).'">'.
htmlspecialchars($value ?? '');
};
$ago = function ($seconds) {
return $seconds === null ? '' :
($seconds < 50 ? round($seconds, 1) :
($seconds < 50 * 60 ? round($seconds / 60).'m' :
($seconds < 24 * 3600 ? round($seconds / 3600).'h' :
round($seconds / 24 / 3600).'d')));
};
$isListening = function ($host, $port) {
$time = microtime(true);
try {
fclose(fsockopen($host, $port, $errno, $error, 2));
$open = true;
} catch (Throwable $e) {}
return [!empty($open), microtime(true) - $time];
};
// Diagona Icons (CC-BY 3.0) | pinvoke.com | https://p.yusukekamiyamane.com
// oxipng -omax --strip all -a -Z 16/148.png 16/152.png 16/156.png
$icons = [
'red' => 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAgVBMVEX/////qoj/ZkT9Y0H5Xz3/VTPSKQfOJQPMIgD/ZkT2WjjVLgzMIgD/qoj/pYP/n33/l3X9k3H/jmz+h2X/hGL7fVv/e1n/cU//aEb/ZkT9Y0H/YD75Xz3/Wjj/VTPxVDL0TiztTizqRyXoRyXjQR/nPRveOhjaNBLSKQfOJQPMIgBY0iR1AAAADXRSTlMAAAAAAAAAAAC/v7+/XtiDwwAAAHJJREFUeNplyAMSA0EABdG1bVuT+x8wP9zBK3W1JFIUxa7fbCSGKjep/5Y2soqhdXHwFXcahpOHf7mDMUaUEWNOKDPGmlFWjK2gbBhHSTkwzopyYrhL+7e4GMY19V/TZWCYOtmHt53oJoZlWd7jzUNKgieViBAPbN/HxwAAAABJRU5ErkJggg==',
'green' => 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAyVBMVEX///+I7ohVu1VEqkRCqEI+pD4XfRcTeRMRdxFEqkQ7oTsagBoRdxFCqEI+pD4XfRcTeRNEqkQ2nDYfhR8RdxFEqkQymDIjiSMRdxFHrUdApkAfhR8YfhiI7oiF64WB54F84nx43nh33Xd123Vy2HJv1W9u1G5ozmhnzWdhx2FexF5WvFZVu1VUulRTuVNSuFJRt1FPtU9Ns01LsUtKsEpIrkhHrUdGrEZFq0VEqkQ8ojw7oTs5nzkzmTMwljAtky0ojigjiSMRdxHZiKCbAAAAHXRSTlMAAAAAAAAAAAAqKioqZWVlZYKCgoLOzs7O5+fn58De1a8AAACrSURBVHjaZMgDcsUAAAbhZztGGdt27n+o/rV2tPNN/jefz7dXqiio6xYLWEyPnPF0d/dkcMfpArA8RfL9W3J0WgJ2vPrwkcrvADf78Sv7BqB16fkjSacBnZf6pqYomumnXgfog7r5qA56AGOl1UepxQCI0kuKtxKvJAB7IXaDEAVuLOwBq/OQ2Y7rOnY2nFeA9ewitrlt5614ma0Bm83mQLLjyJIH7MswPQ8AhSAbM24sPI8AAAAASUVORK5CYII=',
'yellow' => 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAA1VBMVEX/////zGb/mQD9lwD5kwDSbADOaADMZgD/mQD2kADVbwDMZgD9lwD5kwDSbADOaAD/mQDxiwDadADMZgD/mQDthwDeeADMZgD9mwf3lAbYcgHRawD/zGb/yWD/xVj/wE//wE7/u0T/ukL9ukb9t0D+szf7rzT9rjH+ri36pyf3oiP3nhr2nhz6nRL2nBb7mwv5mw/+mgb9mgX/mQD9mQX5mAn5lwn0lxP2lQv1lQ30kwr0kwnzjwTzjQDxjQXwjQXqigruiADoggDkfgDjfQDadQHMZgD4TUsyAAAAHHRSTlMAAAAAAAAAACoqKiplZWVlgoKCgs7Ozs7n5+fnGavOOgAAAK1JREFUeNpkyANyBAEABdGsbVtj29b9j5QfY7vU9V6eq9fr3elS15fTLhbQqA23zPV4vDLbYa0BaI7Ex+m9hzhqAno74vwZsesBZtzlO24GWFH322d3agXIBFtgaZKkWUwGKKQ4/SyWCsCad6PPXH4NmCeK47/nKMkc0N97smkhU/b2fUBrXAaqZhiaGpTjFqBdnxzyUNfD/DCptwGdTmew2FTV68SFuYFMTM8DAG1rG4nL3dGaAAAAAElFTkSuQmCC',
];
$secret = keyValue('admin');
$path = '/'.keyValue('path');
$keyValues = pdo()->prepare('SELECT `key`, value FROM keyValues ORDER BY `key`');
$servers = pdo()->prepare('SELECT * FROM servers ORDER BY id');
$onlineServersStmt = pdo()->prepare("SELECT COUNT(1) FROM servers WHERE accepting = 1 AND serverStatsTime > ? - 1.0");
$serverTotalsStmt = pdo()->prepare('SELECT SUM(lingering) lingering, SUM(connected) connected, SUM(lobby) lobby, SUM(games) games FROM servers');
if (empty($request['sse'])) {
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
<title>HeroWO Servers Dashboard</title>
<style>
<?=apiStylesheet()?>
body:not(.sse_timeout) .sse__timeout { display: none; }
.sse__timeout { background: orange; padding: 1em; }
.accepting_0 { outline: 0.06em solid orange; text-decoration: line-through; }
.online_0 { background: #eee; }
[colspan] > * { margin-right: 1em; }
</style>
</head>
<body>
<script>
function sseInfo(url) {
;(new EventSource(url))
.addEventListener('full', function (e) {
this.close()
// Use Firefox to see the result nicely formatted.
var win = open('data:application/json;charset=utf-8,' + encodeURIComponent(e.data))
if (!win) {
alert('Got spanked by your browser for trying to open a new tab with statistics.')
} else if (navigator.userAgent.match(/WebKit/)) {
// Chrome seems to always open about:blank from open() or <a>
// even though it works if you type in the URL directly.
win.document.write('<pre style="white-space: pre-wrap">')
win.document.write(e.data
.replace(/&/g, '&')
.replace(/</g, '<'))
win.document.close()
}
})
}
// Don't change HTML while user is clicking to avoid ignoring that click
// or making selection impossible.
var down
document.body.addEventListener('mousedown', function () { down = true })
document.body.addEventListener('mouseup', function () { down = false })
addEventListener('DOMContentLoaded', function () {
var ping = 0
var es
setInterval(function () {
if (ping + 10000 < Date.now()) {
document.body.classList.add('sse_timeout')
down = false
es.close()
start()
}
}, 10000)
function start() {
es = new EventSource(<?=escapeHtmlScriptJSON(encodeJsonLine('?'.http_build_query(['do' => 'dashboard', 'admin' => $secret, 'sse' => true])))?>)
es.onmessage = function (e) {
if (!down) {
ping = Date.now()
document.body.innerHTML = e.data
document.body.classList.remove('sse_timeout')
}
}
}
start()
})
</script>
<?php
} else {
header('Content-Type: text/event-stream; charset=utf-8');
header('X-Accel-Buffering: no');
ob_start(function ($buf, $phase) {
$buf = 'data:'.str_replace("\n", "\ndata:", $buf);
// NB: strange stuff, PHP_OUTPUT_HANDLER_WRITE == 0 but how can such a
// value be part of a bitmask?
if ($phase & PHP_OUTPUT_HANDLER_FLUSH) {
// End of SSE message. It's okay if we accidentally emit more than two
// consecutive \n.
$buf .= "\n\n";
}
return $buf;
});
}
for ($iteration = +empty($request['sse']) ?: -1; $iteration--; ) {
if ($iteration !== 0 /*first non-?sse=1 iteration*/ and $iteration !== -2 /*first ?sse*/) {
sleep(1);
}
$time = microtime(true);
$onlineServersStmt->execute([$time]);
$onlineServers = $onlineServersStmt->fetchColumn();
$onlineServersStmt->closeCursor();
$serverTotalsStmt->execute();
$serverTotals = $serverTotalsStmt->fetchObject();
$serverTotalsStmt->closeCursor();
?>
<p class="sse__timeout">
Data on this page is stale because the server
is taking too long to send an update.
</p>
<h2>Key/Values</h2>
<table>
<?php $keyValues->execute()?>
<?php while ($row = $keyValues->fetchObject()) {?>
<tr>
<th><?=htmlspecialchars($row->key)?></th>
<td><?=htmlspecialchars($row->value)?></td>
</tr>
<?php }?>
</table>
<h2>Servers</h2>
<table>
<tr>
<th>Game Servers</th>
<th>Lobbies</th>
<th>Games</th>
<th>Game Clients</th>
<th>SSE Clients</th>
</tr>
<tr>
<td <?=$loHi($onlineServers, 3)?></td>
<td <?=$loHi($serverTotals->lobby, 3, 10)?></td>
<td <?=$loHi($serverTotals->games, 3, 10)?></td>
<td class="<?=$loHiClass($serverTotals->connected + $serverTotals->lingering, 5, 20)?>">
<?=htmlspecialchars("$serverTotals->connected+$serverTotals->lingering")?>
</td>
<?php
$offline = $slow = false;
$counts = [];
foreach (explode(' ', keyValue('sseURL')) as $i => $url) {
$addr = parse_url($url);
$secure = $addr['scheme'] === 'https';
$addr += ['port' => $secure ? 443 : 80];
[$online, $est] = $isListening($addr['host'], $addr['port']);
$offline |= !$online;
$slow = $est > 0.1;
$counts[] = '?';
if ($online) {
try {
$f = fsockopen($addr['host'], $addr['port'], $error, $errno, 0.2);
try {
$secure and stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT);
$s = "GET /?admin=".rawurlencode($secret)." HTTP/1.1\r\n".
"Host: $addr[host]\r\n".
"Accept: text/event-stream\r\n".
"\r\n";
fwrite($f, $s);
while (fgets($f) !== "\r\n") ; // HTTP/1.1 200 OK ... blank
$count = fgets($f); // body
is_numeric($count) and $counts[$i] = $count;
} finally {
fclose($f);
}
} catch (Throwable $e) {}
}
}
$class = [];
$offline and $class[] = 'accepting_0 online_0';
$slow and $class[] = 'lo';
foreach ($counts as $count) {
$class[] = $loHiClass($count, 10, 100);
}
echo '<td class="', join(' ', $class), '">';
echo join('+', $counts);
$offline and print(' (offline)');
$slow and print(' (slow conn)');
echo '</td>';
?>
</tr>
</table>
<p>
<a href="#" onclick="sseInfo(<?=htmlspecialchars(encodeJsonLine(strtok(keyValue('sseURL'), ' ')))?>); return false">
Games & Maps
</a>
</p>
<table>
<thead>
<tr>
<th>ID</th>
<th>State</th>
<th>URL</th>
<th>Secret</th>
<th>Free Mem</th>
<th>Updated</th>
<th>Seen Clients</th>
<th>Lingering</th>
<th>Connected</th>
<th>Special</th>
<th>Pending Commands</th>
<th>Lobby</th>
<th>Games</th>
<th>PID</th>
<th>Uptime</th>
</tr>
</thead>
<tbody>
<?php $servers->execute()?>
<?php while ($row = $servers->fetchObject()) {?>
<?php
[$online, $est] = $row->accepting < 0 ? [0, 0]
: $isListening($row->host, $row->port);
$class = ['accepting_'.+!!$row->accepting, 'online_'.+$online];
?>
<tr class="<?=join(' ', $class)?>">
<th rowspan="2">
<img src="data:image/png;base64,<?=htmlspecialchars($icons[$online ? $row->accepting ? 'green' : 'yellow' : 'red'])?>">
<?=htmlspecialchars($row->id)?>
</th>
<td class="<?=$loHiClass($est, 0, 0.1)?>">
<?=$row->accepting < 0 ? 'Masked' : (!$online ? 'Offline' : ($row->accepting ? 'Accepting' : 'Draining').($est > 0.1 ? ' (slow conn)' : ''))?>
</td>
<td>
<?=htmlspecialchars(wss($row))?>
</td>
<td><?=htmlspecialchars($row->secret)?></td>
<td <?=$loHi($row->maxMemory - $row->memory, 64, $row->maxMemory * 0.3)."/{$row->maxMemory}M"?></td>
<td class="<?=$row->serverStatsTime ? $loHiClass($diff = $time - $row->serverStatsTime, 0, 0.5) : 'lo'?>">
<?=$row->serverStatsTime ? $ago($diff) : ''?>
</td>
<td <?=$loHi($row->totalClients, 100, 10000)?></td>
<td <?=$loHi($row->lingering, 0, 20)?></td>
<td <?=$loHi($row->connected, 5, 20)?></td>
<td><?=htmlspecialchars($row->special ?? '')?></td>
<td <?=$loHi($row->pending, 0, 10)?></td>
<td <?=$loHi($row->lobby, 1, 5)?></td>
<td <?=$loHi($row->games, 1, 5)?></td>
<td><?=htmlspecialchars($row->pid ?? '')?></td>
<td class="<?=$loHiClass($row->uptime, 60, 30 * 24 * 3600)?>">
<?=$ago($row->uptime)?>
</td>
</tr>
<tr>
<td colspan="13">
<a href="#" onclick="prompt('websocket.js options:', <?=htmlspecialchars(encodeJsonLine("-console connect -host $row->host -port $row->port".($row->secure ? ' -secure' : '')." -path ".escapeshellarg($path)." -admin ".escapeshellarg($row->secret)))?>); return false">
Connection String</a>
<?php if ($online) {?>
<a target="_blank" href="<?=htmlspecialchars('?'.http_build_query(['do' => 'dashboardInfo', 'admin' => $secret, 'info' => 'contextStats', 'server' => $row->id]))?>">
Context Stats</a>
<a href="#" onclick="(new Image).src = <?=htmlspecialchars(encodeJsonLine('?'.http_build_query(['do' => 'server', 'admin' => $secret, 'id' => $row->id, 'accepting' => !$row->accepting])))?>; this.innerHTML += '...'; return false">
<?=$row->accepting ? 'Stop Accepting' : 'Start Accepting'?></a>
<?php }?>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
ob_get_level() and ob_flush();
flush();
}
}
function do_dashboardInfo(array $request) {
if (!ADMIN) {
throw new PublicException('Admin only.', 403);
}
switch ($request['info']) {
default:
throw new PublicException('Bad ?info: '.$request['info']);
case 'contextStats':
$server = pdo('SELECT host, port, secure, secret FROM servers WHERE id = '.pdo()->quote($request['server']));
$client = connectTo($server);
$client->plugins()->add($dd = new DashboardData);
$dd->request($client, $dd::LOGIN, 'admin', ['secret' => $server->secret]);
$dd->request($client, $dd::STATS, 'contextStats');
$client->loop();
return $dd->result;
}
}
class DashboardData extends JsonrpcData {
const STATS = 2;
public $result;
protected function jsonrpc($cx, $id, $result) {
switch ($id) {
default:
throw new JsonrpcException("Bad response \$id: $id");
case static::STATS:
$this->result = $result;
$cx->gracefulDisconnectAndWait(null, new Drop);
break;
}
}
}
// {"url": "User/Map/Path", "private": true}
//
// In multipart/form-data mode, ?url may be replaced by ?load (a binary file
// upload or a regular parameter, base64-encoded).