WebSocket.php 12 KB
Newer Older
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
<?php


namespace IMATHUZH\Qfq\Core\Report;

/**
 * Simple WebSocket client.
 *
 * Class WebSocket
 * @package qfq
 *
 * @author Simon Samtleben <foo@bloatless.org>
 * @version 2.0
 */
class WebSocket {

    /**
     * @var string $host
     */
    private $host;

    /**
     * @var int $port
     */
    private $port;

    /**
     * @var string $path
     */
    private $path;

    /**
     * @var string $origin
     */
    private $origin;

    /**
     * @var resource $socket
     */
    private $socket = null;

    /**
     * @var bool $connected
     */
    private $connected = false;

    /**
     * @var string $target
     */
    private $target = '';

    public function __destruct() {
        $this->disconnect();
    }

    /**
     * Sends data to remote server.
     *
     * @param string $data
     * @param string $type
     * @param bool $masked
     * @return bool
     */
    public function sendData(string $data, string $type = 'text', bool $masked = true) {
        if ($this->connected === false) {
            trigger_error("Not connected", E_USER_WARNING);
            return false;
        }
        if (!is_string($data)) {
            trigger_error("Not a string data was given.", E_USER_WARNING);
            return false;
        }
        if (strlen($data) === 0) {
            return false;
        }
        $res = @fwrite($this->socket, $this->hybi10Encode($data, $type, $masked));
        if ($res === 0 || $res === false) {
            return false;
        }
        $buffer = ' ';
        $answer = '';

        while ($buffer !== '') {
            $buffer = fread($this->socket, 512);// drop?
            $answer .= $buffer;
        }

88
89
90
91
        // Decode WebSocket answer
        if ($answer !== '') {
            $data = $this->hybi10Decode($answer);
            $answer = $data['payload'];
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
        }

        return $answer;
    }

    /**
     * @param string $data
     * @param string $type
     * @param bool $masked
     * @return mixed|string
     */
    public function sendAndWait(string $data, string $type = 'text', bool $masked = true) {
        if ($this->sendData($data, $type, $masked)) {
            // to be implemented - for now it waits a bit and sends a predefined message
            usleep(250);
            $msg = json_decode($data, true);
            $msg['type'] = 'response';
            $msg['token'] = 'some_random_unusable_token';
            return json_decode($msg);
        } else {
            // error!
            return '';
        }

        /*        $this->connected = false;

                // send ping:
                $data = 'ping?';
                @fwrite($this->socket, $this->hybi10Encode($data, 'ping', true));
                $response = @fread($this->socket, 300);
                if (empty($response)) {
                    return false;
                }
                $response = $this->hybi10Decode($response);
                if (!is_array($response)) {
                    return false;
                }
                if (!isset($response['type']) || $response['type'] !== 'pong') {
                    return false;
                }
                $this->connected = true;

                return true;*/
    }


    /**
     * Connects to a websocket server.
     *
     * @param string $host
     * @param int $port
     * @param string $path
     * @param string $origin
     * @return bool
     */
    public function connect(string $host, int $port, string $path, string $origin = '') {
        $this->host = $host;
        $this->port = $port;
        $this->path = $path;
        $this->origin = $origin;

        $key = base64_encode($this->generateRandomString(16, false, true));
        $header = "GET " . $path . " HTTP/1.1\r\n";
        $header .= "Host: " . $host . ":" . $port . "\r\n";
        $header .= "Upgrade: websocket\r\n";
        $header .= "Connection: Upgrade\r\n";
        $header .= "Sec-WebSocket-Key: " . $key . "\r\n";
        if (!empty($origin)) {
            $header .= "Sec-WebSocket-Origin: " . $origin . "\r\n";
        }
        $header .= "Sec-WebSocket-Version: 13\r\n\r\n";

        $this->socket = fsockopen($host, $port, $errno, $errstr, 2);
        if ($this->socket === false) {
            return false;
        }

        socket_set_timeout($this->socket, 0, 10000);
        @fwrite($this->socket, $header);
        $response = @fread($this->socket, 1500);

        preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $response, $matches);

        if ($matches) {
            $keyAccept = trim($matches[1]);
            $expectedResponse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
            $this->connected = ($keyAccept === $expectedResponse) ? true : false;
        }

