db5456a78e06069e420a1bcffcb188038c976471
[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;             // user associated with input socket
379     var $s2p;             // pending page associated with input socket
380     var $pending_pages;
381
382     var $list;
383     var $in;
384
385     var $debug;
386     var $blocking_mode;
387
388     var $app;
389
390     var $curtime;
391
392     var $rndstr;
393     var $main_loop;
394
395     function Sac_a_push()
396     {
397     }
398
399     function sig_handler($sig)
400     {
401         switch ($sig) {
402         case SIGINT:
403             exit(1);
404             break;
405         case SIGTERM:
406             if (static::$cnt_master != NULL) {
407                     fwrite(static::$cnt_master, "\nshutdown\n");
408                     fflush(static::$cnt_master);
409             }
410             else {
411                 exit(1);
412             }
413             break;
414         case SIGHUP: 
415             if (static::$cnt_master != NULL) {
416                 fwrite(static::$cnt_master, "\nreload\n");
417                 fflush(static::$cnt_master);
418             }
419             break;
420         }
421     }
422
423     static function create(&$app, $sockname, $debug, $blocking_mode)
424     {        
425         $thiz = new Sac_a_push();
426         
427         $thiz->app = $app;
428         $thiz->file_socket = $sockname;
429         $thiz->unix_socket = "unix://$sockname";
430         $thiz->debug = $debug;
431         $thiz->socks = array();
432         $thiz->s2u  = array();
433         $thiz->s2p  = array();
434         $thiz->pending_pages = array();
435
436         // create a couple of sockets for control management
437         if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
438                                             STREAM_IPPROTO_IP)) == FALSE) {
439             return FALSE;
440         }
441         static::$cnt_master = $sockpair[0];
442         static::$cnt_slave  = $sockpair[1];
443
444         pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
445         pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
446         pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
447
448         $thiz->blocking_mode = 0; // 0 for non-blocking
449
450         $thiz->rndstr = "";
451         for ($i = 0 ; $i < 4096 ; $i++) {
452             if (($i % 128) == 0)
453                 $thiz->rndstr .= " ";
454             else
455                 $thiz->rndstr .= chr(mt_rand(65, 90));
456         }
457         
458         if (file_exists($thiz->file_socket)) {
459             unlink($thiz->file_socket);
460         }
461     
462         $old_umask = umask(0);
463         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
464             return (FALSE);
465         }
466         umask($old_umask);
467         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
468
469         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
470             return(FALSE);
471         }
472
473         $thiz->main_loop = FALSE;
474
475         return ($thiz);
476     }
477
478     function socks_set($sock, $user, $pendpage)
479     {
480         $id = intval($sock);
481
482         $this->socks[$id] = $sock;
483         if ($user != NULL)
484             $this->s2u[$id]   = $user;
485         if ($pendpage != NULL)
486             $this->s2p[$id]   = $pendpage;
487     }
488
489     function socks_unset($sock)
490     {
491         $id = intval($sock);
492
493         if (isset($this->s2u[$id]))
494             unset($this->s2u[$id]);
495         if (isset($this->s2p[$id]))
496             unset($this->s2p[$id]);
497         unset($this->socks[$id]);
498     }
499
500     function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
501     {
502         $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
503
504         if ($pendpage->try_flush($this->curtime) == FALSE) {
505             // Add $pendpage to the pendpage array
506             $this->pendpage_add($pendpage);
507         }
508     }
509
510     function pendpage_add($pendpage)
511     {
512         array_push($this->pending_pages, $pendpage);
513     }
514
515     function garbage_manager($force)
516     {
517         $this->app->garbage_manager($force);
518
519         foreach ($this->socks as $k => $sock) {
520             $id = intval($sock);
521             if (isset($this->s2u[$id])) {
522                 if ($this->s2u[$id]->sess == '') {
523                     if ($this->s2u[$id]->rd_socket_get() != NULL) {
524                         $this->s2u[$id]->rd_socket_set(NULL);
525                     }
526                     unset($this->socks[$id]);
527                     unset($this->s2u[$id]);
528                     fclose($sock);
529                     printf("CLOSE ON GARBAGE MANAGER\n");
530                 }
531             }
532         }
533     }
534
535     function run()
536     {
537         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
538
539         GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
540         GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
541         GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
542         GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
543         GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
544         GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
545         GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
546         GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
547         GLOBAL $G_with_topbanner;
548
549         if ($this->main_loop) {
550             return (FALSE);
551         }
552         
553         $this->main_loop = TRUE;
554         
555         while ($this->main_loop) {
556             $this->curtime = time();
557             printf("IN LOOP: Current opened: %d  pending_pages: %d - ", count($this->socks), count($this->pending_pages));
558             
559             /* Prepare the read array */
560             /* // when we manage it ... */
561             /* if ($shutdown)  */
562             /*     $read   = array_merge(array("$in" => $in), $socks); */
563             /* else */
564             $read   = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in,
565                                         intval(static::$cnt_slave) => static::$cnt_slave),
566                                   $this->socks);
567             
568             if ($this->debug > 1) {
569                 printf("PRE_SELECT\n");
570                 print_r($read);
571             }
572             $write  = NULL;
573             $except = NULL;
574             $num_changed_sockets = @stream_select($read, $write, $except, 5, 500000);
575         
576             if ($num_changed_sockets == 0) {
577                 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
578             } 
579             else if ($num_changed_sockets > 0) {
580                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
581                 if ($this->debug > 1) {
582                     print_r($read);
583                 }
584                 /* At least at one of the sockets something interesting happened */
585                 foreach ($read as $i => $sock) {
586                     $id = intval($sock);
587                     $manage_page = FALSE;
588                     /* is_resource check is required because there is the possibility that
589                        during new request an old connection is closed */
590                     if (!is_resource($sock)) {
591                         continue;
592                     }
593                     if ($sock === $this->list) {
594                         printf("NUOVA CONNEX\n");
595                         if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
596                             printf("SOCKET_ACCEPT FAILED\n");
597                             continue;
598                         }
599                         $stream_info = "";
600                         $method      = "";
601                         $get         = array();
602                         $post        = array();
603                         $cookie      = array();
604                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
605                             printf("NEW_SOCKET: %d\n", intval($new_socket));
606                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
607                             printf("RECEIVED HEADER:\n%s", $stream_info);
608                             $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
609                             $addr = stream_socket_get_name($new_socket, TRUE);
610                             printf("PATH: [%s]\n", $path);
611                             printf("M: %s\nHEADER:\n", $method);
612                             if ($method == "POST") {
613                                 // ADD PUSH INTO FD ARRAY AS WAITING DATA
614                                 // Passing all infos from spu_process_info as arguments:
615                                 //
616                                 // MAYBE: $stream_info,
617                                 // $method, $header, $get, $post, $cookie
618                                 // $s_a_p (this), $new_socket, substr($path, SITE_PREFIX_LEN),
619                                 // $addr
620                             }
621                             else {
622                                 $manage_page = TRUE;
623                             }
624                             print_r($header);
625                             printf("GET:\n");
626                             print_r($get);
627                             printf("POST:\n");
628                             print_r($post);
629                             printf("COOKIE:\n");
630                             print_r($cookie);
631                             $header_out = array();
632
633                             // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
634                             $rret = FALSE;
635                             if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
636                                 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
637                             }
638                             if ($rret == FALSE) { 
639                                 // FIXME: manage 404 !!!
640                                 printf("TODO: fix unknown page\n");
641                             }
642                             printf("number of sockets after %d\n", count($this->socks));
643                         }
644                         else {
645                             printf("WARNING: ancillary_getstream failed\n");
646                         }
647                     }
648                     else {
649                         $buf = fread($sock, 512);
650                         // if socket is closed
651                         if ($buf == FALSE || strlen($buf) == 0) {
652                             // close socket case
653                             if ($buf == FALSE) {
654                                 printf("ERROR READING\n");
655                             }
656                             if ($sock === $this->list) {
657                                 printf("Arrivati %d bytes da list\n", strlen($buf));
658                                 return(21);
659                             }
660                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
661                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
662                                 return(22);
663                             }
664                             else {
665                                 unset($this->socks[$id]);
666                                 if (isset($this->s2u[$id])) {
667                                     // $user_a[$s2u[$id]]->disable();
668                                     if ($this->s2u[$id]->rd_socket_get() != NULL) {
669                                         $this->s2u[$id]->rd_socket_set(NULL);
670                                     }
671                                     unset($this->s2u[$id]);
672                                 }
673                             }
674                             fclose($sock);
675                             printf("CLOSE ON READ\n");
676
677                             if ($this->debug > 1) {
678                                 printf("post unset\n");
679                                 print_r($this->socks);
680                             }
681                         }
682                         else {
683                             if ($this->debug > 1) {
684                                 print_r($read);
685                             }
686                             if ($sock === $this->list) {
687                                 printf("Arrivati %d bytes da list\n", strlen($buf));
688                             }
689                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
690                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
691                                 $line = trim($buf);
692                                 if ($line == "reload") {
693                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
694
695                                     global_dump();
696                                 }
697                                 else if ($line == "shutdown") {
698                                     if ($this->app->dump_data()) {
699                                         return(0);
700                                     }
701                                     else {
702                                         return(1);
703                                     }
704                                 }
705                             }
706                             else {
707                                 $key = array_search("$sock", $this->socks);
708                                 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
709                             }
710                         }
711                     }
712                     // TODO: MOVE HERE request_mgr to factorize new_sockets and POST closed
713                     // $rret = $this->app->request_mgr
714                 }
715             }
716
717             $this->garbage_manager(FALSE);
718
719             /* manage unfinished pages */
720             foreach ($this->pending_pages as $k => $pgflush) {
721                 // TODO: try_flush if exists in the class
722                 if ($pgflush->try_flush($this->curtime) == TRUE) {
723                     unset($this->pending_pages[$k]);
724                 }
725             }
726             
727             /*
728                $response:                        raw stream data not sent
729                $content:                         html consistent data (<script bla bla>)
730                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
731             */
732
733             /* manage open streaming */
734             foreach ($this->socks as $k => $sock) {
735                 $id = intval($sock);
736                 if (isset($this->s2u[$id])) {
737                     $user = $this->s2u[$id];
738                     $response = $user->rd_cache_get();
739                     $do_ping = FALSE;
740                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
741                         $do_ping = TRUE;
742                     }
743                     else {
744                         $user->ping_req = FALSE;
745                     }
746
747                     if ($response == "") {
748                         $content = "";
749                         $user->stream_main($content, $get, $post, $cookie);
750                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
751                         if ($do_ping && $user->ping_req == FALSE) {
752                             $content .= $user->stream_keepalive(TRUE);
753                             $user->ping_req = TRUE;
754                         }
755                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
756                             $content = $user->stream_keepalive(FALSE);
757                         }
758                         if ($content != "") {
759                             $response = chunked_content($user->rd_zls_get(), $content);
760                         }
761                     }
762                     
763                     if ($response != "") {
764                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
765                         echo "SPIA: [".$response."]\n";
766                         $response_l = mb_strlen($response, "ASCII");
767                         $wret = @fwrite($sock, $response);
768                         if ($wret < $response_l) {
769                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
770                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
771                         }
772                         else {
773                             $user->rd_cache_set("");
774                         }
775                         fflush($sock);
776                         $user->rd_kalive_reset($this->curtime);
777                     }
778                     
779                     // close socket after a while to prevent client memory consumption
780                     if ($user->rd_endtime_is_expired($this->curtime)) {
781                         if ($this->s2u[$id]->rd_socket_get() != NULL) {
782                             $this->s2u[$id]->rd_socket_set(NULL);
783                         }
784                         unset($this->socks[$id]);
785                         unset($this->s2u[$id]);
786                         fclose($sock);
787                         printf("CLOSE ON LOOP\n");
788                     }
789                 }
790             }  // foreach ($this->socks...
791             printf("\n");
792         }  // while (...
793     }  // function run(...
794 }
795
796 ?>