fix typo
[brisk.git] / web / Obj / transports.phh
1 <?php
2 /*
3  *  sac-a-push - Obj/transports.phh
4  *
5  *  Copyright (C) 2012 Matteo Nastasi
6  *                          mailto: nastasi@alternativeoutput.it
7  *                                  matteo.nastasi@milug.org
8  *                          web: http://www.alternativeoutput.it
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details. You should have received a
19  * copy of the GNU General Public License along with this program; if
20  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
21  * Suite 330, Boston, MA 02111-1307, USA.
22  *
23  */
24
25 /*
26  *  test: SO x Browser
27  *  Values: Y: works, N: not works, @: continuous download,
28  *          D: continuous download after first reload
29  *
30  *  Stream IFRAME:
31  *
32  * Iframe| IW | FF | Ch | Op | Ko | IE
33  * ------+----+----+----+----+----+----
34  *   Lnx | D  |    | @  |    | @  | x
35  *   Win | x  | D  | @  | @  |    | D
36  *   Mac | x  |    |    |    |    |
37  *
38  *
39  *   WS  | IW | FF | Ch | Op | Ko | IE
40  * ------+----+----+----+----+----+----
41  *   Lnx |    |    |    |    |    |
42  *   Win |    |    |    |    |    |
43  *   Mac |    |    |    |    |    |
44  *
45  *
46  *   XHR | IW | FF | Ch | Op | Ko | IE
47  * ------+----+----+----+----+----+----
48  *   Lnx | Y  |    | ^D |    | Y  | x
49  *   Win | x  | Y  | Y  |    |    | N
50  *   Mac | x  |    |    |    |    |
51  *
52  *
53  * HtmlFl| IW | FF | Ch | Op | Ko | IE
54  * ------+----+----+----+----+----+----
55  *   Lnx | N  |    |    |    | N  |
56  *   Win | x  | N  | N  |    |    | Y* (* seems delay between click and load of a new page)
57  *   Mac | x  |    |    |    |    |
58  *
59  *
60  */
61
62 class Transport_template {
63
64     function Transport_template() {
65     }
66
67     // return string value is appended to the content of the returned page
68     // return FALSE if fails
69     // check with '===' operator to disambiguation between "" and FALSE return value
70     function init($enc, $header, &$header_out, $init_string, $base, $step)
71     {
72     }
73
74     function close()
75     {
76     }
77
78     function chunk($step, $cont)
79     {
80     }
81
82     function is_chunked()
83     {
84     }
85
86     // return string to add to the stream to perform something to the engine
87     static function fini($init_string, $base, $blockerr)
88     {
89         return "";
90     }
91 }
92
93 class Transport_websocket {
94     protected $magicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
95
96     function Transport_websocket($secure = FALSE) {
97         $this->type = ($secure == FALSE ? "websocket" : "websocketsec");
98         $this->headerOriginRequired                 = false;
99         $this->headerSecWebSocketProtocolRequired   = false;
100         $this->headerSecWebSocketExtensionsRequired = false;
101
102         $this->sendingContinuous = false;
103
104         $this->handlingPartialPacket = false;
105         $this->partialMessage = "";
106
107         $this->hasSentClose = false;
108     }
109
110     protected function extractHeaders($message) {
111         $header = array('fin'     => $message[0] & chr(128),
112                         'rsv1'    => $message[0] & chr(64),
113                         'rsv2'    => $message[0] & chr(32),
114                         'rsv3'    => $message[0] & chr(16),
115                         'opcode'  => ord($message[0]) & 15,
116                         'hasmask' => $message[1] & chr(128),
117                         'length'  => 0,
118                         'mask'    => "");
119         $header['length'] = (ord($message[1]) >= 128) ? ord($message[1]) - 128 : ord($message[1]);
120
121         if ($header['length'] == 126) {
122             if ($header['hasmask']) {
123                 $header['mask'] = $message[4] . $message[5] . $message[6] . $message[7];
124             }
125             $header['length'] = ord($message[2]) * 256
126                 + ord($message[3]);
127         } elseif ($header['length'] == 127) {
128             if ($header['hasmask']) {
129                 $header['mask'] = $message[10] . $message[11] . $message[12] . $message[13];
130             }
131             $header['length'] = ord($message[2]) * 65536 * 65536 * 65536 * 256
132                 + ord($message[3]) * 65536 * 65536 * 65536
133                 + ord($message[4]) * 65536 * 65536 * 256
134                 + ord($message[5]) * 65536 * 65536
135                 + ord($message[6]) * 65536 * 256
136                 + ord($message[7]) * 65536
137                 + ord($message[8]) * 256
138                 + ord($message[9]);
139         } elseif ($header['hasmask']) {
140             $header['mask'] = $message[2] . $message[3] . $message[4] . $message[5];
141         }
142         //echo $this->strtohex($message);
143         //$this->printHeaders($header);
144         return $header;
145     }
146
147     protected function extractPayload($message,$headers) {
148         $offset = 2;
149         if ($headers['hasmask']) {
150             $offset += 4;
151         }
152         if ($headers['length'] > 65535) {
153             $offset += 8;
154         } elseif ($headers['length'] > 125) {
155             $offset += 2;
156         }
157         return substr($message,$offset);
158     }
159
160     protected function applyMask($headers,$payload) {
161         $effectiveMask = "";
162         if ($headers['hasmask']) {
163             $mask = $headers['mask'];
164         } else {
165             return $payload;
166         }
167
168         while (mb_strlen($effectiveMask, "ASCII") < mb_strlen($payload, "ASCII")) {
169             $effectiveMask .= $mask;
170         }
171         while (mb_strlen($effectiveMask, "ASCII") > mb_strlen($payload, "ASCII")) {
172             $effectiveMask = substr($effectiveMask,0,-1);
173         }
174         return $effectiveMask ^ $payload;
175     }
176
177     protected function checkRSVBits($headers,$user) { // override this method if you are using an extension where the RSV bits are used.
178         if (ord($headers['rsv1']) + ord($headers['rsv2']) + ord($headers['rsv3']) > 0) {
179             //$this->disconnect($user); // todo: fail connection
180             return true;
181         }
182         return false;
183     }
184
185     protected function strtohex($str) {
186         $strout = "";
187         for ($i = 0; $i < mb_strlen($str, "ASCII"); $i++) {
188             $strout .= (ord($str[$i])<16) ? "0" . dechex(ord($str[$i])) : dechex(ord($str[$i]));
189             $strout .= " ";
190             if ($i%32 == 7) {
191                 $strout .= ": ";
192             }
193             if ($i%32 == 15) {
194                 $strout .= ": ";
195             }
196             if ($i%32 == 23) {
197                 $strout .= ": ";
198             }
199             if ($i%32 == 31) {
200                 $strout .= "\n";
201             }
202         }
203         return $strout . "\n";
204     }
205
206     function unchunk($cont)
207     {
208         // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
209         return $this->deframe($cont);
210     }
211
212     function chunk($step, $cont)
213     {
214         // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
215         return $this->frame('@BEGIN@'.$cont.'@END@'); // , 'text', TRUE);
216     }
217
218     protected function frame($message, $messageType='text', $messageContinues=false) {
219         switch ($messageType) {
220         case 'continuous':
221             $b1 = 0;
222             break;
223         case 'text':
224             $b1 = ($this->sendingContinuous) ? 0 : 1;
225             break;
226         case 'binary':
227             $b1 = ($this->sendingContinuous) ? 0 : 2;
228             break;
229         case 'close':
230             $b1 = 8;
231             break;
232         case 'ping':
233             $b1 = 9;
234             break;
235         case 'pong':
236             $b1 = 10;
237             break;
238         }
239         if ($messageContinues) {
240             $this->sendingContinuous = true;
241         } else {
242             $b1 += 128;
243             $this->sendingContinuous = false;
244         }
245
246         $length = mb_strlen($message, "ASCII");
247         $lengthField = "";
248         if ($length < 126) {
249             $b2 = $length;
250         } elseif ($length <= 65536) {
251             $b2 = 126;
252             $hexLength = dechex($length);
253             //$this->stdout("Hex Length: $hexLength");
254             if (mb_strlen($hexLength, "ASCII")%2 == 1) {
255                 $hexLength = '0' . $hexLength;
256             }
257             $n = mb_strlen($hexLength, "ASCII") - 2;
258
259             for ($i = $n; $i >= 0; $i=$i-2) {
260                 $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
261             }
262             while (mb_strlen($lengthField, "ASCII") < 2) {
263                 $lengthField = chr(0) . $lengthField;
264             }
265         } else {
266             $b2 = 127;
267             $hexLength = dechex($length);
268             if (mb_strlen($hexLength, "ASCII")%2 == 1) {
269                 $hexLength = '0' . $hexLength;
270             }
271             $n = mb_strlen($hexLength, "ASCII") - 2;
272
273             for ($i = $n; $i >= 0; $i=$i-2) {
274                 $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
275             }
276             while (mb_strlen($lengthField, "ASCII") < 8) {
277                 $lengthField = chr(0) . $lengthField;
278             }
279         }
280
281         return chr($b1) . chr($b2) . $lengthField . $message;
282     }
283
284     protected function deframe($message) {
285         //echo $this->strtohex($message);
286         $headers = $this->extractHeaders($message);
287         $pongReply = false;
288         $willClose = false;
289         switch($headers['opcode']) {
290         case 0:
291         case 1:
292         case 2:
293             break;
294         case 8:
295             // todo: close the connection
296             $this->hasSentClose = true;
297             return "";
298         case 9:
299             $pongReply = true;
300         case 10:
301             break;
302         default:
303             //$this->disconnect($user); // todo: fail connection
304             $willClose = true;
305             break;
306         }
307
308         if ($this->handlingPartialPacket) {
309             $message = $this->partialBuffer . $message;
310             $this->handlingPartialPacket = false;
311             return $this->deframe($message);
312         }
313
314         if ($this->checkRSVBits($headers,$this)) {
315             return false;
316         }
317
318         if ($willClose) {
319             // todo: fail the connection
320             return false;
321         }
322
323         $payload = $this->partialMessage . $this->extractPayload($message,$headers);
324
325         if ($pongReply) {
326             $reply = $this->frame($payload,$this,'pong');
327             // TODO FIXME ALL socket_write management
328             socket_write($user->socket,$reply,mb_strlen($reply, "ASCII"));
329             return false;
330         }
331         if (extension_loaded('mbstring')) {
332             if ($headers['length'] > mb_strlen($payload, "ASCII")) {
333                 $this->handlingPartialPacket = true;
334                 $this->partialBuffer = $message;
335                 return false;
336             }
337         } else {
338             if ($headers['length'] > mb_strlen($payload, "ASCII")) {
339                 $this->handlingPartialPacket = true;
340                 $this->partialBuffer = $message;
341                 return false;
342             }
343         }
344
345         $payload = $this->applyMask($headers,$payload);
346
347         if ($headers['fin']) {
348             $this->partialMessage = "";
349             return $payload;
350         }
351         $this->partialMessage = $payload;
352         return false;
353     }
354
355
356     protected function checkHost($hostName) {
357         return true; // Override and return false if the host is not one that you would expect.
358         // Ex: You only want to accept hosts from the my-domain.com domain,
359         // but you receive a host from malicious-site.com instead.
360     }
361
362     protected function checkOrigin($origin) {
363         return true; // Override and return false if the origin is not one that you would expect.
364     }
365
366     protected function checkWebsocProtocol($protocol) {
367         return true; // Override and return false if a protocol is not found that you would expect.
368     }
369
370     protected function checkWebsocExtensions($extensions) {
371         return true; // Override and return false if an extension is not found that you would expect.
372     }
373
374     protected function processProtocol($protocol) {
375         return ""; // return either "Sec-WebSocket-Protocol: SelectedProtocolFromClientList\r\n" or return an empty string.
376         // The carriage return/newline combo must appear at the end of a non-empty string, and must not
377         // appear at the beginning of the string nor in an otherwise empty string, or it will be considered part of
378         // the response body, which will trigger an error in the client as it will not be formatted correctly.
379     }
380
381     protected function processExtensions($extensions) {
382         return ""; // return either "Sec-WebSocket-Extensions: SelectedExtensions\r\n" or return an empty string.
383     }
384
385     function init($enc, $headers, &$headers_out, $init_string, $base, $step)
386     {
387         if (0) { // TODO: what is ?
388             if (isset($headers['get'])) {
389                 $this->requestedResource = $headers['get'];
390             } else {
391                 // todo: fail the connection
392                 $headers_out['HTTP-Response'] = "405 Method Not Allowed";
393             }
394         }
395
396         if (!isset($headers['Host']) || !$this->checkHost($headers['Host'])) {
397             // error_log('bad 1');
398             $headers_out['HTTP-Response'] = "400 Bad Request";
399         }
400         if (!isset($headers['Upgrade']) || strtolower($headers['Upgrade']) != 'websocket') {
401             // error_log('bad 2 ' . $headers['Upgrade']);
402             $headers_out['HTTP-Response'] = "400 Bad Request";
403         }
404         if (!isset($headers['Connection']) || strpos(strtolower($headers['Connection']), 'upgrade') === FALSE) {
405             // error_log('bad 3');
406             $headers_out['HTTP-Response'] = "400 Bad Request";
407         }
408         if (!isset($headers['Sec-Websocket-Key'])) {
409             // error_log('bad 4');
410             $headers_out['HTTP-Response'] = "400 Bad Request";
411         } else {
412         }
413
414         if (!isset($headers['Sec-Websocket-Version']) || strtolower($headers['Sec-Websocket-Version']) != 13) {
415             $headers_out['HTTP-Response'] = "426 Upgrade Required";
416             $headers_out['Sec-WebSocketVersion'] = "13";
417         }
418         if ( ($this->headerOriginRequired && !isset($headers['Origin']) )
419              || ($this->headerOriginRequired && !$this->checkOrigin($headers['Origin'])) ) {
420             $headers_out['HTTP-Response'] = "403 Forbidden";
421         }
422         if ( ($this->headerSecWebSocketProtocolRequired && !isset($headers['Sec-Websocket-Protocol']))
423              || ($this->headerSecWebSocketProtocolRequired &&
424                  !$this->checkWebsocProtocol($headers['Sec-Websocket-Protocol']))) {
425             // error_log('bad 5');
426             $headers_out['HTTP-Response'] = "400 Bad Request";
427         }
428         if ( ($this->headerSecWebSocketExtensionsRequired  && !isset($headers['Sec-Websocket-Extensions']))
429              || ($this->headerSecWebSocketExtensionsRequired &&
430                  !$this->checkWebsocExtensions($headers['Sec-Websocket-Extensions'])) ) {
431             // error_log('bad 6');
432             $headers_out['HTTP-Response'] = "400 Bad Request";
433         }
434
435         if (isset($headers_out['HTTP-Response'])) {
436             // TODO: check return management
437             return (FALSE);
438         }
439
440         // TODO: verify both variables
441         // here there is a change of the socket status from start to handshaked
442         // th headers are saved too but without any further access so we skip it
443
444
445
446         $inno = 'x3JJHMbDL1EzLkh9GBhXDw==';
447         $outo = sha1($inno . $this->magicGUID);
448         $rawToken = "";
449         for ($i = 0; $i < 20; $i++) {
450             $rawToken .= chr(hexdec(substr($outo,$i*2, 2)));
451         }
452
453         $outo = base64_encode($rawToken);
454
455         $webSocketKeyHash = sha1($headers['Sec-Websocket-Key'] . $this->magicGUID);
456         $rawToken = "";
457         for ($i = 0; $i < 20; $i++) {
458             $rawToken .= chr(hexdec(substr($webSocketKeyHash,$i*2, 2)));
459         }
460         $handshakeToken = base64_encode($rawToken);
461         $subProtocol = (isset($headers['Sec-Websocket-Protocol'])) ?
462             $this->processProtocol($headers['Sec-Websocket-Protocol']) : "";
463         $extensions = (isset($headers['Sec-Websocket-Extensions'])) ?
464             $this->processExtensions($headers['Sec-Websocket-Extensions']) : "";
465
466         $headers_out['HTTP-Response'] = "101 Switching Protocols";
467         $headers_out['Upgrade']       = 'websocket';
468         $headers_out['Connection']    = 'Upgrade';
469         $headers_out['Sec-WebSocket-Accept'] = "$handshakeToken$subProtocol$extensions";
470
471         return ("");
472     }
473
474     static function close()
475     {
476         return(chr(0x88).chr(0x02).chr(0xe8).chr(0x03));
477     }
478
479     static function fini($init_string, $base, $blockerr)
480     {
481         return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@',  ($blockerr ? 'xstm.stop(); ' : ''), $base).self::close());
482     }
483
484     function is_chunked()
485     {
486         return FALSE;
487     }
488
489 }
490
491 class Transport_xhr {
492
493     function Transport_xhr() {
494         $this->type = 'xhr';
495     }
496
497     function init($enc, $header, &$header_out, $init_string, $base, $step)
498     {
499         $ret = sprintf("@BEGIN@ /* %s */ @END@", $init_string);
500         if ($enc != 'plain')
501             $header_out['Content-Encoding'] = $enc;
502         $header_out['Cache-Control'] = 'no-cache, must-revalidate';     // HTTP/1.1
503         $header_out['Expires']       = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
504         $header_out['Content-type']  = 'application/xml; charset="utf-8"';
505
506         return ($ret);
507     }
508
509     function close()
510     {
511         return "";
512     }
513
514     static function fini($init_string, $base, $blockerr)
515     {
516         return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@',  ($blockerr ? 'xstm.stop(); ' : ''), $base));
517         return ("");
518     }
519
520     function chunk($step, $cont)
521     {
522         // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
523         return ("@BEGIN@".$cont."@END@");
524     }
525
526     function is_chunked()
527     {
528         return TRUE;
529     }
530 }
531
532 class Transport_iframe {
533
534     function Transport_iframe() {
535         $this->type = 'iframe';
536     }
537
538     function init($enc, $header, &$header_out, $init_string, $base, $step)
539     {
540         $ret = "";
541
542         if ($enc != 'plain')
543             $header_out['Content-Encoding'] = $enc;
544         $header_out['Cache-Control'] = 'no-cache, must-revalidate';     // HTTP/1.1
545         $header_out['Expires']       = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
546         $header_out['Content-type']  = 'text/html; charset="utf-8"';
547
548         $ret .= sprintf("<html>
549 <head>
550 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
551 <script type=\"text/javascript\" src=\"%sxynt-streaming-ifra.js\"></script>
552 <script type=\"text/javascript\">
553 var xynt_streaming = \"ready\";", $base, $base);
554         if ($step > 0)
555             $ret .= sprintf("last_clean = %d;\n", ($step-1));
556         $ret .= sprintf("
557 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.transp.stopped = true; } } catch(e) { /* console.log(\"catcha\"); */ } };
558 </script>
559 </head>
560 <body>");
561         $ret .= sprintf("<!-- \n%s -->\n", $init_string);
562
563         return ($ret);
564     }
565
566     function close()
567     {
568         return "";
569     }
570
571     static function fini($init_string, $base, $blockerr)
572     {
573         $ret = "";
574         $ret .= sprintf("<html>
575 <head>
576 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
577 <script type=\"text/javascript\" src=\"%sxynt-streaming-ifra.js\"></script>
578 <script type=\"text/javascript\">
579 var xynt_streaming = \"ready\";", $base, $base);
580         $ret .= sprintf("
581 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.reload(); } } catch(e) { /* console.log(\"catcha\"); */ } };
582 </script>
583 </head>
584 <body>");
585         $ret .= sprintf("<!-- \n%s -->\n", $init_string);
586         $ret .= sprintf("<script id='hs%d' type='text/javascript'><!--
587 push(\"%s\");
588 // -->
589 </script>", 0, escpush($blockerr) );
590         return ($ret);
591     }
592
593     function chunk($step, $cont)
594     {
595         // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
596         if ($cont == NULL) {
597             return sprintf("<script id='hs%d' type='text/javascript'><!--
598 push(null);\n// -->\n</script>", $step);
599         }
600         else {
601             return sprintf("<script id='hs%d' type='text/javascript'><!--
602 push(\"%s\");\n// -->\n</script>", $step, escpush($cont) );
603         }
604     }
605
606     function is_chunked()
607     {
608         return TRUE;
609     }
610 }
611
612 class Transport_htmlfile extends Transport_iframe {
613     function Transport_htmlfile() {
614         $this->type = 'htmlfile';
615     }
616 }
617
618 class Transport {
619     function Transport()
620     {
621     }
622
623     static function create($transp)
624     {
625         if ($transp == 'websocket' || $transp == 'websocketsec') {
626             return new Transport_websocket($transp == 'websocketsec');
627         }
628         else if ($transp == 'xhr') {
629             return new Transport_xhr();
630         }
631         else if ($transp == 'htmlfile') {
632             return new Transport_htmlfile();
633         }
634         else  {
635             return new Transport_iframe();
636         }
637     }
638     static function gettype($transp)
639     {
640         if ($transp == 'websocket' || $transp == 'xhr' || $transp == 'htmlfile') {
641             return "Transport_".$transp;
642         }
643         else {
644             return 'Transport_iframe';
645         }
646     }
647 }
648 ?>