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