        return $this->connected;
    }

    /**
     * Checks if connection to webserver is active.
     *
     * @return bool
     */
    public function checkConnection() {
        $this->connected = false;

        // send ping:
        $data = 'ping?';
        @fwrite($this->socket, $this->hybi10Encode($data, 'ping', true));
        $response = @fread($this->socket, 300);
        if (empty($response)) {
            return false;
        }
        $response = $this->hybi10Decode($response);
        if (!is_array($response)) {
            return false;
        }
        if (!isset($response['type']) || $response['type'] !== 'pong') {
            return false;
        }
        $this->connected = true;

        return true;
    }


    /**
     * Disconnects from websocket server.
     *
     * @return void
     */
    public function disconnect() {
        $this->connected = false;
        is_resource($this->socket) && fclose($this->socket);
    }

    /**
     * Reconnects to previously connected websocket server.
     *
     * @return void
     */
    public function reconnect() {
        sleep(10);
        $this->connected = false;
        fclose($this->socket);
        $this->connect($this->host, $this->port, $this->path, $this->origin);
    }

    /**
     * Generates a random string.
     *
     * @param int $length
     * @param bool $addSpaces
     * @param bool $addNumbers
     * @return string
     */
    private function generateRandomString(int $length = 10, bool $addSpaces = true, bool $addNumbers = true) {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
        $useChars = [];
        // select some random chars:
        for ($i = 0; $i < $length; $i++) {
            $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
        }
        // add spaces and numbers:
        if ($addSpaces === true) {
            array_push($useChars, ' ', ' ', ' ', ' ', ' ', ' ');
        }
        if ($addNumbers === true) {
            array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
        }
        shuffle($useChars);
        $randomString = trim(implode('', $useChars));
        $randomString = substr($randomString, 0, $length);

        return $randomString;
    }

    /**
     * Encodes data according to the WebSocket protocol standard.
     *
     * @param string $payload
     * @param string $type
     * @param bool $masked
     * @return string
     */
    private function hybi10Encode(string $payload, string $type = 'text', bool $masked = true) {
        $frameHead = [];
        $payloadLength = strlen($payload);

        switch ($type) {
            case 'text':
                // first byte indicates FIN, Text-Frame (10000001):
                $frameHead[0] = 129;
                break;

            case 'close':
                // first byte indicates FIN, Close Frame(10001000):
                $frameHead[0] = 136;
                break;

            case 'ping':
                // first byte indicates FIN, Ping frame (10001001):
                $frameHead[0] = 137;
                break;

            case 'pong':
                // first byte indicates FIN, Pong frame (10001010):
                $frameHead[0] = 138;
                break;
        }

        // set mask and payload length (using 1, 3 or 9 bytes)
        if ($payloadLength > 65535) {
            $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 255 : 127;
            for ($i = 0; $i < 8; $i++) {
                $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
            }
            // most significant bit MUST be 0 (close connection if frame too big)
            if ($frameHead[2] > 127) {
                $this->disconnect();
                throw new \RuntimeException('Invalid payload. Could not encode frame.');
            }
        } elseif ($payloadLength > 125) {
            $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 254 : 126;
            $frameHead[2] = bindec($payloadLengthBin[0]);
            $frameHead[3] = bindec($payloadLengthBin[1]);
        } else {
            $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
        }

        // convert frame-head to string:
        foreach (array_keys($frameHead) as $i) {
            $frameHead[$i] = chr($frameHead[$i]);
        }
        if ($masked === true) {
            // generate a random mask:
            $mask = [];
            for ($i = 0; $i < 4; $i++) {
                $mask[$i] = chr(rand(0, 255));
            }

            $frameHead = array_merge($frameHead, $mask);
        }
        $frame = implode('', $frameHead);

        // append payload to frame:
        for ($i = 0; $i < $payloadLength; $i++) {
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
        }

        return $frame;
    }

    /**
     * Decodes a received frame/string according to the WebSocket protocol standards.
     *
     * @param string $data
     * @return array
     */
    private function hybi10Decode(string $data) {
        $unmaskedPayload = '';
        $decodedData = [];

        // estimate frame type:
        $firstByteBinary = sprintf('%08b', ord($data[0]));
        $secondByteBinary = sprintf('%08b', ord($data[1]));
        $opcode = bindec(substr($firstByteBinary, 4, 4));
        $isMasked = ($secondByteBinary[0] == '1') ? true : false;
        $payloadLength = ord($data[1]) & 127;

        switch ($opcode) {
            // text frame:
            case 1:
                $decodedData['type'] = 'text';
                break;
            case 2:
                $decodedData['type'] = 'binary';
                break;
            // connection close frame:
            case 8:
                $decodedData['type'] = 'close';
                break;
            // ping frame:
            case 9:
                $decodedData['type'] = 'ping';
                break;
            // pong frame:
            case 10:
                $decodedData['type'] = 'pong';
                break;
            default:
                throw new \RuntimeException('Could not decode frame. Invalid type.');
        }

        if ($payloadLength === 126) {
            $mask = substr($data, 4, 4);
            $payloadOffset = 8;
            $dataLength = bindec(sprintf('%08b', ord($data[2])) . sprintf('%08b', ord($data[3]))) + $payloadOffset;
        } elseif ($payloadLength === 127) {
            $mask = substr($data, 10, 4);
            $payloadOffset = 14;
            $tmp = '';
            for ($i = 0; $i < 8; $i++) {
                $tmp .= sprintf('%08b', ord($data[$i + 2]));
            }
            $dataLength = bindec($tmp) + $payloadOffset;
            unset($tmp);
        } else {
            $mask = substr($data, 2, 4);
            $payloadOffset = 6;
            $dataLength = $payloadLength + $payloadOffset;
        }

        if ($isMasked === true) {
            for ($i = $payloadOffset; $i < $dataLength; $i++) {
                $j = $i - $payloadOffset;
                if (isset($data[$i])) {
                    $unmaskedPayload .= $data[$i] ^ $mask[$j % 4];
                }
            }
            $decodedData['payload'] = $unmaskedPayload;
        } else {
            $payloadOffset = $payloadOffset - 4;
            $decodedData['payload'] = substr($data, $payloadOffset);
        }

        return $decodedData;
    }
}