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