enhanced POST management
[brisk.git] / web / Obj / sac-a-push.phh
1 <?php
2 /*
3  *  brisk - Obj/sac-a-push.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 define('SITE_PREFIX', '/brisk/');
26 define('SITE_PREFIX_LEN', 7);
27
28 declare(ticks = 1);
29
30 function global_dump()
31 {
32     GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
33     GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
34     GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
35     GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
36     GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
37     GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
38     GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
39     GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
40     GLOBAL $G_with_topbanner;
41
42     fprintf(STDERR, "G_alarm_passwd = [%s]\n", print_r($G_alarm_passwd, TRUE));
43     fprintf(STDERR, "G_black_list = [%s]\n", print_r($G_black_list, TRUE));
44     fprintf(STDERR, "G_btrace_pref_sub = [%s]\n", print_r($G_btrace_pref_sub, TRUE));
45     fprintf(STDERR, "G_dbauth = [%s]\n", print_r($G_dbauth, TRUE));
46     fprintf(STDERR, "G_dbpfx = [%s]\n", print_r($G_dbpfx, TRUE));
47     fprintf(STDERR, "G_donors_all = [%s]\n", print_r($G_donors_all, TRUE));
48     fprintf(STDERR, "G_donors_cur = [%s]\n", print_r($G_donors_cur, TRUE));
49     fprintf(STDERR, "G_is_local = [%s]\n", print_r($G_is_local, TRUE));
50     fprintf(STDERR, "G_lang = [%s]\n", print_r($G_lang, TRUE));
51     fprintf(STDERR, "G_poll_entries = [%s]\n", print_r($G_poll_entries, TRUE));
52     fprintf(STDERR, "G_poll_name = [%s]\n", print_r($G_poll_name, TRUE));
53     fprintf(STDERR, "G_poll_title = [%s]\n", print_r($G_poll_title, TRUE));
54     fprintf(STDERR, "G_proxy_white_list = [%s]\n", print_r($G_proxy_white_list, TRUE));
55     fprintf(STDERR, "G_room_roadmap = [%s]\n", print_r($G_room_roadmap, TRUE));
56     fprintf(STDERR, "G_shutdown = [%s]\n", print_r($G_shutdown, TRUE));
57     fprintf(STDERR, "G_sidebanner = [%s]\n", print_r($G_sidebanner, TRUE));
58     fprintf(STDERR, "G_sidebanner2 = [%s]\n", print_r($G_sidebanner2, TRUE));
59     fprintf(STDERR, "G_splash_content = [%s]\n", print_r($G_splash_content, TRUE));
60     fprintf(STDERR, "G_splash_contents = [%s]\n", print_r($G_splash_contents, TRUE));
61     fprintf(STDERR, "G_splash_cont_idx = [%s]\n", print_r($G_splash_cont_idx, TRUE));
62     fprintf(STDERR, "G_splash_h = [%s]\n", print_r($G_splash_h, TRUE));
63     fprintf(STDERR, "G_splash_idx = [%s]\n", print_r($G_splash_idx, TRUE));
64     fprintf(STDERR, "G_splash_interval = [%s]\n", print_r($G_splash_interval, TRUE));
65     fprintf(STDERR, "G_splash_timeout = [%s]\n", print_r($G_splash_timeout, TRUE));
66     fprintf(STDERR, "G_splash_w = [%s]\n", print_r($G_splash_w, TRUE));
67     fprintf(STDERR, "G_topbanner = [%s]\n", print_r($G_topbanner, TRUE));
68     fprintf(STDERR, "G_with_donors = [%s]\n", print_r($G_with_donors, TRUE));
69     fprintf(STDERR, "G_with_poll = [%s]\n", print_r($G_with_poll, TRUE));
70     fprintf(STDERR, "G_with_sidebanner = [%s]\n", print_r($G_with_sidebanner, TRUE));
71     fprintf(STDERR, "G_with_sidebanner2 = [%s]\n", print_r($G_with_sidebanner2, TRUE));
72     fprintf(STDERR, "G_with_splash = [%s]\n", print_r($G_with_splash, TRUE));
73     fprintf(STDERR, "G_with_topbanner = [%s]\n", print_r($G_with_topbanner, TRUE));
74 }
75
76 function pid_save()
77 {
78     $pid = getmypid();
79     $fname = LEGAL_PATH."/brisk.pid";
80
81     if (file_exists($fname)) {
82         log_crit("WARN: brisk.pid already exists");
83     }
84     file_put_contents($fname, sprintf("%d\n", $pid));
85 }
86
87 function pid_remove()
88 {
89     $fname = LEGAL_PATH."/brisk.pid";
90
91     if (file_exists($fname)) {
92         unlink($fname);
93     }
94 }
95
96 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
97 {
98     $check_post = FALSE;
99     $header = array();
100     $get = array();
101     $post = array();
102     foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
103         // printf("LINE: [%s]\n", $line);
104         if ($check_post) {
105             if (!isset($header['The-Request'])) {
106                 return FALSE;
107             }
108             $req = explode(" ", $header['The-Request']);
109             $method = $req[0];
110
111             if (isset($header['Cookie'])) {
112                 $cookies = explode(";", $header['Cookie']);
113                 for ($i = 0 ; $i < count($cookies) ; $i++) {
114                     $nameval = explode("=", trim($cookies[$i]));
115                     if (count($nameval) != 2) {
116                         printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
117                         continue;
118                     }
119                     $cookie[$nameval[0]] = urldecode($nameval[1]);
120                 }
121             }
122             // GET params management
123             $get_vars = explode('?', $req[1], 2);
124             $path = $get_vars[0];
125             if (count($get_vars) > 1) {
126                 $a = explode('&', $get_vars[1]);
127                 printf("A COUNT: [%s] %d\n", $a[0], count($a));
128                 for ($i = 0 ; $i < count($a) ; $i++) {
129                     $b = explode('=', $a[$i]);
130                     $get[$b[0]] = urldecode($b[1]);
131                 }
132             }
133             // POST params management
134             if ($req[0] == 'POST') {
135                 $conttype_all = explode(";", $header['Content-Type']);
136                 $header['Content-Type'] = $conttype_all[0];
137                 // $path_all[1-] other things like charset and so on
138
139                 if ($header['Content-Type'] != 'application/x-www-form-urlencoded' 
140                     || !isset($header['Content-Length'])) {
141                     return FALSE;
142                 }
143                 $post_len = mb_strlen($line, "ASCII");
144                 $a = explode('&', $line);
145                 for ($i = 0 ; $i < count($a) ; $i++) {
146                     $b = explode('=', $a[$i]);
147                     $post[$b[0]] = urldecode($b[1]);
148                 }
149                 printf("INFO: postlen: %d\n", $post_len);
150             }
151             break;
152         }
153         if ($line == "") {
154             $check_post = TRUE;
155             continue;
156         }
157         $split = explode(":", $line, 2);
158         $header[$split[0]] = $split[1];        
159     }
160     return $path;
161 }
162
163 function gpcs_var($name, $get, $post, $cookie)
164 {
165     if (isset($GLOBALS[$name])) 
166         return FALSE;
167     else if (isset($cookie[$name])) 
168         return ($cookie[$name]);
169     else if (isset($post[$name])) 
170         return ($post[$name]);
171     else if (isset($get[$name])) 
172         return ($get[$name]);
173
174     return FALSE;
175 }
176
177 function headers_render($header, $len)
178 {
179     $cookies = "";
180
181     if (isset($header['cookies'])) {
182         $cookies = $header['cookies']->render();
183         unset($header['cookies']);
184     }
185     if (isset($header['Location'])) {
186         $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
187     }
188     else {
189         $s = "HTTP/1.1 200 OK\r\n";
190
191         if (!isset($header['Date']))
192             $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
193         if (!isset($header['Connection']))
194             $s .= "Connection: close\r\n";
195         if (!isset($header['Content-Type']))
196             $s .= "Content-Type: text/html\r\n";
197         foreach($header as $key => $value) {
198             $s .= sprintf("%s: %s\r\n", $key, $value);
199         }
200         if ($len >= 0) {
201             $s .= sprintf("Content-Length: %d\r\n", $len);
202         }
203         else {
204             $s .= "Cache-Control: no-cache, must-revalidate\r\n";
205             $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
206             if (!isset($header['Content-Encoding'])) {
207                 $s .= "Content-Encoding: chunked\r\n";
208             }
209             $s .= "Transfer-Encoding: chunked\r\n";
210         }
211         $s .= $cookies;
212     }
213     $s .= "\r\n";
214
215     return ($s);
216 }
217
218 /*
219  *  Caching system using ob php system to cache old style pages
220  *  to a var and than send it with more calm
221  */
222
223 function shutta()
224 {
225   log_rd2("SHUTTA [".connection_status()."] !");
226 }
227
228 register_shutdown_function('shutta');
229
230 /*
231  *  MAIN
232  */
233
234 function chunked_content($zls, $content)
235 {
236     if ($zls) {
237         $cont_comp = $zls->compress_chunk($content);
238     }
239     else {
240         $cont_comp = $content;
241     }
242     $cont_comp_l = mb_strlen($cont_comp, "ASCII");
243     printf("CHUNK: [%s]\n", $content);
244
245     return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
246 }
247
248 function chunked_fini()
249 {
250     return sprintf("0\r\n");
251 }
252
253 function get_encoding($header)
254 {
255     $enc = "plain";
256     if (isset($header['Accept-Encoding'])) {
257         $acc = explode(',', $header['Accept-Encoding']);
258
259         if (array_search('gzip', $acc) !== FALSE) {
260             $enc = 'gzip';
261         }
262         else if (array_search('deflate', $acc) !== FALSE) {
263             $enc = 'deflate';
264         }
265     }
266
267     return ($enc);
268 }
269
270 class Cookie {
271     var $attr;
272     // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
273     // string $name  [, string $value  [, int $expire = 0  [, string $path  [, string $domain  [, bool $secure = false  [, bool $httponly = false  ]]]]]] )
274     function Cookie()
275     {
276         $this->attr = array();
277     }
278
279     static function create($name)
280     {
281         $thiz = new Cookie();
282
283         $thiz->attr[$name] = "";
284
285         $argc = func_num_args();
286         for ($i = 1 ; $i < $argc ; $i++) {
287             $arg = func_get_arg($i);
288             switch ($i) {
289             case 1:
290                 $thiz->attr[$name] = urlencode($arg);
291                 break;
292             case 2:
293                 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
294                 break;
295             case 3:
296                 $thiz->attr['Path'] = $arg;
297                 break;
298             case 4:
299                 $thiz->attr['Domain'] = $arg;
300                 break;
301             case 5:
302                 if ($arg == TRUE) {
303                     $thiz->attr['Secure'] = NULL;
304                 }
305                 break;
306             case 6:
307                 if ($arg == TRUE) {
308                     $thiz->attr['HttpOnly'] = NULL;
309                 }
310                 break;
311             default:
312                 return FALSE;
313             }
314         }
315
316         return $thiz;
317     }
318
319     function render()
320     {
321         $r = "Set-Cookie: ";
322         $isfirst = TRUE;
323
324         foreach ($this->attr as $k => $v) {
325             if ($v == NULL) {
326                 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
327             }
328             else {
329                 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
330             }
331             $isfirst = FALSE;
332         }
333         $r .= "\r\n";
334
335         return $r;
336     }
337 }
338
339 class Cookies {
340     var $cookies;
341
342     function Cookies()
343     {
344         $this->cookies = array();
345     }
346
347     function add($name)
348     {
349         if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
350             return (FALSE);
351
352         array_push($this->cookies, $cookie);
353
354         return (TRUE);
355     }
356
357     function render()
358     {
359         $r = "";
360         foreach ($this->cookies as $cookie) {
361             $r .= $cookie->render();
362         }
363
364         return ($r);
365     }
366 }
367
368
369 class Sac_a_push {
370     // maybe fixed_fd is unuseful
371     static $fixed_fd = 3;
372     static $cnt_master = NULL;
373     static $cnt_slave  = NULL;
374     
375     var $file_socket;
376     var $unix_socket;
377     var $socks;
378     var $s2u;
379     var $pending_pages;
380
381     var $list;
382     var $in;
383
384     var $debug;
385     var $blocking_mode;
386
387     var $app;
388
389     var $curtime;
390
391     var $rndstr;
392     var $main_loop;
393
394     function Sac_a_push()
395     {
396     }
397
398     function sig_handler($sig)
399     {
400         switch ($sig) {
401         case SIGINT:
402             exit(1);
403             break;
404         case SIGTERM:
405             if (static::$cnt_master != NULL) {
406                     fwrite(static::$cnt_master, "\nshutdown\n");
407                     fflush(static::$cnt_master);
408             }
409             else {
410                 exit(1);
411             }
412             break;
413         case SIGHUP: 
414             if (static::$cnt_master != NULL) {
415                 fwrite(static::$cnt_master, "\nreload\n");
416                 fflush(static::$cnt_master);
417             }
418             break;
419         }
420     }
421
422     static function create(&$app, $sockname, $debug, $blocking_mode)
423     {        
424         $thiz = new Sac_a_push();
425         
426         $thiz->app = $app;
427         $thiz->file_socket = $sockname;
428         $thiz->unix_socket = "unix://$sockname";
429         $thiz->debug = $debug;
430         $thiz->socks = array();
431         $thiz->s2u  = array();
432         $thiz->pending_pages = array();
433
434         // create a couple of sockets for control management
435         if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
436                                             STREAM_IPPROTO_IP)) == FALSE) {
437             return FALSE;
438         }
439         static::$cnt_master = $sockpair[0];
440         static::$cnt_slave  = $sockpair[1];
441
442         pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
443         pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
444         pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
445
446         $thiz->blocking_mode = 0; // 0 for non-blocking
447
448         $thiz->rndstr = "";
449         for ($i = 0 ; $i < 4096 ; $i++) {
450             if (($i % 128) == 0)
451                 $thiz->rndstr .= " ";
452             else
453                 $thiz->rndstr .= chr(mt_rand(65, 90));
454         }
455         
456         if (file_exists($thiz->file_socket)) {
457             unlink($thiz->file_socket);
458         }
459     
460         $old_umask = umask(0);
461         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
462             return (FALSE);
463         }
464         umask($old_umask);
465         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
466
467         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
468             return(FALSE);
469         }
470
471         $thiz->main_loop = FALSE;
472
473         return ($thiz);
474     }
475
476     function socks_set($sock, $user)
477     {
478         $id = intval($sock);
479
480         $this->s2u[$id]   = $user;
481         $this->socks[$id] = $sock;
482     }
483
484     function socks_unset($sock)
485     {
486         $id = intval($sock);
487
488         unset($this->s2u[$id]);
489         unset($this->socks[$id]);
490     }
491
492     function pendpage_try_addflush($enc, &$new_socket, $tout, $header_out, $content)
493     {
494         $pgflush = PendingPage::pendingpage_flushing($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
495
496         if ($pgflush->try_flush($this->curtime) == FALSE) {
497             // Add $pgflush to the pgflush array
498             $this->pgflush_add($pgflush);
499         }
500     }
501
502     function pgflush_add($pgflush)
503     {
504         array_push($this->pending_pages, $pgflush);
505     }
506
507     function garbage_manager($force)
508     {
509         $this->app->garbage_manager($force);
510
511         foreach ($this->socks as $k => $sock) {
512             if ($this->s2u[intval($sock)]->sess == '') {
513                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
514                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
515                 }
516                 unset($this->socks[intval($sock)]);
517                 unset($this->s2u[intval($sock)]);
518                 fclose($sock);
519                 printf("CLOSE ON GARBAGE MANAGER\n");
520             }
521         }
522     }
523
524     function run()
525     {
526         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
527
528         GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
529         GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
530         GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
531         GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
532         GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
533         GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
534         GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
535         GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
536         GLOBAL $G_with_topbanner;
537
538         if ($this->main_loop) {
539             return (FALSE);
540         }
541         
542         $this->main_loop = TRUE;
543         
544         while ($this->main_loop) {
545             $this->curtime = time();
546             printf("IN LOOP: Current opened: %d  pending_pages: %d - ", count($this->socks), count($this->pending_pages));
547             
548             /* Prepare the read array */
549             /* // when we manage it ... */
550             /* if ($shutdown)  */
551             /*     $read   = array_merge(array("$in" => $in), $socks); */
552             /* else */
553             $read   = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in,
554                                         intval(static::$cnt_slave) => static::$cnt_slave),
555                                   $this->socks);
556             
557             if ($this->debug > 1) {
558                 printf("PRE_SELECT\n");
559                 print_r($read);
560             }
561             $write  = NULL;
562             $except = NULL;
563             $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
564         
565             if ($num_changed_sockets == 0) {
566                 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
567             } 
568             else if ($num_changed_sockets > 0) {
569                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
570                 if ($this->debug > 1) {
571                     print_r($read);
572                 }
573                 /* At least at one of the sockets something interesting happened */
574                 foreach ($read as $i => $sock) {
575                     /* is_resource check is required because there is the possibility that
576                        during new request an old connection is closed */
577                     if (!is_resource($sock)) {
578                         continue;
579                     }
580                     if ($sock === $this->list) {
581                         printf("NUOVA CONNEX\n");
582                         if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
583                             printf("SOCKET_ACCEPT FAILED\n");
584                             continue;
585                         }
586                         $stream_info = "";
587                         $method      = "";
588                         $get         = array();
589                         $post        = array();
590                         $cookie      = array();
591                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
592                             printf("NEW_SOCKET: %d\n", intval($new_socket));
593                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
594                             printf("RECEIVED HEADER:\n%s", $stream_info);
595                             $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
596                             $addr = stream_socket_get_name($new_socket, TRUE);
597                             printf("PATH: [%s]\n", $path);
598                             printf("M: %s\nHEADER:\n", $method);
599                             if ($method == "POST") {
600                                 // ADD PUSH INTO FD ARRAY AS WAITING DATA
601                                 // Passing all infos from spu_process_info as arguments:
602                                 //
603                                 // MAYBE: $stream_info,
604                                 // $method, $header, $get, $post, $cookie
605                                 // $s_a_p (this), $new_socket, substr($path, SITE_PREFIX_LEN),
606                                 // $addr
607                             }
608                             print_r($header);
609                             printf("GET:\n");
610                             print_r($get);
611                             printf("POST:\n");
612                             print_r($post);
613                             printf("COOKIE:\n");
614                             print_r($cookie);
615                             $header_out = array();
616
617                             // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
618                             $rret = FALSE;
619                             if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
620                                 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
621                             }
622                             if ($rret == FALSE) { 
623                                 // FIXME: manage 404 !!!
624                                 printf("TODO: fix unknown page\n");
625                             }
626                             printf("number of sockets after %d\n", count($this->socks));
627                         }
628                         else {
629                             printf("WARNING: ancillary_getstream failed\n");
630                         }
631                     }
632                     else {
633                         $buf = fread($sock, 512);
634                         // if socket is closed
635                         if ($buf == FALSE || strlen($buf) == 0) {
636                             // close socket case
637                             if ($buf == FALSE) {
638                                 printf("ERROR READING\n");
639                             }
640                             if ($sock === $this->list) {
641                                 printf("Arrivati %d bytes da list\n", strlen($buf));
642                                 return(21);
643                             }
644                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
645                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
646                                 return(22);
647                             }
648                             else {
649                                 // $user_a[$s2u[intval($sock)]]->disable();
650                                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
651                                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
652                                 }
653                                 unset($this->socks[intval($sock)]);
654                                 unset($this->s2u[intval($sock)]);
655                             }
656                             fclose($sock);
657                             printf("CLOSE ON READ\n");
658
659                             if ($this->debug > 1) {
660                                 printf("post unset\n");
661                                 print_r($this->socks);
662                             }
663                         }
664                         else {
665                             if ($this->debug > 1) {
666                                 print_r($read);
667                             }
668                             if ($sock === $this->list) {
669                                 printf("Arrivati %d bytes da list\n", strlen($buf));
670                             }
671                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
672                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
673                                 $line = trim($buf);
674                                 if ($line == "reload") {
675                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
676
677                                     global_dump();
678                                 }
679                                 else if ($line == "shutdown") {
680                                     if ($this->app->dump_data()) {
681                                         return(0);
682                                     }
683                                     else {
684                                         return(1);
685                                     }
686                                 }
687                             }
688                             else {
689                                 $key = array_search("$sock", $this->socks);
690                                 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
691                             }
692                         }
693                     }
694                     // TODO: MOVE HERE request_mgr to factorize new_sockets and POST closed
695                     // $rret = $this->app->request_mgr
696                 }
697             }
698
699             $this->garbage_manager(FALSE);
700
701             /* manage unfinished pages */
702             foreach ($this->pending_pages as $k => $pgflush) {
703                 // TODO: try_flush if exists in the class
704                 if ($pgflush->try_flush($this->curtime) == TRUE) {
705                     unset($this->pending_pages[$k]);
706                 }
707             }
708             
709             /*
710                $response:                        raw stream data not sent
711                $content:                         html consistent data (<script bla bla>)
712                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
713             */
714
715             /* manage open streaming */
716             foreach ($this->socks as $k => $sock) {
717                 if (isset($this->s2u[intval($sock)])) {
718                     $user = $this->s2u[intval($sock)];
719                     $response = $user->rd_cache_get();
720                     $do_ping = FALSE;
721                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
722                         $do_ping = TRUE;
723                     }
724                     else {
725                         $user->ping_req = FALSE;
726                     }
727
728                     if ($response == "") {
729                         $content = "";
730                         $user->stream_main($content, $get, $post, $cookie);
731                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
732                         if ($do_ping && $user->ping_req == FALSE) {
733                             $content .= $user->stream_keepalive(TRUE);
734                             $user->ping_req = TRUE;
735                         }
736                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
737                             $content = $user->stream_keepalive(FALSE);
738                         }
739                         if ($content != "") {
740                             $response = chunked_content($user->rd_zls_get(), $content);
741                         }
742                     }
743                     
744                     if ($response != "") {
745                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
746                         echo "SPIA: [".$response."]\n";
747                         $response_l = mb_strlen($response, "ASCII");
748                         $wret = @fwrite($sock, $response);
749                         if ($wret < $response_l) {
750                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
751                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
752                         }
753                         else {
754                             $user->rd_cache_set("");
755                         }
756                         fflush($sock);
757                         $user->rd_kalive_reset($this->curtime);
758                     }
759                     
760                     // close socket after a while to prevent client memory consumption
761                     if ($user->rd_endtime_is_expired($this->curtime)) {
762                         if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
763                             $this->s2u[intval($sock)]->rd_socket_set(NULL);
764                         }
765                         unset($this->socks[intval($sock)]);
766                         unset($this->s2u[intval($sock)]);
767                         fclose($sock);
768                         printf("CLOSE ON LOOP\n");
769                     }
770                 }
771             }  // foreach ($this->socks...
772             printf("\n");
773         }  // while (...
774     }  // function run(...
775 }
776
777 ?>