transport API: add header argument to the init methon (required by websocket handshake)
[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  *   XHR | IW | FF | Ch | Op | Ko | IE
40  * ------+----+----+----+----+----+----
41  *   Lnx | Y  |    | ^D |    | Y  | x
42  *   Win | x  | Y  | Y  |    |    | N
43  *   Mac | x  |    |    |    |    |
44  *
45  *
46  * HtmlFl| IW | FF | Ch | Op | Ko | IE
47  * ------+----+----+----+----+----+----
48  *   Lnx | N  |    |    |    | N  |
49  *   Win | x  | N  | N  |    |    | Y* (* seems delay between click and load of a new page)
50  *   Mac | x  |    |    |    |    |
51  *
52  *
53  */
54
55
56 class Transport_template {
57
58     function Transport_template() {
59     }
60
61     // return string value is appended to the content of the returned page
62     function init($enc, $header, &$header_out, $init_string, $base, $step)
63     {
64     }
65
66     static function fini($init_string, $base, $blockerr)
67     {
68     }
69
70     function chunk($step, $cont)
71     {
72     }
73 }
74
75 class Transport_websocket {
76     $magicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
77
78     function Transport_websocket() {
79     }
80
81     protected function doHandshake($user, $buffer) {
82         $magicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
83         $headers = array();
84         $lines = explode("\n",$buffer);
85         foreach ($lines as $line) {
86             if (strpos($line,":") !== false) {
87                 $header = explode(":",$line,2);
88                 $headers[strtolower(trim($header[0]))] = trim($header[1]);
89             } else if (stripos($line,"get ") !== false) {
90                 preg_match("/GET (.*) HTTP/i", $buffer, $reqResource);
91                 $headers['get'] = trim($reqResource[1]);
92             }
93         }
94         if (isset($headers['get'])) {
95             $user->requestedResource = $headers['get'];
96         } else {
97             // todo: fail the connection
98             $handshakeResponse = "HTTP/1.1 405 Method Not Allowed\r\n\r\n";                     
99         }
100         if (!isset($headers['host']) || !$this->checkHost($headers['host'])) {
101             $handshakeResponse = "HTTP/1.1 400 Bad Request";
102         }
103         if (!isset($headers['upgrade']) || strtolower($headers['upgrade']) != 'websocket') {
104             $handshakeResponse = "HTTP/1.1 400 Bad Request";
105         } 
106         if (!isset($headers['connection']) || strpos(strtolower($headers['connection']), 'upgrade') === FALSE) {
107             $handshakeResponse = "HTTP/1.1 400 Bad Request";
108         }
109         if (!isset($headers['sec-websocket-key'])) {
110             $handshakeResponse = "HTTP/1.1 400 Bad Request";
111         } else {
112             
113         }
114         if (!isset($headers['sec-websocket-version']) || strtolower($headers['sec-websocket-version']) != 13) {
115             $handshakeResponse = "HTTP/1.1 426 Upgrade Required\r\nSec-WebSocketVersion: 13";
116         }
117         if (($this->headerOriginRequired && !isset($headers['origin']) ) || ($this->headerOriginRequired && !$this->checkOrigin($headers['origin']))) {
118             $handshakeResponse = "HTTP/1.1 403 Forbidden";
119         }
120         if (($this->headerSecWebSocketProtocolRequired && !isset($headers['sec-websocket-protocol'])) || ($this->headerSecWebSocketProtocolRequired && !$this->checkWebsocProtocol($header['sec-websocket-protocol']))) {
121             $handshakeResponse = "HTTP/1.1 400 Bad Request";
122         }
123         if (($this->headerSecWebSocketExtensionsRequired && !isset($headers['sec-websocket-extensions'])) || ($this->headerSecWebSocketExtensionsRequired && !$this->checkWebsocExtensions($header['sec-websocket-extensions']))) {
124             $handshakeResponse = "HTTP/1.1 400 Bad Request";
125         }
126         
127         // Done verifying the _required_ headers and optionally required headers.
128         
129         if (isset($handshakeResponse)) {
130             socket_write($user->socket,$handshakeResponse,strlen($handshakeResponse));
131             $this->disconnect($user->socket);
132             return false;
133         }
134         
135         $user->headers = $headers;
136         $user->handshake = $buffer;
137         
138         $webSocketKeyHash = sha1($headers['sec-websocket-key'] . $magicGUID);
139         
140         $rawToken = "";
141         for ($i = 0; $i < 20; $i++) {
142             $rawToken .= chr(hexdec(substr($webSocketKeyHash,$i*2, 2)));
143         }
144         $handshakeToken = base64_encode($rawToken) . "\r\n";
145         
146         $subProtocol = (isset($headers['sec-websocket-protocol'])) ? $this->processProtocol($headers['sec-websocket-protocol']) : "";
147         $extensions = (isset($headers['sec-websocket-extensions'])) ? $this->processExtensions($headers['sec-websocket-extensions']) : "";
148         
149         $handshakeResponse = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: $handshakeToken$subProtocol$extensions\r\n";
150         socket_write($user->socket,$handshakeResponse,strlen($handshakeResponse));
151         $this->connected($user);
152     }
153     
154
155     function init($enc, $header, &$header_out, $init_string, $base, $step)
156     {
157         
158
159
160
161         $ret = sprintf("@BEGIN@ /* %s */ @END@", $init_string);
162         if ($enc != 'plain')
163             $header_out['Content-Encoding'] = $enc;
164         $header_out['Cache-Control'] = 'no-cache, must-revalidate';     // HTTP/1.1
165         $header_out['Expires']       = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
166         $header_out['Content-type']  = 'application/xml; charset="utf-8"';
167
168         return ($ret);
169     }
170
171     static function fini($init_string, $base, $blockerr)
172     {
173         return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@',  ($blockerr ? 'xstm.stop(); ' : ''), $base));
174         return ("");
175     }
176
177     function chunk($step, $cont)
178     {
179         return ("@BEGIN@".$cont."@END@");
180     }
181 }
182
183 class Transport_xhr {
184
185     function Transport_xhr() {
186     }
187
188     function init($enc, $header, &$header_out, $init_string, $base, $step)
189     {
190         $ret = sprintf("@BEGIN@ /* %s */ @END@", $init_string);
191         if ($enc != 'plain')
192             $header_out['Content-Encoding'] = $enc;
193         $header_out['Cache-Control'] = 'no-cache, must-revalidate';     // HTTP/1.1
194         $header_out['Expires']       = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
195         $header_out['Content-type']  = 'application/xml; charset="utf-8"';
196
197         return ($ret);
198     }
199
200     static function fini($init_string, $base, $blockerr)
201     {
202         return (sprintf('@BEGIN@ %s window.onbeforeunload = null; window.onunload = null; document.location.assign("%sindex.php"); @END@',  ($blockerr ? 'xstm.stop(); ' : ''), $base));
203         return ("");
204     }
205
206     function chunk($step, $cont)
207     {
208         return ("@BEGIN@".$cont."@END@");
209     }
210 }
211
212 class Transport_iframe {
213
214     function Transport_iframe() {
215     }
216
217     function init($enc, $header, &$header_out, $init_string, $base, $step)
218     {
219         $ret = "";
220
221         if ($enc != 'plain')
222             $header_out['Content-Encoding'] = $enc;
223         $header_out['Cache-Control'] = 'no-cache, must-revalidate';     // HTTP/1.1
224         $header_out['Expires']       = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
225         $header_out['Content-type']  = 'text/html; charset="utf-8"';
226         
227         $ret .= sprintf("<html>
228 <head>
229 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
230 <script type=\"text/javascript\" src=\"%sxynt-streaming-ifra.js\"></script>
231 <script type=\"text/javascript\">
232 var xynt_streaming = \"ready\";", $base, $base);
233         if ($step > 0)
234             $ret .= sprintf("last_clean = %d;\n", ($step-1));
235         $ret .= sprintf("
236 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.transp.stopped = true; } } catch(e) { /* console.log(\"catcha\"); */ } };
237 </script> 
238 </head>
239 <body>");
240         $ret .= sprintf("<!-- \n%s -->\n", $init_string);
241
242         return ($ret);
243     }
244
245     static function fini($init_string, $base, $blockerr)
246     {
247         $ret = "";
248         $ret .= sprintf("<html>
249 <head>
250 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
251 <script type=\"text/javascript\" src=\"%sxynt-streaming-ifra.js\"></script>
252 <script type=\"text/javascript\">
253 var xynt_streaming = \"ready\";", $base, $base);
254         $ret .= sprintf("
255 window.onload = function () { try { if (xynt_streaming != \"ready\") { xynt_streaming.reload(); } } catch(e) { /* console.log(\"catcha\"); */ } };
256 </script>
257 </head>
258 <body>");
259         $ret .= sprintf("<!-- \n%s -->\n", $init_string);
260         $ret .= sprintf("<script id='hs%d' type='text/javascript'><!--
261 push(\"%s\");
262 // -->
263 </script>", 0, escpush($blockerr) );
264         return ($ret);
265     }
266
267     function chunk($step, $cont)
268     {
269         if ($cont == NULL) {
270             return sprintf("<script id='hs%d' type='text/javascript'><!--
271 push(null);\n// -->\n</script>", $step);
272         }
273         else {
274             return sprintf("<script id='hs%d' type='text/javascript'><!--
275 push(\"%s\");\n// -->\n</script>", $step, escpush($cont) );
276         }
277     }
278 }
279
280 class Transport_htmlfile extends Transport_iframe {
281 }
282
283 class Transport {
284     function Transport()
285     {
286     }
287
288     static function create($transp)
289     {
290         if ($transp == 'xhr') {
291             return new Transport_xhr();
292         }
293         else if ($transp == 'htmlfile') {
294             return new Transport_htmlfile();
295         }
296         else  {
297             return new Transport_iframe();
298         }
299     }
300     static function gettype($transp)
301     {
302         if ($transp == 'xhr' || $transp == 'htmlfile') {
303             return "Transport_".$transp;
304         }
305         else {
306             return 'Transport_iframe';
307         }
308     }
309 }
310 ?>