-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.php
501 lines (415 loc) · 13.1 KB
/
core.php
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
<?php
declare(strict_types=1);
// Helpers
class QuasselHelper {
// Session deadlock prevention
public static function killSession() {
session_start(["cookie_lifetime" => 86400, "read_and_close" => true]);
}
// Read file by handle to eof
public static function readFullFile(mixed $file) : string {
$data = "";
while (!feof($file)) {
$data .= fread($file, 8192);
}
return $data;
}
// Read file from standard input
public static function readPutFile() : string {
$file = fopen("php://input", "r");
if ($file===false) {
return "";
}
$data = QuasselHelper::readFullFile($file);
fclose($file);
return $data;
}
// Common hash function here
public static function hash(string $node) : string {
return hash("sha256", $node, true, []);
}
// Build unique node ID
public static function uniqueID() : string {
return bin2hex(QuasselHelper::hash(strval(time())."_".random_bytes(64)));
}
}
// Physical storage of nodes (on disk/per file at the moment)
class QuasselDataStore {
public $directoryLevels;
public $storeDirectory;
public function __construct() {
$this->directoryLevels = 4;
$this->storeDirectory = "store/";
}
public function __destruct() {
}
// Update node index or data
public function update(string $data) : bool {
$rpc = json_decode($data, true);
if (isset($rpc["node"]) && isset($rpc["type"]) && isset($rpc["chat"])) {
$file = $this->openFile($rpc["chat"]."_".$rpc["node"], "c+");
if ($file===false) {
return false;
}
// TODO: Lock upgradable (from shared to exclusive)?
flock($file, LOCK_EX);
$stored = QuasselHelper::readFullFile($file);
$stored = json_decode($stored, true);
if (!isset($stored)) {
$stored = array();
}
$result = $this->merge($stored, $rpc);
if (!empty($result)) {
fseek($file, 0, SEEK_SET);
fwrite($file, json_encode($result));
ftruncate($file, ftell($file));
fflush($file);
}
flock($file, LOCK_UN);
fclose($file);
}
return true;
}
// Return updates or wait if no updates are available
public function poll(string $data) : string {
$result = "";
$rpc = json_decode($data, true);
if (isset($rpc["node"]) && isset($rpc["type"]) && isset($rpc["chat"])) {
$file = $this->openFile($rpc["chat"]."_".$rpc["node"], "r+");
if ($file===false) {
return "";
}
$count = 0;
while (true) {
if ($count==60) {
return "";
}
$count++;
flock($file, LOCK_SH);
fseek($file, 0, SEEK_SET);
$stored = QuasselHelper::readFullFile($file);
$stored = json_decode($stored, true);
if (!isset($stored)) {
$stored = array();
}
$result = $this->index($stored, $rpc);
flock($file, LOCK_UN);
if ($rpc["type"]!==$result["type"]) {
return "";
}
$uid = $result["uid"];
if ((!isset($rpc["uid"]) || $rpc["uid"]!==$uid)) {
$result["timestamp"] = time();
if ($result["type"]==="data") {
} elseif ($result["type"]==="index") {
$result["uid"] = $uid;
if (isset($rpc["uid"])) {
$needed = $rpc["uid"];
$messages = array_keys($result["messages"]);
foreach ($messages as $message) {
if (!isset($result["messages"][$message]["uid"]) || $result["messages"][$message]["uid"]<=$needed) {
unset($result["messages"][$message]);
}
}
}
} else {
return "";
}
break;
}
// TODO: dirty! Use some kind of synchronization here in future (at best conditional variables or socket_pair?)
sleep(1);
}
fclose($file);
}
return json_encode($result);
}
// Merge incoming data with on disk data
public function merge(array &$stored, array $rpc) : array {
if (isset($stored["type"])) {
if ($stored["type"]!==$rpc["type"]) {
error_log("type mismatch on store merge");
return array();
}
} else {
$stored["type"] = $rpc["type"];
}
if (isset($stored["chat"])) {
if ($stored["chat"]!==$rpc["chat"]) {
error_log("chat mismatch on store merge");
return array();
}
} else {
$stored["chat"] = $rpc["chat"];
}
if (isset($stored["uid"])) {
$stored["uid"]++;
} else {
$stored["uid"] = 1;
}
if ($stored["type"]==="index") {
if (isset($rpc["append"])) {
$id = $rpc["append"];
if (!isset($stored["messages"]) || !is_array($stored["messages"])) {
$stored["messages"] = array();
}
foreach ($stored["messages"] as $message) {
if ($message["id"]===$id) {
return array();
}
}
array_push($stored["messages"], array("id" => $id, "uid" => $stored["uid"], "timestamp" => time()));
}
} elseif ($stored["type"]==="data") {
if (isset($rpc["data"])) {
$stored["data"] = $rpc["data"];
}
}
return $stored;
}
// Update index (design?)
public function index(array $stored, array $rpc) : array {
if (isset($stored["type"])) {
if ($stored["type"]!==$rpc["type"]) {
error_log("type mismatch on store index");
return array();
}
}
if (isset($stored["chat"])) {
if ($stored["chat"]!==$rpc["chat"]) {
error_log("chat mismatch on store index");
return array();
}
}
return $stored;
}
// Open storage file
public function openFile(string $fileName, string $mode) : mixed {
$complete = $this->storeDirectory;
$n = 0;
// TODO: Insert Unicode checks here if filesystem supports unicode/utf8
$length = strlen($fileName);
while ($n<$length-1 && $n<$this->directoryLevels) {
$complete .= $fileName[$n].DIRECTORY_SEPARATOR;
$n++;
}
$complete .= substr($fileName, $n);
error_log($complete);
if ($mode=="c+") {
$dirname = dirname($complete);
if (!is_dir($dirname) && !mkdir($dirname, 0777, true)) {
return false;
}
}
return fopen($complete, $mode);
}
}
// Virtual storage over multiple instances
class QuasselWebStore {
public function __construct() {
}
public function __destruct() {
}
// Store data to multiple instances
public function store(array $servers, array $data) : bool {
$multi = curl_multi_init();
$requests = array();
foreach ($servers as $url => $dht) {
$request = json_encode($data);
$requests[$url] = curl_init();
curl_setopt($requests[$url], CURLOPT_RETURNTRANSFER, true);
curl_setopt($requests[$url], CURLOPT_URL, "http://".$url."/store.php");
curl_setopt($requests[$url], CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($requests[$url], CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Length: ".strlen($request)));
curl_setopt($requests[$url], CURLOPT_POSTFIELDS, $request);
curl_multi_add_handle($multi, $requests[$url]);
}
while (true) {
$status = curl_multi_exec($multi, $active);
if ($active) {
curl_multi_select($multi);
}
while (true) {
$info = curl_multi_info_read($multi);
if ($info===false) {
break;
}
}
if (!$active || $status!=CURLM_OK) {
break;
}
}
$done = true;
foreach ($servers as $url => $dht) {
$content = curl_multi_getcontent($requests[$url]);
if ($content!=="done") {
$done = false;
}
curl_close($requests[$url]);
}
curl_multi_close($multi);
return $done;
}
// Retrieve data from multiple instances
public function retrieve(array $servers, array $data, array $uids) : array {
$multi = curl_multi_init();
$requests = array();
foreach ($servers as $url => $dht) {
$copy = $data;
$hash = bin2hex($dht["hash"]);
if (isset($uids[$hash])) {
$copy["uid"] = $uids[$hash];
}
$request = json_encode($copy);
$requests[$url] = curl_init();
curl_setopt($requests[$url], CURLOPT_RETURNTRANSFER, true);
curl_setopt($requests[$url], CURLOPT_URL, "http://".$url."/retrieve.php");
curl_setopt($requests[$url], CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($requests[$url], CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Length: ".strlen($request)));
curl_setopt($requests[$url], CURLOPT_POSTFIELDS, $request);
curl_multi_add_handle($multi, $requests[$url]);
}
while (true) {
$status = curl_multi_exec($multi, $active);
if ($active) {
curl_multi_select($multi);
}
while (true) {
$info = curl_multi_info_read($multi);
if ($info===false) {
break;
}
}
if (!$active || $status!=CURLM_OK) {
break;
}
}
$merged = array();
$merged["messages"] = array();
$merged["uids"] = array();
$merged["node"] = $data["node"];
foreach ($servers as $url => $dht) {
$content = curl_multi_getcontent($requests[$url]);
$stored = json_decode($content, true);
$hash = bin2hex($dht["hash"]);
if (isset($stored)) {
$merged["uids"][$hash] = $stored["uid"];
}
// TODO: merge indexes
if (isset($stored["messages"])) {
$merged["messages"] = $stored["messages"];
}
if (isset($stored["data"])) {
$merged["data"] = $stored["data"];
}
curl_close($requests[$url]);
}
curl_multi_close($multi);
return $merged;
}
}
// Distributed hash table
class QuasselDHT {
public $maxServers;
public $servers;
public function __construct() {
$this->maxServers = 3;
$this->servers = array();
$this->appendServer($_SERVER["HTTP_HOST"]);
}
public function __destruct() {
}
// Return distributed instances which could hold the data
public function keying(string $node) : array {
$node = QuasselHelper::hash($node);
$sort = array();
foreach ($this->servers as $key => $value) {
$sort[$key] = $this->diff($value["hash"], $node);
}
asort($sort);
$sort = array_slice($sort, 0, $this->maxServers, true);
foreach ($sort as $key => $value) {
$sort[$key] = $this->servers[$key];
}
return $sort;
}
// Distance between an instance and node information
public function diff(string $hash, string $node) : string {
$diff = "";
for ($n = 0; $n<strlen($hash); $n++) {
$diff .= chr(ord($hash[$n])^ord($node[$n]));
}
return $diff;
}
// Append an instance
public function appendServer(string $server) {
$this->servers[$server] = array("hash"=>QuasselHelper::hash($server));
}
// Send data to the webstore from identified instances
public function send(string $node, array $data) : bool {
$servers = $this->keying($node);
$store = new QuasselWebStore();
return $store->store($servers, $data);
}
// Retrieve data to the webstore from identified instances
public function receive(string $node, array $data, array $uids) : array {
$servers = $this->keying($node);
$store = new QuasselWebStore();
return $store->retrieve($servers, $data, $uids);
}
}
// Upper layer chat functionality
class QuasselChat {
public $dht;
public $node;
public $hashed;
public function __construct(object $dht, string $node) {
$this->dht = $dht;
$this->node = $node;
$this->hashed = QuasselHelper::hash($node);
}
public function __destruct() {
}
// Place chat message
public function place(string $data) : bool {
$uid = QuasselHelper::uniqueID();
$rpcMessageUpdate = array("node" => $uid, "chat" => bin2hex($this->hashed), "type" => "data", "data" => $data);
if (!$this->dht->send($this->hashed, $rpcMessageUpdate)) {
return false;
}
$rpcIndexUpdate = array("node" => bin2hex($this->hashed), "chat" => bin2hex($this->hashed), "type" => "index", "append" => $uid);
return $this->dht->send($this->hashed, $rpcIndexUpdate);
}
// Poll index
public function index(array $uids) : array {
$rpcIndexPoll = array("node" => bin2hex($this->hashed), "chat" => bin2hex($this->hashed), "type" => "index");
return $this->dht->receive($this->hashed, $rpcIndexPoll, $uids);
}
// Poll message
public function message(string $message) : array {
$rpcMessagePoll = array("node" => $message, "chat" => bin2hex($this->hashed), "type" => "data");
return $this->dht->receive($this->hashed, $rpcMessagePoll, array());
}
}
// API base
class QuasselCore {
public $dht;
public function __construct() {
$this->dht = new QuasselDHT();
}
public function __destruct() {
}
public function routeMessage(string $node, string $data) : bool {
$chat = new QuasselChat($this->dht, $node);
return $chat->place($data);
}
public function pollMessages(string $node, array $uids) : array {
$chat = new QuasselChat($this->dht, $node);
return $chat->index($uids);
}
public function pollMessage(string $node, string $message) : array {
$chat = new QuasselChat($this->dht, $node);
return $chat->message($message);
}
}
?>