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($secure = FALSE) {
97 $this->type = ($secure == FALSE ? "websocket" : "websocketsec");
98 $this->headerOriginRequired = false;
99 $this->headerSecWebSocketProtocolRequired = false;
100 $this->headerSecWebSocketExtensionsRequired = false;
102 $this->sendingContinuous = false;
104 $this->handlingPartialPacket = false;
105 $this->partialMessage = "";
107 $this->hasSentClose = false;
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),
119 $header['length'] = (ord($message[1]) >= 128) ? ord($message[1]) - 128 : ord($message[1]);
121 if ($header['length'] == 126) {
122 if ($header['hasmask']) {
123 $header['mask'] = $message[4] . $message[5] . $message[6] . $message[7];
125 $header['length'] = ord($message[2]) * 256
127 } elseif ($header['length'] == 127) {
128 if ($header['hasmask']) {
129 $header['mask'] = $message[10] . $message[11] . $message[12] . $message[13];
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
139 } elseif ($header['hasmask']) {
140 $header['mask'] = $message[2] . $message[3] . $message[4] . $message[5];
142 //echo $this->strtohex($message);
143 //$this->printHeaders($header);
147 protected function extractPayload($message,$headers) {
149 if ($headers['hasmask']) {
152 if ($headers['length'] > 65535) {
154 } elseif ($headers['length'] > 125) {
157 return substr($message,$offset);
160 protected function applyMask($headers,$payload) {
162 if ($headers['hasmask']) {
163 $mask = $headers['mask'];
168 while (mb_strlen($effectiveMask, "ASCII") < mb_strlen($payload, "ASCII")) {
169 $effectiveMask .= $mask;
171 while (mb_strlen($effectiveMask, "ASCII") > mb_strlen($payload, "ASCII")) {
172 $effectiveMask = substr($effectiveMask,0,-1);
174 return $effectiveMask ^ $payload;
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
185 protected function strtohex($str) {
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]));
203 return $strout . "\n";
206 function unchunk($cont)
208 // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
209 return $this->deframe($cont);
212 function chunk($step, $cont)
214 // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
215 return $this->frame('@BEGIN@'.$cont.'@END@'); // , 'text', TRUE);
218 protected function frame($message, $messageType='text', $messageContinues=false) {
219 switch ($messageType) {
224 $b1 = ($this->sendingContinuous) ? 0 : 1;
227 $b1 = ($this->sendingContinuous) ? 0 : 2;
239 if ($messageContinues) {
240 $this->sendingContinuous = true;
243 $this->sendingContinuous = false;
246 $length = mb_strlen($message, "ASCII");
250 } elseif ($length <= 65536) {
252 $hexLength = dechex($length);
253 //$this->stdout("Hex Length: $hexLength");
254 if (mb_strlen($hexLength, "ASCII")%2 == 1) {
255 $hexLength = '0' . $hexLength;
257 $n = mb_strlen($hexLength, "ASCII") - 2;
259 for ($i = $n; $i >= 0; $i=$i-2) {
260 $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
262 while (mb_strlen($lengthField, "ASCII") < 2) {
263 $lengthField = chr(0) . $lengthField;
267 $hexLength = dechex($length);
268 if (mb_strlen($hexLength, "ASCII")%2 == 1) {
269 $hexLength = '0' . $hexLength;
271 $n = mb_strlen($hexLength, "ASCII") - 2;
273 for ($i = $n; $i >= 0; $i=$i-2) {
274 $lengthField = chr(hexdec(substr($hexLength, $i, 2))) . $lengthField;
276 while (mb_strlen($lengthField, "ASCII") < 8) {
277 $lengthField = chr(0) . $lengthField;
281 return chr($b1) . chr($b2) . $lengthField . $message;
284 protected function deframe($message) {
285 //echo $this->strtohex($message);
286 $headers = $this->extractHeaders($message);
289 switch($headers['opcode']) {
295 // todo: close the connection
296 $this->hasSentClose = true;
303 //$this->disconnect($user); // todo: fail connection
308 if ($this->handlingPartialPacket) {
309 $message = $this->partialBuffer . $message;
310 $this->handlingPartialPacket = false;
311 return $this->deframe($message);
314 if ($this->checkRSVBits($headers,$this)) {
319 // todo: fail the connection
323 $payload = $this->partialMessage . $this->extractPayload($message,$headers);
326 $reply = $this->frame($payload,$this,'pong');
327 // TODO FIXME ALL socket_write management
328 socket_write($user->socket,$reply,mb_strlen($reply, "ASCII"));
331 if (extension_loaded('mbstring')) {
332 if ($headers['length'] > mb_strlen($payload, "ASCII")) {
333 $this->handlingPartialPacket = true;
334 $this->partialBuffer = $message;
338 if ($headers['length'] > mb_strlen($payload, "ASCII")) {
339 $this->handlingPartialPacket = true;
340 $this->partialBuffer = $message;
345 $payload = $this->applyMask($headers,$payload);
347 if ($headers['fin']) {
348 $this->partialMessage = "";
351 $this->partialMessage = $payload;
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.
362 protected function checkOrigin($origin) {
363 return true; // Override and return false if the origin is not one that you would expect.
366 protected function checkWebsocProtocol($protocol) {
367 return true; // Override and return false if a protocol is not found that you would expect.
370 protected function checkWebsocExtensions($extensions) {
371 return true; // Override and return false if an extension is not found that you would expect.
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.
381 protected function processExtensions($extensions) {
382 return ""; // return either "Sec-WebSocket-Extensions: SelectedExtensions\r\n" or return an empty string.
385 function init($enc, $headers, &$headers_out, $init_string, $base, $step)
387 if (0) { // TODO: what is ?
388 if (isset($headers['get'])) {
389 $this->requestedResource = $headers['get'];
391 // todo: fail the connection
392 $headers_out['HTTP-Response'] = "405 Method Not Allowed";
396 if (!isset($headers['Host']) || !$this->checkHost($headers['Host'])) {
397 // error_log('bad 1');
398 $headers_out['HTTP-Response'] = "400 Bad Request";
400 if (!isset($headers['Upgrade']) || strtolower($headers['Upgrade']) != 'websocket') {
401 // error_log('bad 2 ' . $headers['Upgrade']);
402 $headers_out['HTTP-Response'] = "400 Bad Request";
404 if (!isset($headers['Connection']) || strpos(strtolower($headers['Connection']), 'upgrade') === FALSE) {
405 // error_log('bad 3');
406 $headers_out['HTTP-Response'] = "400 Bad Request";
408 if (!isset($headers['Sec-Websocket-Key'])) {
409 // error_log('bad 4');
410 $headers_out['HTTP-Response'] = "400 Bad Request";
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";
418 if ( ($this->headerOriginRequired && !isset($headers['Origin']) )
419 || ($this->headerOriginRequired && !$this->checkOrigin($headers['Origin'])) ) {
420 $headers_out['HTTP-Response'] = "403 Forbidden";
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";
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";
435 if (isset($headers_out['HTTP-Response'])) {
436 // TODO: check return management
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
446 $inno = 'x3JJHMbDL1EzLkh9GBhXDw==';
447 $outo = sha1($inno . $this->magicGUID);
449 for ($i = 0; $i < 20; $i++) {
450 $rawToken .= chr(hexdec(substr($outo,$i*2, 2)));
453 $outo = base64_encode($rawToken);
455 $webSocketKeyHash = sha1($headers['Sec-Websocket-Key'] . $this->magicGUID);
457 for ($i = 0; $i < 20; $i++) {
458 $rawToken .= chr(hexdec(substr($webSocketKeyHash,$i*2, 2)));
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']) : "";
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";
474 static function close()
476 return(chr(0x88).chr(0x02).chr(0xe8).chr(0x03));
479 static function fini($init_string, $base, $blockerr)
481 return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@', ($blockerr ? 'xstm.stop(); ' : ''), $base).self::close());
484 function is_chunked()
491 class Transport_xhr {
493 function Transport_xhr() {
497 function init($enc, $header, &$header_out, $init_string, $base, $step)
499 $ret = sprintf("@BEGIN@ /* %s */ @END@", $init_string);
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"';
514 static function fini($init_string, $base, $blockerr)
516 return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@', ($blockerr ? 'xstm.stop(); ' : ''), $base));
520 function chunk($step, $cont)
522 // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
523 return ("@BEGIN@".$cont."@END@");
526 function is_chunked()
532 class Transport_iframe {
534 function Transport_iframe() {
535 $this->type = 'iframe';
538 function init($enc, $header, &$header_out, $init_string, $base, $step)
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"';
548 $ret .= sprintf("<html>
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);
555 $ret .= sprintf("last_clean = %d;\n", ($step-1));
557 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.transp.stopped = true; } } catch(e) { /* console.log(\"catcha\"); */ } };
561 $ret .= sprintf("<!-- \n%s -->\n", $init_string);
571 static function fini($init_string, $base, $blockerr)
574 $ret .= sprintf("<html>
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);
581 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.reload(); } } catch(e) { /* console.log(\"catcha\"); */ } };
585 $ret .= sprintf("<!-- \n%s -->\n", $init_string);
586 $ret .= sprintf("<script id='hs%d' type='text/javascript'><!--
589 </script>", 0, escpush($blockerr) );
593 function chunk($step, $cont)
595 // fprintf(STDERR, "CHUNK: [%s]\n", $cont);
597 return sprintf("<script id='hs%d' type='text/javascript'><!--
598 push(null);\n// -->\n</script>", $step);
601 return sprintf("<script id='hs%d' type='text/javascript'><!--
602 push(\"%s\");\n// -->\n</script>", $step, escpush($cont) );
606 function is_chunked()
612 class Transport_htmlfile extends Transport_iframe {
613 function Transport_htmlfile() {
614 $this->type = 'htmlfile';
623 static function create($transp)
625 if ($transp == 'websocket' || $transp == 'websocketsec') {
626 return new Transport_websocket($transp == 'websocketsec');
628 else if ($transp == 'xhr') {
629 return new Transport_xhr();
631 else if ($transp == 'htmlfile') {
632 return new Transport_htmlfile();
635 return new Transport_iframe();
638 static function gettype($transp)
640 if ($transp == 'websocket' || $transp == 'xhr' || $transp == 'htmlfile') {
641 return "Transport_".$transp;
644 return 'Transport_iframe';