3 * sac-a-push - Obj/transports.phh
5 * Copyright (C) 2012 Matteo Nastasi
6 * mailto: nastasi@alternativeoutput.it
7 * matteo.nastasi@milug.org
8 * web: http://www.alternativeoutput.it
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.
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.
27 * Values: Y: works, N: not works, @: continuous download,
28 * D: continuous download after first reload
32 * Iframe| IW | FF | Ch | Op | Ko | IE
33 * ------+----+----+----+----+----+----
34 * Lnx | D | | @ | | @ | x
35 * Win | x | D | @ | @ | | D
39 * WS | IW | FF | Ch | Op | Ko | IE
40 * ------+----+----+----+----+----+----
46 * XHR | IW | FF | Ch | Op | Ko | IE
47 * ------+----+----+----+----+----+----
48 * Lnx | Y | | ^D | | Y | x
49 * Win | x | Y | Y | | | N
53 * HtmlFl| IW | FF | Ch | Op | Ko | IE
54 * ------+----+----+----+----+----+----
56 * Win | x | N | N | | | Y* (* seems delay between click and load of a new page)
62 class Transport_template {
64 function Transport_template() {
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)
78 function chunk($step, $cont)
86 // return string to add to the stream to perform something to the engine
87 static function fini($init_string, $base, $blockerr)
93 class Transport_websocket {
94 protected $magicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
96 function Transport_websocket() {
97 $this->headerOriginRequired = false;
98 $this->headerSecWebSocketProtocolRequired = false;
99 $this->headerSecWebSocketExtensionsRequired = false;
101 $this->sendingContinuous = false;
102 $this->sendingContinuous = false;
103 $this->partialMessage = "";
105 $this->hasSentClose = false;
108 protected function extractHeaders($message) {
109 $header = array('fin' => $message[0] & chr(128),
110 'rsv1' => $message[0] & chr(64),
111 'rsv2' => $message[0] & chr(32),
112 'rsv3' => $message[0] & chr(16),
113 'opcode' => ord($message[0]) & 15,
114 'hasmask' => $message[1] & chr(128),
117 $header['length'] = (ord($message[1]) >= 128) ? ord($message[1]) - 128 : ord($message[1]);
119 if ($header['length'] == 126) {
120 if ($header['hasmask']) {
121 $header['mask'] = $message[4] . $message[5] . $message[6] . $message[7];
123 $header['length'] = ord($message[2]) * 256
125 } elseif ($header['length'] == 127) {
126 if ($header['hasmask']) {
127 $header['mask'] = $message[10] . $message[11] . $message[12] . $message[13];
129 $header['length'] = ord($message[2]) * 65536 * 65536 * 65536 * 256
130 + ord($message[3]) * 65536 * 65536 * 65536
131 + ord($message[4]) * 65536 * 65536 * 256
132 + ord($message[5]) * 65536 * 65536
133 + ord($message[6]) * 65536 * 256
134 + ord($message[7]) * 65536
135 + ord($message[8]) * 256
137 } elseif ($header['hasmask']) {
138 $header['mask'] = $message[2] . $message[3] . $message[4] . $message[5];
140 //echo $this->strtohex($message);
141 //$this->printHeaders($header);
145 protected function extractPayload($message,$headers) {
147 if ($headers['hasmask']) {
150 if ($headers['length'] > 65535) {
152 } elseif ($headers['length'] > 125) {
155 return substr($message,$offset);
158 protected function applyMask($headers,$payload) {
160 if ($headers['hasmask']) {
161 $mask = $headers['mask'];
166 while (mb_strlen($effectiveMask, "ASCII") < mb_strlen($payload, "ASCII")) {
167 $effectiveMask .= $mask;
169 while (mb_strlen($effectiveMask, "ASCII") > mb_strlen($payload, "ASCII")) {
170 $effectiveMask = substr($effectiveMask,0,-1);
172 return $effectiveMask ^ $payload;
175 protected function checkRSVBits($headers,$user) { // override this method if you are using an extension where the RSV bits are used.
176 if (ord($headers['rsv1']) + ord($headers['rsv2']) + ord($headers['rsv3']) > 0) {
177 //$this->disconnect($user); // todo: fail connection
183 protected function strtohex($str) {
185 for ($i = 0; $i < mb_strlen($str, "ASCII"); $i++) {
186 $strout .= (ord($str[$i])<16) ? "0" . dechex(ord($str[$i])) : dechex(ord($str[$i]));
201 return $strout . "\n";
204 function chunk($step, $cont)
206 return $this->frame('@BEGIN@'.$cont.'@END@'); // , 'text', TRUE);
209 protected function frame($message, $messageType='text', $messageContinues=false) {
210 switch ($messageType) {
215 $b1 = ($this->sendingContinuous) ? 0 : 1;
218 $b1 = ($this->sendingContinuous) ? 0 : 2;
230 if ($messageContinues) {
231 $this->sendingContinuous = true;
234 $this->sendingContinuous = false;
237 $length = mb_strlen($message, "ASCII");
241 } elseif ($length <= 65536) {
243 $hexLength = dechex($length);
244 //$this->stdout("Hex Length: $hexLength");
245 if (mb_strlen($hexLength, "ASCII")%2 == 1) {
246 $hexLength = '0' . $hexLength;
248 $n = mb_strlen($hexLength, "ASCII") - 2;
250 for ($i = $n; $i >= 0; $i=$i-2) {
251 $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
253 while (mb_strlen($lengthField, "ASCII") < 2) {
254 $lengthField = chr(0) . $lengthField;
258 $hexLength = dechex($length);
259 if (mb_strlen($hexLength, "ASCII")%2 == 1) {
260 $hexLength = '0' . $hexLength;
262 $n = mb_strlen($hexLength, "ASCII") - 2;
264 for ($i = $n; $i >= 0; $i=$i-2) {
265 $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
267 while (mb_strlen($lengthField, "ASCII") < 8) {
268 $lengthField = chr(0) . $lengthField;
272 return chr($b1) . chr($b2) . $lengthField . $message;
275 protected function deframe($message) {
276 //echo $this->strtohex($message);
277 $headers = $this->extractHeaders($message);
280 switch($headers['opcode']) {
286 // todo: close the connection
287 $this->hasSentClose = true;
294 //$this->disconnect($user); // todo: fail connection
299 if ($this->handlingPartialPacket) {
300 $message = $this->partialBuffer . $message;
301 $this->handlingPartialPacket = false;
302 return $this->deframe($message);
305 if ($this->checkRSVBits($headers,$this)) {
310 // todo: fail the connection
314 $payload = $this->partialMessage . $this->extractPayload($message,$headers);
317 $reply = $this->frame($payload,$this,'pong');
318 // TODO FIXME ALL socket_write management
319 socket_write($user->socket,$reply,mb_strlen($reply, "ASCII"));
322 if (extension_loaded('mbstring')) {
323 if ($headers['length'] > mb_strlen($payload, "ASCII")) {
324 $this->handlingPartialPacket = true;
325 $this->partialBuffer = $message;
329 if ($headers['length'] > mb_strlen($payload, "ASCII")) {
330 $this->handlingPartialPacket = true;
331 $this->partialBuffer = $message;
336 $payload = $this->applyMask($headers,$payload);
338 if ($headers['fin']) {
339 $this->partialMessage = "";
342 $this->partialMessage = $payload;
347 protected function checkHost($hostName) {
348 return true; // Override and return false if the host is not one that you would expect.
349 // Ex: You only want to accept hosts from the my-domain.com domain,
350 // but you receive a host from malicious-site.com instead.
353 protected function checkOrigin($origin) {
354 return true; // Override and return false if the origin is not one that you would expect.
357 protected function checkWebsocProtocol($protocol) {
358 return true; // Override and return false if a protocol is not found that you would expect.
361 protected function checkWebsocExtensions($extensions) {
362 return true; // Override and return false if an extension is not found that you would expect.
365 protected function processProtocol($protocol) {
366 return ""; // return either "Sec-WebSocket-Protocol: SelectedProtocolFromClientList\r\n" or return an empty string.
367 // The carriage return/newline combo must appear at the end of a non-empty string, and must not
368 // appear at the beginning of the string nor in an otherwise empty string, or it will be considered part of
369 // the response body, which will trigger an error in the client as it will not be formatted correctly.
372 protected function processExtensions($extensions) {
373 return ""; // return either "Sec-WebSocket-Extensions: SelectedExtensions\r\n" or return an empty string.
376 function init($enc, $headers, &$headers_out, $init_string, $base, $step)
378 if (0) { // TODO: what is ?
379 if (isset($headers['get'])) {
380 $this->requestedResource = $headers['get'];
382 // todo: fail the connection
383 $headers_out['HTTP-Response'] = "405 Method Not Allowed";
387 if (!isset($headers['Host']) || !$this->checkHost($headers['Host'])) {
388 $headers_out['HTTP-Response'] = "400 Bad Request";
390 if (!isset($headers['Upgrade']) || strtolower($headers['Upgrade']) != 'websocket') {
391 $headers_out['HTTP-Response'] = "400 Bad Request";
393 if (!isset($headers['Connection']) || strpos(strtolower($headers['Connection']), 'upgrade') === FALSE) {
394 $headers_out['HTTP-Response'] = "400 Bad Request";
396 if (!isset($headers['Sec-Websocket-Key'])) {
397 $headers_out['HTTP-Response'] = "400 Bad Request";
401 if (!isset($headers['Sec-Websocket-Version']) || strtolower($headers['Sec-Websocket-Version']) != 13) {
402 $headers_out['HTTP-Response'] = "426 Upgrade Required";
403 $headers_out['Sec-WebSocketVersion'] = "13";
405 if ( ($this->headerOriginRequired && !isset($headers['Origin']) )
406 || ($this->headerOriginRequired && !$this->checkOrigin($headers['Origin'])) ) {
407 $headers_out['HTTP-Response'] = "403 Forbidden";
409 if ( ($this->headerSecWebSocketProtocolRequired && !isset($headers['Sec-Websocket-Protocol']))
410 || ($this->headerSecWebSocketProtocolRequired &&
411 !$this->checkWebsocProtocol($headers['Sec-Websocket-Protocol']))) {
412 $headers_out['HTTP-Response'] = "400 Bad Request";
414 if ( ($this->headerSecWebSocketExtensionsRequired && !isset($headers['Sec-Websocket-Extensions']))
415 || ($this->headerSecWebSocketExtensionsRequired &&
416 !$this->checkWebsocExtensions($headers['Sec-Websocket-Extensions'])) ) {
417 $headers_out['HTTP-Response'] = "400 Bad Request";
420 if (isset($headers_out['HTTP-Response'])) {
421 // TODO: check return management
425 // TODO: verify both variables
426 // here there is a change of the socket status from start to handshaked
427 // th headers are saved too but without any further access so we skip it
431 $inno = 'x3JJHMbDL1EzLkh9GBhXDw==';
432 $outo = sha1($inno . $this->magicGUID);
434 for ($i = 0; $i < 20; $i++) {
435 $rawToken .= chr(hexdec(substr($outo,$i*2, 2)));
438 $outo = base64_encode($rawToken);
440 $webSocketKeyHash = sha1($headers['Sec-Websocket-Key'] . $this->magicGUID);
442 for ($i = 0; $i < 20; $i++) {
443 $rawToken .= chr(hexdec(substr($webSocketKeyHash,$i*2, 2)));
445 $handshakeToken = base64_encode($rawToken);
446 $subProtocol = (isset($headers['Sec-Websocket-Protocol'])) ?
447 $this->processProtocol($headers['Sec-Websocket-Protocol']) : "";
448 $extensions = (isset($headers['Sec-Websocket-Extensions'])) ?
449 $this->processExtensions($headers['Sec-Websocket-Extensions']) : "";
451 $headers_out['HTTP-Response'] = "101 Switching Protocols";
452 $headers_out['Upgrade'] = 'websocket';
453 $headers_out['Connection'] = 'Upgrade';
454 $headers_out['Sec-WebSocket-Accept'] = "$handshakeToken$subProtocol$extensions";
459 static function close()
461 return(chr(0x88).chr(0x02).chr(0xe8).chr(0x03));
464 static function fini($init_string, $base, $blockerr)
466 return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@', ($blockerr ? 'xstm.stop(); ' : ''), $base).self::close());
469 function is_chunked()
476 class Transport_xhr {
478 function Transport_xhr() {
481 function init($enc, $header, &$header_out, $init_string, $base, $step)
483 $ret = sprintf("@BEGIN@ /* %s */ @END@", $init_string);
485 $header_out['Content-Encoding'] = $enc;
486 $header_out['Cache-Control'] = 'no-cache, must-revalidate'; // HTTP/1.1
487 $header_out['Expires'] = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
488 $header_out['Content-type'] = 'application/xml; charset="utf-8"';
498 static function fini($init_string, $base, $blockerr)
500 return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@', ($blockerr ? 'xstm.stop(); ' : ''), $base));
504 function chunk($step, $cont)
506 return ("@BEGIN@".$cont."@END@");
509 function is_chunked()
515 class Transport_iframe {
517 function Transport_iframe() {
520 function init($enc, $header, &$header_out, $init_string, $base, $step)
525 $header_out['Content-Encoding'] = $enc;
526 $header_out['Cache-Control'] = 'no-cache, must-revalidate'; // HTTP/1.1
527 $header_out['Expires'] = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
528 $header_out['Content-type'] = 'text/html; charset="utf-8"';
530 $ret .= sprintf("<html>
532 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
533 <script type=\"text/javascript\" src=\"%sxynt-streaming-ifra.js\"></script>
534 <script type=\"text/javascript\">
535 var xynt_streaming = \"ready\";", $base, $base);
537 $ret .= sprintf("last_clean = %d;\n", ($step-1));
539 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.transp.stopped = true; } } catch(e) { /* console.log(\"catcha\"); */ } };
543 $ret .= sprintf("<!-- \n%s -->\n", $init_string);
553 static function fini($init_string, $base, $blockerr)
556 $ret .= sprintf("<html>
558 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
559 <script type=\"text/javascript\" src=\"%sxynt-streaming-ifra.js\"></script>
560 <script type=\"text/javascript\">
561 var xynt_streaming = \"ready\";", $base, $base);
563 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.reload(); } } catch(e) { /* console.log(\"catcha\"); */ } };
567 $ret .= sprintf("<!-- \n%s -->\n", $init_string);
568 $ret .= sprintf("<script id='hs%d' type='text/javascript'><!--
571 </script>", 0, escpush($blockerr) );
575 function chunk($step, $cont)
578 return sprintf("<script id='hs%d' type='text/javascript'><!--
579 push(null);\n// -->\n</script>", $step);
582 return sprintf("<script id='hs%d' type='text/javascript'><!--
583 push(\"%s\");\n// -->\n</script>", $step, escpush($cont) );
587 function is_chunked()
593 class Transport_htmlfile extends Transport_iframe {
601 static function create($transp)
603 if ($transp == 'websocket') {
604 return new Transport_websocket();
606 else if ($transp == 'xhr') {
607 return new Transport_xhr();
609 else if ($transp == 'htmlfile') {
610 return new Transport_htmlfile();
613 return new Transport_iframe();
616 static function gettype($transp)
618 if ($transp == 'websocket' || $transp == 'xhr' || $transp == 'htmlfile') {
619 return "Transport_".$transp;
622 return 'Transport_iframe';