cd0d6abb81bd0dc67a4795876e9d90fca90ac431
[brisk.git] / web / Obj / sac-a-push.phh
1 <?php
2
3 /*
4  *  brisk - spush/sac-a-push.phh
5  *
6  *  Copyright (C) 2012 Matteo Nastasi
7  *                          mailto: nastasi@alternativeoutput.it 
8  *                                  matteo.nastasi@milug.org
9  *                          web: http://www.alternativeoutput.it
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * General Public License for more details. You should have received a
20  * copy of the GNU General Public License along with this program; if
21  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
22  * Suite 330, Boston, MA 02111-1307, USA.
23  *
24  */
25
26 define('SITE_PREFIX', '/brisk/');
27 define('SITE_PREFIX_LEN', 7);
28
29 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
30 {
31     $check_post = FALSE;
32     $header = array();
33     $get = array();
34     $post = array();
35     foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
36         // printf("LINE: [%s]\n", $line);
37         if ($check_post) {
38             if (!isset($header['The-Request'])) {
39                 return FALSE;
40             }
41             $req = explode(" ", $header['The-Request']);
42             $method = $req[0];
43
44             if (isset($header['Cookie'])) {
45                 $cookies = explode(";", $header['Cookie']);
46                 for ($i = 0 ; $i < count($cookies) ; $i++) {
47                     $nameval = explode("=", trim($cookies[$i]));
48                     if (count($nameval) != 2) {
49                         printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
50                         continue;
51                     }
52                     $cookie[$nameval[0]] = urldecode($nameval[1]);
53                 }
54             }
55             // GET params management
56             $get_vars = explode('?', $req[1], 2);
57             $path =   $get_vars[0];
58             if (count($get_vars) > 1) {
59                 $a = explode('&', $get_vars[1]);
60                 printf("A COUNT: [%s] %d\n", $a[0], count($a));
61                 for ($i = 0 ; $i < count($a) ; $i++) {
62                     $b = explode('=', $a[$i]);
63                     $get[$b[0]] = urldecode($b[1]);
64                 }
65             }
66             // POST params management
67             if ($req[0] == 'POST') {
68                 if ($header['Content-Type'] != 'application/x-www-form-urlencoded' 
69                     || !isset($header['Content-Length'])) {
70                     return FALSE;
71                 }
72                 $post_len = mb_strlen($line, "latin1");
73                 $a = explode('&', $line);
74                 for ($i = 0 ; $i < count($a) ; $i++) {
75                     $b = explode('=', $a[$i]);
76                     $post[$b[0]] = urldecode($b[1]);
77                 }
78                 printf("INFO: postlen: %d\n", $post_len);
79             }
80             break;
81         }
82         if ($line == "") {
83             $check_post = TRUE;
84             continue;
85         }
86         $split = explode(":", $line, 2);
87         $header[$split[0]] = $split[1];        
88     }
89     return $path;
90 }
91
92 function gpcs_var($name, $get, $post, $cookie)
93 {
94     if (isset($GLOBALS[$name])) 
95         return FALSE;
96     else if (isset($cookie[$name])) 
97         return ($cookie[$name]);
98     else if (isset($post[$name])) 
99         return ($post[$name]);
100     else if (isset($get[$name])) 
101         return ($get[$name]);
102
103     return FALSE;
104 }
105
106 function headers_render($header, $len)
107 {
108     
109     $s = "";
110     $s .= "HTTP/1.1 200 OK\r\n";
111     if (!isset($header['Date']))
112         $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
113     if (!isset($header['Connection']))
114         $s .= "Connection: close\r\n";
115     if (!isset($header['Content-Type']))
116         $s .= "Content-Type: text/html\r\n";
117     foreach($header as $key => $value) {
118         $s .= sprintf("%s: %s\r\n", $key, $value);
119     }
120     if ($len == -1) {
121         $s .= "Cache-Control: no-cache, must-revalidate\r\n";
122         $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
123         $s .= "Content-Encoding: chunked\r\n";
124         $s .= "Transfer-Encoding: chunked\r\n";
125     }
126     else if ($len > 0) {
127         $s .= sprintf("Content-Length: %d\r\n", $len);
128     }
129     $s .= "\r\n";
130
131     return ($s);
132 }
133
134 /*
135  *  Caching system using ob php system to cache old style pages
136  *  to a var and than send it with more calm
137  */
138
139 function shutta()
140 {
141   log_rd2("SHUTTA [".connection_status()."] !");
142 }
143
144 register_shutdown_function('shutta');
145
146 /*
147  *  MAIN
148  */
149
150 function chunked_content($content)
151 {
152     $content_l = mb_strlen($content, "ASCII");
153
154     return (sprintf("%X\r\n%s\r\n", $content_l, $content));
155 }
156
157 function chunked_fini()
158 {
159     return sprintf("0\r\n");
160 }
161
162 class Sac_a_push {
163     static $fixed_fd = 2;
164     
165     var $file_socket;
166     var $unix_socket;
167     var $socks;
168     var $s2u;
169     var $pages_flush;
170
171     var $list;
172     var $in;
173
174     var $debug;
175     var $blocking_mode;
176
177     var $app;
178     var $bin5;
179
180     var $curtime;
181
182     var $rndstr;
183     var $main_loop;
184
185     function Sac_a_push()
186     {
187     }
188
189     // Sac_a_push::create("/tmp/brisk.sock", 0, 0
190
191     static function create(&$app, $sockname, $debug, $blocking_mode)
192     {        
193         $thiz = new Sac_a_push();
194         
195         $thiz->app = $app;
196         $thiz->file_socket = $sockname;
197         $thiz->unix_socket = "unix://$sockname";
198         $thiz->debug = $debug;
199         $thiz->socks = array();
200         $thiz->s2u  = array();
201         $thiz->pages_flush = array();
202
203         $thiz->blocking_mode = 0; // 0 for non-blocking
204
205         $thiz->rndstr = "";
206         for ($i = 0 ; $i < 4096 ; $i++) {
207             $thiz->rndstr .= chr(mt_rand(65, 90));
208         }
209         
210         if (file_exists($thiz->file_socket)) {
211             unlink($thiz->file_socket);
212         }
213     
214         $old_umask = umask(0);
215         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
216             return (FALSE);
217         }
218         umask($old_umask);
219         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
220
221         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
222             return(FALSE);
223         }
224
225         $thiz->main_loop = FALSE;
226
227         return ($thiz);
228     }
229
230     function socks_set($sock, $user)
231     {
232         $id = intval($sock);
233
234         $this->s2u[$id]   = $user;
235         $this->socks[$id] = $sock;
236     }
237
238     function socks_unset($sock)
239     {
240         $id = intval($sock);
241
242         unset($this->s2u[$id]);
243         unset($this->socks[$id]);
244     }
245
246     function pgflush_try_add(&$new_socket, $tout, $header_out, $content)
247     {
248         $pgflush = new PageFlush($new_socket, $this->curtime, $tout, $header_out, $content);
249
250         if ($pgflush->try_flush($this->curtime) == FALSE) {
251             // Add $pgflush to the pgflush array
252             $this->pgflush_add($pgflush);
253         }
254     }
255
256     function pgflush_add($pgflush)
257     {
258         array_push($this->pages_flush, $pgflush);
259     }
260
261     function run()
262     {
263         if ($this->main_loop) {
264             return (FALSE);
265         }
266         
267         $this->main_loop = TRUE;
268         
269         while ($this->main_loop) {
270             $this->curtime = time();
271             printf("IN LOOP: Current opened: %d  pages_flush: %d - ", count($this->socks), count($this->pages_flush));
272             
273             /* Prepare the read array */
274             /* // when we manage it ... */
275             /* if ($shutdown)  */
276             /*     $read   = array_merge(array("$in" => $in), $socks); */
277             /* else */
278             $read   = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
279                                   $this->socks);
280             
281             if ($this->debug > 1) {
282                 printf("PRE_SELECT\n");
283                 print_r($read);
284             }
285             $write  = NULL;
286             $except = NULL;
287             $num_changed_sockets = stream_select($read, $write, $except, 0, 250000);
288         
289             if ($num_changed_sockets == 0) {
290                 printf(" no data in 5 secs ");
291             } 
292             else if ($num_changed_sockets > 0) {
293                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
294                 if ($this->debug > 1) {
295                     print_r($read);
296                 }
297                 /* At least at one of the sockets something interesting happened */
298                 foreach ($read as $i => $sock) {
299                     /* is_resource check is required because there is the possibility that
300                        during new request an old connection is closed */
301                     if (!is_resource($sock)) {
302                         continue;
303                     }
304                     if ($sock === $this->list) {
305                         printf("NUOVA CONNEX\n");
306                         $new_unix = stream_socket_accept($this->list);
307                         $stream_info = "";
308                         $method      = "";
309                         $get         = array();
310                         $post        = array();
311                         $cookie      = array();
312                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
313                             printf("NEW_SOCKET: %d\n", intval($new_socket));
314                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
315                             printf("RECEIVED HEADER:\n%s", $stream_info);
316                             $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
317                             printf("PATH: [%s]\n", $path);
318                             printf("M: %s\nHEADER:\n", $method);
319                             print_r($header);
320                             printf("GET:\n");
321                             print_r($get);
322                             printf("POST:\n");
323                             print_r($post);
324                             printf("COOKIE:\n");
325                             print_r($cookie);
326
327                             $addr = stream_socket_get_name($new_socket, TRUE);
328                             $header_out = array();
329
330                             $subs = SITE_PREFIX."briskin5/";
331                             $subs_l = strlen($subs);
332                             $rret = FALSE;
333                             if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
334                                 $rret = $this->app->request_mgr($this, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
335                             }
336                             if ($rret == FALSE) { 
337                                 // FIXME: manage 404 !!!
338                                 printf("TODO: fix unknown page\n");
339                             }
340                             printf("number of sockets after %d\n", count($this->socks));
341                         }
342                         else {
343                             printf("WARNING: ancillary_getstream failed\n");
344                         }
345                     }
346                     else {
347                         if (($buf = fread($sock, 512)) === FALSE) {
348                             printf("error read\n");
349                         }
350                         else if (strlen($buf) === 0) {
351                             if ($sock === $this->list) {
352                                 printf("Arrivati %d bytes da list\n", strlen($buf));
353                             }
354                             else if ($sock === $this->in) {
355                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
356                             }
357                             else {
358                                 // $user_a[$s2u[intval($sock)]]->disable();
359                                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
360                                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
361                                 }
362                                 unset($this->socks[intval($sock)]);
363                                 unset($this->s2u[intval($sock)]);
364                                 fclose($sock);
365                                 printf("CLOSE ON READ\n");
366                             }
367                             if ($this->debug > 1) {
368                                 printf("post unset\n");
369                                 print_r($this->socks);
370                             }
371                         }
372                         else {
373                             if ($this->debug > 1) {
374                                 print_r($read);
375                             }
376                             if ($sock === $this->list) {
377                                 printf("Arrivati %d bytes da list\n", strlen($buf));
378                             }
379                             else if ($sock === $this->in) {
380                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
381                             }
382                             else {
383                                 $key = array_search("$sock", $this->socks);
384                                 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
385                             }
386                         }
387                     }
388                 }
389             }
390             
391
392             $this->app->garbage_manager(FALSE);
393
394
395             /* manage unfinished pages */
396             foreach ($this->pages_flush as $k => $pgflush) {
397                 if ($pgflush->try_flush($this->curtime) == TRUE) {
398                     unset($this->pages_flush[$k]);
399                 }
400             }
401             
402             /* manage open streaming */
403             foreach ($this->socks as $k => $sock) {
404                 if (isset($this->s2u[intval($sock)])) {
405                     $user = $this->s2u[intval($sock)];
406                     $response = $user->rd_cache_get();
407                     if (($this->curtime - $user->lacc) <= (EXPIRE_TIME_RD / 2)) {
408                         $user->ping_req = FALSE;
409                     }
410                     if ($response == "") {
411                         $content = "";
412                         $user->stream_main($content, $get, $post, $cookie);
413                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
414                         if ($content == "" && $user->ping_req == FALSE 
415                             && (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 2))) {
416                             $content = $user->stream_ping();
417                             $user->ping_req = TRUE;
418                         }
419                         if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
420                             $content = $user->stream_keepalive();
421                         }
422                         if ($content != "") {
423                             $response = chunked_content($content);
424                         }
425                     }
426                     
427                     if ($response != "") {
428                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
429                         echo "SPIA: [".$response."...]\n";
430                         $response_l = mb_strlen($response, "ASCII");
431                         $wret = @fwrite($sock, $response);
432                         if ($wret < $response_l) {
433                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
434                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
435                         }
436                         else {
437                             $user->rd_cache_set("");
438                         }
439                         fflush($sock);
440                         $user->rd_kalive_reset($this->curtime);
441                     }
442                     
443                     // close socket after a while to prevent client memory consumption
444                     if ($user->rd_endtime_is_expired($this->curtime)) {
445                         if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
446                             $this->s2u[intval($sock)]->rd_socket_set(NULL);
447                         }
448                         unset($this->socks[intval($sock)]);
449                         unset($this->s2u[intval($sock)]);
450                         fclose($sock);
451                         printf("CLOSE ON LOOP\n");
452                     }
453                 }
454             }  // foreach ($this->socks...
455             printf("\n");
456         }  // while (...
457     }  // function run(...
458 }
459
460 ?>