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