-
-
Notifications
You must be signed in to change notification settings - Fork 252
/
linker.php
339 lines (272 loc) · 10.4 KB
/
linker.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
<?php
require __DIR__ . '/vendor/autoload.php';
gc_enable();
use Movim\Bootstrap;
use Movim\RPC;
use Movim\Session;
use Movim\Scheduler;
use React\Promise\Timer;
use App\PresenceBuffer;
$loop = React\EventLoop\Loop::get();
$bootstrap = new Bootstrap;
$bootstrap->boot();
// DNS
$config = React\Dns\Config\Config::loadSystemConfigBlocking();
$server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8';
$factory = new React\Dns\Resolver\Factory();
$dns = $factory->create($server);
// Scheduler
Scheduler::getInstance()->start();
// TCP Connector
$connector = null;
// We load and register all the widgets
$wrapper = \Movim\Widget\Wrapper::getInstance();
$wrapper->registerAll($bootstrap->getWidgets());
$xmppSocket = null;
$parser = new \Moxl\Parser(fn (\SimpleXMLElement $node) => \Moxl\Xec\Handler::handle($node));
$timestampReceive = $timestampSend = $sqlQueryExecuted = time();
function handleSSLErrors($errno, $errstr)
{
logOut(colorize('SSL Error ' . $errno . ': ' . $errstr, 'red'));
}
// Temporary linker killer
$loop->addPeriodicTimer(5, function () use (&$xmppSocket, &$timestampReceive, &$timestampSend) {
if (($timestampSend < time() - 3600 * 24 /* 24h */ || $timestampReceive < time() - 60 * 30 /* 30min */)
&& isset($xmppSocket)
) {
$xmppSocket->close();
}
});
// Buffer timers
$loop->addPeriodicTimer(1, function () {
$pb = PresenceBuffer::getInstance();
$pb->save();
});
$wsSocket = null;
function writeOut($msg = null)
{
global $wsSocket;
if (!empty($msg)) {
$wsSocket->send(json_encode($msg));
}
}
function logOut($log, string $type = 'system')
{
fwrite(STDERR, colorize(getenv('sid'), 'turquoise') . ' ' . colorize($type, 'purple'). " \n" . $log . "\n");
}
function writeXMPP($xml)
{
global $xmppSocket;
global $timestampSend;
if (!empty($xml) && $xmppSocket) {
$timestampSend = time();
$xmppSocket->write(trim($xml));
if (config('daemon.debug')) {
logOut(colorize(trim($xml) . ' ', 'yellow'), '>>> XMPP sent');
}
}
}
function enableEncryption($connection)
{
global $loop;
$encryption = new \React\Socket\StreamEncryption($loop, false);
logOut(colorize('Enable TLS on the socket', 'blue'));
$session = Session::instance();
stream_context_set_option($connection->stream, 'ssl', 'SNI_enabled', true);
stream_context_set_option($connection->stream, 'ssl', 'peer_name', $session->get('host'));
stream_context_set_option($connection->stream, 'ssl', 'allow_self_signed', false);
return $encryption->enable($connection)->then(
fn () => logOut(colorize('TLS enabled', 'blue')),
function ($error) use ($connection) {
logOut(colorize('TLS error ' . $error->getMessage(), 'blue'));
$evt = new Movim\Widget\Base;
$evt->event('ssl_error');
shutdown();
}
);
}
function handleClientDNS(array $results, $dns, $connector, $xmppBehaviour)
{
global $loop;
if (count($results) > 1) {
$port = 5222;
$directTLSSocket = false;
if (
$results['directtls'] !== false && $results['directtls'][0]['target'] !== '.'
&& $results['starttls'] !== false && $results['starttls'][0]['target'] !== '.'
) {
if ($results['starttls'][0]['priority'] < $results['directtls'][0]['priority']) {
$host = $results['starttls'][0]['target'];
$port = $results['starttls'][0]['port'];
logOut(colorize('Picked STARTTLS', 'blue'));
} else {
$host = $results['directtls'][0]['target'];
$port = $results['directtls'][0]['port'];
$directTLSSocket = true;
logOut(colorize('Picked DirectTLS', 'blue'));
}
} elseif ($results['directtls'] !== false && $results['directtls'][0]['target'] !== '.') {
$host = $results['directtls'][0]['target'];
$port = $results['directtls'][0]['port'];
$directTLSSocket = true;
logOut(colorize('Picked DirectTLS', 'blue'));
} elseif ($results['starttls'] !== false && $results['starttls'][0]['target'] !== '.') {
$host = $results['starttls'][0]['target'];
$port = $results['starttls'][0]['port'];
logOut(colorize('Picked STARTTLS', 'blue'));
} else {
// No SRV, we fallback to the default host
$session = Session::instance();
$host = $session->get('host');
}
$socket = 'tcp://';
if ($directTLSSocket) $socket = 'tls://';
$socket .= $host . ':' . $port;
logOut(colorize('Connect to ' . $socket, 'blue'));
$connector = new React\Socket\HappyEyeBallsConnector(
$loop,
new React\Socket\Connector([
'timeout' => 5.0,
'tls' => [
'SNI_enabled' => true,
'allow_self_signed' => false,
'peer_name' => $host
]
]),
$dns
);
$connector->connect($socket)->then(
$xmppBehaviour,
function (\Exception $error) {
logOut(colorize($error->getMessage(), 'red'));
$evt = new Movim\Widget\Base;
$evt->event('timeout_error');
}
);
}
}
function shutdown()
{
global $loop;
global $wsSocket;
logOut(colorize('Shutdown', 'blue'));
$wsSocket->close();
$loop->stop();
}
$wsSocketBehaviour = function ($msg) use (&$xmppSocket, &$connector, &$xmppBehaviour, &$dns) {
global $wsSocket;
$msg = json_decode($msg);
if (isset($msg)) {
switch ($msg->func) {
case 'message':
(new RPC)->handleJSON($msg->b);
break;
case 'up':
case 'down':
if (
isset($xmppSocket)
&& is_resource($xmppSocket->stream)
) {
$evt = new Movim\Widget\Base;
$evt->event('session_' . $msg->func);
}
break;
case 'unregister':
\Moxl\Stanza\Stream::end();
if (isset($xmppSocket)) {
$xmppSocket->close();
}
shutdown();
break;
case 'register':
// Set the host, useful for the CN certificate check
$session = Session::instance();
// If the host is already set, we already launched the registration process
if ($session->get('host')) {
return;
} else {
$session->set('host', $msg->host);
}
global $loop;
$results = [];
Timer\timeout($dns->resolveAll('_xmpps-client._tcp.' . $msg->host, React\Dns\Model\Message::TYPE_SRV), 3.0, $loop)
->then(
function ($resolved) use (&$results, &$dns, $connector, $xmppBehaviour) {
$results['directtls'] = $resolved;
handleClientDNS($results, $dns, $connector, $xmppBehaviour);
},
function ($rejected) use (&$results, &$dns, $connector, $xmppBehaviour) {
$results['directtls'] = false;
handleClientDNS($results, $dns, $connector, $xmppBehaviour);
}
);
Timer\timeout($dns->resolveAll('_xmpp-client._tcp.' . $msg->host, React\Dns\Model\Message::TYPE_SRV), 3.0, $loop)
->then(
function ($resolved) use (&$results, &$dns, $connector, $xmppBehaviour) {
$results['starttls'] = $resolved;
handleClientDNS($results, $dns, $connector, $xmppBehaviour);
},
function ($rejected) use (&$results, &$dns, $connector, $xmppBehaviour) {
$results['starttls'] = false;
handleClientDNS($results, $dns, $connector, $xmppBehaviour);
}
);
break;
}
}
return;
};
$xmppBehaviour = function (React\Socket\Connection $stream) use (&$xmppSocket, $parser, &$timestampReceive) {
global $wsSocket;
$xmppSocket = $stream;
$evt = new Movim\Widget\Base;
$evt->event('socket_connected');
if (getenv('verbose')) {
logOut(colorize('XMPP socket launched', 'blue'));
logOut(" launched : " . \humanSize(memory_get_usage()));
}
$xmppSocket->on('data', function ($message) use (&$xmppSocket, $parser, &$timestampReceive) {
if (!empty($message)) {
if (config('daemon.debug')) {
logOut(colorize($message . ' ', 'yellow'), '<<< XMPP received');
}
if ($message == '</stream:stream>') {
$xmppSocket->close();
shutdown();
} elseif (
$message == "<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"
|| $message == '<proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>'
) {
enableEncryption($xmppSocket)->then(
function () {
$session = Session::instance();
\Moxl\Stanza\Stream::init($session->get('host'), $session->get('jid'));
},
function () {
return;
}
);
}
$timestampReceive = time();
if (!$parser->parse($message)) {
logOut($parser->getError());
}
}
});
$xmppSocket->on('error', fn () => shutdown());
$xmppSocket->on('close', fn () => shutdown());
// And we say that we are ready !
$obj = new \StdClass;
$obj->func = 'registered';
fwrite(STDERR, 'registered');
$wsSocket->send(json_encode($obj));
};
$wsConnector = new \Ratchet\Client\Connector($loop);
$wsConnector('ws://127.0.0.1:' . getenv('port'), [], [
'MOVIM_SESSION_ID' => getenv('sid'),
'MOVIM_DAEMON_KEY' => getenv('key')
])->then(function (Ratchet\Client\WebSocket $socket) use (&$wsSocket, $wsSocketBehaviour) {
$wsSocket = $socket;
$wsSocket->on('message', $wsSocketBehaviour);
});
$loop->run();