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