method to identify closed socket changed
[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         foreach($header as $key => $value) {
225             if (strtolower($key) == "http-response")
226                 continue;
227             $s .= sprintf("%s: %s\r\n", $key, $value);
228         }
229         if ($len >= 0) {
230             $s .= sprintf("Content-Length: %ld\r\n", $len);
231         }
232     }
233     else {
234         $s = "HTTP/1.1 200 OK\r\n";
235
236         if (!isset($header['Date']))
237             $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
238         if (!isset($header['Connection']))
239             $s .= "Connection: close\r\n";
240         if (!isset($header['Content-Type']))
241             $s .= "Content-Type: text/html\r\n";
242         foreach($header as $key => $value) {
243             $s .= sprintf("%s: %s\r\n", $key, $value);
244         }
245         if ($len >= 0) {
246             $s .= sprintf("Content-Length: %d\r\n", $len);
247         }
248         else {
249             $s .= "Cache-Control: no-cache, must-revalidate\r\n";
250             $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
251             if (!isset($header['Content-Encoding'])) {
252                 $s .= "Content-Encoding: chunked\r\n";
253             }
254             $s .= "Transfer-Encoding: chunked\r\n";
255         }
256         $s .= $cookies;
257     }
258     $s .= "\r\n";
259
260     return ($s);
261 }
262
263 /*
264  *  Caching system using ob php system to cache old style pages
265  *  to a var and than send it with more calm
266  */
267
268 function shutta()
269 {
270   log_rd2("SHUTTA [".connection_status()."] !");
271 }
272
273 register_shutdown_function('shutta');
274
275 /*
276  *  MAIN
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     var $is_daemon;
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, $argv)
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         $thiz->is_daemon = FALSE;
463
464         if (array_search("-d", $argv) !== FALSE || array_search("--daemon", $argv) !== FALSE) {
465             $thiz->is_daemon = TRUE;
466         }
467
468         // create a couple of sockets for control management
469         if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
470                                             STREAM_IPPROTO_IP)) == FALSE) {
471             return FALSE;
472         }
473         static::$cnt_master = $sockpair[0];
474         static::$cnt_slave  = $sockpair[1];
475
476         pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
477         pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
478         pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
479
480         $thiz->blocking_mode = 0; // 0 for non-blocking
481
482         $thiz->rndstr = "";
483         for ($i = 0 ; $i < 4096 ; $i++) {
484             if (($i % 128) == 0)
485                 $thiz->rndstr .= " ";
486             else
487                 $thiz->rndstr .= chr(mt_rand(65, 90));
488         }
489         
490         if (file_exists($thiz->file_socket)) {
491             unlink($thiz->file_socket);
492         }
493     
494         $old_umask = umask(0);
495         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
496             return (FALSE);
497         }
498         umask($old_umask);
499         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
500
501         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
502             return(FALSE);
503         }
504
505         $thiz->main_loop = FALSE;
506
507         return ($thiz);
508     }
509
510     function socks_set($sock, $user, $pendpage)
511     {
512         $id = intval($sock);
513
514         $this->socks[$id] = $sock;
515         if ($user != NULL)
516             $this->s2u[$id]   = $user;
517         if ($pendpage != NULL)
518             $this->s2p[$id]   = $pendpage;
519     }
520
521     function socks_unset($sock)
522     {
523         $id = intval($sock);
524
525         if (isset($this->s2u[$id]))
526             unset($this->s2u[$id]);
527         if (isset($this->s2p[$id]))
528             unset($this->s2p[$id]);
529         unset($this->socks[$id]);
530     }
531
532     function pendpage_try_addcont(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
533     {
534         $pendpage = PendingPage::pendingpage_continue(&$new_socket, $this->curtime, $tout, $method,
535                                                            $header,           $get, $post, $cookie,
536                                                              $path,          $addr, $rest, $cont);
537
538         $pendpage->try_flush($this->curtime);
539         // Add $pendpage to the pendpage array (in any case)
540         fprintf(STDERR, "IMPORTANT: Pendadd: %d\n", $pendpage->status);
541         $this->pendpage_add($pendpage);
542     }
543
544     function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
545     {
546         $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
547
548         if ($pendpage->try_flush($this->curtime) == FALSE) {
549             // Add $pendpage to the pendpage array
550             $this->pendpage_add($pendpage);
551         }
552     }
553
554     function pendpage_add($pendpage)
555     {
556         array_push($this->pending_pages, $pendpage);
557         $this->socks_set($pendpage->socket_get(), NULL, $pendpage);
558     }
559
560     function pendpage_rem($pendpage)
561     {
562         $sock = $pendpage->socket_get();
563         if (($key = array_search($pendpage, $this->pending_pages)) !== FALSE) {
564             unset($this->pending_pages[$key]);
565         }
566         else {
567             fprintf(STDERR, "WARNING: pendpage not found\n");
568         }
569         $this->socks_unset($sock);
570         fprintf(STDERR, "PP_REM: %d\n", intval($sock));
571     }
572
573
574     function pendpage_try_addwait(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
575     {
576         $pendpage = PendingPage::pendingpage_waiting($new_socket, $this->curtime, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont);
577         /*
578         if ($pendpage->try_flush($this->curtime) == FALSE) {
579             // Add $pendpage to the pendpage array
580             */
581         $this->pendpage_add($pendpage);
582         /*
583         }
584         */
585     }
586
587     function garbage_manager($force)
588     {
589         $this->app->garbage_manager($force);
590
591         foreach ($this->socks as $k => $sock) {
592             $id = intval($sock);
593             if (isset($this->s2u[$id])) {
594                 if ($this->s2u[$id]->sess == '') {
595                     if ($this->s2u[$id]->rd_socket_get() != NULL) {
596                         $this->s2u[$id]->rd_socket_set(NULL);
597                     }
598                     unset($this->socks[$id]);
599                     unset($this->s2u[$id]);
600                     fclose($sock);
601                     printf("CLOSE ON GARBAGE MANAGER\n");
602                 }
603             }
604         }
605     }
606
607     function run()
608     {
609         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
610
611         GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
612         GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
613         GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
614         GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
615         GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
616         GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
617         GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
618         GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
619         GLOBAL $G_with_topbanner;
620         GLOBAL $G_tos_vers, $G_tos_fname, $G_tos_dtsoft, $G_tos_dthard, $G_tos_idx, $G_doc_path;
621
622         if ($this->main_loop) {
623             return (FALSE);
624         }
625         
626         $this->main_loop = TRUE;
627         
628         while ($this->main_loop) {
629             $this->app->sess_cur_set(FALSE);
630             $this->curtime = time();
631             fprintf(STDERR, "IN LOOP: Current opened: %d  pending_pages: %d\n", count($this->socks), count($this->pending_pages));
632             
633             /* Prepare the read array */
634             /* // when we manage it ... */
635             /* if ($shutdown)  */
636             /*     $read   = array_merge(array("$in" => $in), $socks); */
637             /* else */
638             $pre_read = array_merge(array(intval($this->list) => $this->list,
639                                           intval(static::$cnt_slave) => static::$cnt_slave),
640                                     $this->socks);
641             if ($this->is_daemon == FALSE) {
642                 $read = array_merge($pre_read, array(intval($this->in) => $this->in));
643             }
644             else {
645                 $read = $pre_read;
646             }
647             
648             if ($this->debug > 1) {
649                 printf("PRE_SELECT\n");
650                 print_r($read);
651             }
652             $write  = NULL;
653             $except = NULL;
654             $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
655         
656             if ($num_changed_sockets == 0) {
657                 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
658             } 
659             else if ($num_changed_sockets > 0) {
660                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
661                 if ($this->debug > 1) {
662                     print_r($read);
663                 }
664                 /* At least at one of the sockets something interesting happened */
665                 foreach ($read as $i => $sock) {
666                     $id = intval($sock);
667                     $manage_page = FALSE;
668                     /* is_resource check is required because there is the possibility that
669                        during new request an old connection is closed */
670                     if (!is_resource($sock)) {
671                         continue;
672                     }
673                     if ($sock === $this->list) {
674                         printf("NUOVA CONNEX\n");
675                         if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
676                             printf("SOCKET_ACCEPT FAILED\n");
677                             continue;
678                         }
679                         $stream_info = "";
680                         $method      = "";
681                         $get         = array();
682                         $post        = array();
683                         $cookie      = array();
684                         $rest        = 0;
685                         $cont        = "";
686                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
687                             printf("NEW_SOCKET: %d\n", intval($new_socket));
688                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
689                             printf("RECEIVED HEADER:\n%s", $stream_info);
690                             if (($path = spu_process_info($stream_info, $method, $header,
691                                                           $get, $post, $cookie, $rest, $cont))
692                                 == FALSE) {
693                                 fprintf(STDERR, "TODO: fix wrong header management\n");
694                             }
695                             $addr = stream_socket_get_name($new_socket, TRUE);
696                             printf("PATH: [%s]\n", $path);
697                             if ($method == "POST" && $rest > 0) {
698                                 if (isset($header['Expect']) && $header['Expect'] == '100-continue') {
699                                     fprintf(STDERR, "\nPOSTA DE CHE\n\n");
700                                     $this->pendpage_try_addcont($new_socket, 20,
701                                                                 $method, $header, $get, $post, $cookie,
702                                                                 $path, $addr, $rest, $cont);
703                                 }
704                                 else {
705                                     $this->pendpage_try_addwait($new_socket, 20,
706                                                                 $method, $header, $get, $post, $cookie,
707                                                                 $path, $addr, $rest, $cont);
708                                 }
709                             }
710                             else {
711                                 $manage_page = TRUE;
712                             }
713
714                             printf("number of sockets after %d\n", count($this->socks));
715                         }
716                         else {
717                             printf("WARNING: ancillary_getstream failed\n");
718                         }
719                     }
720                     else {
721                         $buf = fread($sock, 4096);
722                         // if socket is closed
723                         if ($buf == FALSE || feof($sock)) {
724                             // close socket case
725                             if ($buf == FALSE) {
726                                 printf("INFO: read return false\n");
727                             }
728                             if ($sock === $this->list) {
729                                 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
730                                 return(21);
731                             }
732                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
733                                 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
734                                 return(22);
735                             }
736                             else {
737                                 unset($this->socks[$id]);
738                                 if (isset($this->s2u[$id])) {
739                                     // $user_a[$s2u[$id]]->disable();
740                                     if ($this->s2u[$id]->rd_socket_get() != NULL) {
741                                         // try to send close frame (for websocket)
742                                         $clo = $this->s2u[$id]->stream_close();
743                                         $clo_l = mb_strlen($clo, "ASCII");
744                                         @fwrite($sock, $clo, $clo_l);
745                                         $this->s2u[$id]->rd_socket_set(NULL);
746                                     }
747                                     unset($this->s2u[$id]);
748                                 }
749                             }
750                             fclose($sock);
751                             printf("CLOSE ON READ\n");
752
753                             if ($this->debug > 1) {
754                                 printf("post unset\n");
755                                 print_r($this->socks);
756                             }
757                         }
758                         else {
759                             if ($this->debug > 1) {
760                                 print_r($read);
761                             }
762                             if ($sock === $this->list) {
763                                 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
764                             }
765                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
766                                 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
767                                 $line = trim($buf);
768                                 if ($line == "reload") {
769                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
770
771                                     global_dump();
772                                 }
773                                 else if ($line == "shutdown" || $line == "sd") {
774                                     if ($this->app->dump_data()) {
775                                         return(0);
776                                     }
777                                     else {
778                                         return(1);
779                                     }
780                                 }
781                             }
782                             else {
783                                 $key = array_search("$sock", $this->socks);
784                                 fprintf(STDERR, "Arrivati %d bytes dalla socket n. %d\n", mb_strlen($buf, "ASCII"), $key);
785                                 if (isset($this->s2p[$id])) {
786                                     $this->s2p[$id]->rest -= mb_strlen($buf, "ASCII");
787                                     $this->s2p[$id]->cont .= $buf;
788                                     if ($this->s2p[$id]->rest <= 0) {
789                                         $header = $new_socket = $path = $addr = $get = $cookie = 0;
790                                         $post = array();
791
792                                         $this->s2p[$id]->context_get($header, $new_socket, $path, $addr, $get, $post, $cookie);
793                                         $this->pendpage_rem($this->s2p[$id]);
794                                         fprintf(STDERR, "SOCKET RUN: %s\n", $new_socket);
795
796                                         $manage_page = TRUE;
797                                     }
798                                 }
799                             }
800                         }
801                     }
802
803                     if ($manage_page == TRUE) {
804                         printf("M: %s\nHEADER:\n", $method);
805                         print_r($header);
806                         printf("GET:\n");
807                         print_r($get);
808                         printf("POST:\n");
809                         print_r($post);
810                         printf("COOKIE:\n");
811                         print_r($cookie);
812
813                         $header_out = array();
814                         // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
815                         $rret = FALSE;
816                         if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
817                             $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
818                         }
819                         if ($rret == FALSE) {
820                             // FIXME: manage 404 !!!
821                             printf("TODO: fix unknown page\n");
822                         }
823                     }
824                 }
825             }
826
827             $this->garbage_manager(FALSE);
828
829             /* manage unfinished pages */
830             foreach ($this->pending_pages as $k => $pendpage) {
831                 // TODO: try_flush if exists in the class
832                 if ($pendpage->try_flush($this->curtime) == TRUE) {
833                     unset($this->pending_pages[$k]);
834                 }
835             }
836             
837             /*
838                $response:                        raw stream data not sent
839                $content:                         html consistent data (<script bla bla>)
840                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
841             */
842
843             /* manage open streaming */
844             foreach ($this->socks as $k => $sock) {
845                 $id = intval($sock);
846                 if (isset($this->s2u[$id])) {
847                     $user = $this->s2u[$id];
848                     $response = $user->rd_cache_get();
849                     $do_ping = FALSE;
850                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
851                         $do_ping = TRUE;
852                     }
853                     else {
854                         $user->ping_req = FALSE;
855                     }
856
857                     if ($response == "") {
858                         $content = "";
859                         $user->stream_main($content, $get, $post, $cookie);
860                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
861                         if ($do_ping && $user->ping_req == FALSE) {
862                             $content .= $user->stream_keepalive(TRUE);
863                             $user->ping_req = TRUE;
864                         }
865                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
866                             $content = $user->stream_keepalive(FALSE);
867                         }
868                         if ($content != "") {
869                             $response = $user->chunked_content($content);
870                         }
871                     }
872                     
873                     if ($response != "") {
874                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
875                         // echo "SPIA: [".$response."]\n";
876                         $response_l = mb_strlen($response, "ASCII");
877                         $wret = @fwrite($sock, $response, $response_l);
878                         if ($wret < $response_l) {
879                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
880                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
881                         }
882                         else {
883                             $user->rd_cache_set("");
884                         }
885                         fflush($sock);
886                         $user->rd_kalive_reset($this->curtime);
887                     }
888                     
889                     // close socket after a while to prevent client memory consumption
890                     if ($user->rd_endtime_is_expired($this->curtime)) {
891                         if ($this->s2u[$id]->rd_socket_get() != NULL) {
892                             $this->s2u[$id]->rd_socket_set(NULL);
893                         }
894                         unset($this->socks[$id]);
895                         unset($this->s2u[$id]);
896                         $clo = $user->stream_close();
897                         $clo_l = mb_strlen($clo, "ASCII");
898                         @fwrite($sock, $clo, $clo_l);
899                         fclose($sock);
900                         printf("CLOSE ON LOOP\n");
901                     }
902                 }
903             }  // foreach ($this->socks...
904             printf("\n");
905         }  // while (...
906     }  // function run(...
907 }
908
909 ?>