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