6ed7a0e6a5fe300d6bc1e4256e940618efeeb57e
[brisk.git] / web / Obj / sac-a-push.phh
1 <?php
2 /*
3  *  brisk - Obj/sac-a-push.phh
4  *
5  *  Copyright (C) 2012-2014 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 define('DIRECT_ST_READ',  1);
29 define('DIRECT_ST_WRITE', 2);
30
31 declare(ticks = 1);
32
33 function global_dump()
34 {
35     GLOBAL $G_alarm_passwd, $G_ban_list, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
36     GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
37     GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
38     GLOBAL $G_room_roadmap, $G_shutdown;
39     GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
40     GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
41     GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
42     GLOBAL $G_with_splash, $G_sidebanner, $G_sidebanner_idx;
43     GLOBAL $G_with_topbanner;
44
45     fprintf(STDERR, "G_alarm_passwd = [%s]\n", print_r($G_alarm_passwd, TRUE));
46     fprintf(STDERR, "G_ban_list = [%s]\n", print_r($G_ban_list, TRUE));
47     fprintf(STDERR, "G_black_list = [%s]\n", print_r($G_black_list, TRUE));
48     fprintf(STDERR, "G_btrace_pref_sub = [%s]\n", print_r($G_btrace_pref_sub, TRUE));
49     fprintf(STDERR, "G_dbauth = [%s]\n", print_r($G_dbauth, TRUE));
50     fprintf(STDERR, "G_dbpfx = [%s]\n", print_r($G_dbpfx, TRUE));
51     fprintf(STDERR, "G_donors_all = [%s]\n", print_r($G_donors_all, TRUE));
52     fprintf(STDERR, "G_donors_cur = [%s]\n", print_r($G_donors_cur, TRUE));
53     fprintf(STDERR, "G_is_local = [%s]\n", print_r($G_is_local, TRUE));
54     fprintf(STDERR, "G_lang = [%s]\n", print_r($G_lang, TRUE));
55     fprintf(STDERR, "G_poll_entries = [%s]\n", print_r($G_poll_entries, TRUE));
56     fprintf(STDERR, "G_poll_name = [%s]\n", print_r($G_poll_name, TRUE));
57     fprintf(STDERR, "G_poll_title = [%s]\n", print_r($G_poll_title, TRUE));
58     fprintf(STDERR, "G_proxy_white_list = [%s]\n", print_r($G_proxy_white_list, TRUE));
59     fprintf(STDERR, "G_room_roadmap = [%s]\n", print_r($G_room_roadmap, TRUE));
60     fprintf(STDERR, "G_shutdown = [%s]\n", print_r($G_shutdown, TRUE));
61     fprintf(STDERR, "G_splash_content = [%s]\n", print_r($G_splash_content, TRUE));
62     fprintf(STDERR, "G_splash_contents = [%s]\n", print_r($G_splash_contents, TRUE));
63     fprintf(STDERR, "G_splash_cont_idx = [%s]\n", print_r($G_splash_cont_idx, TRUE));
64     fprintf(STDERR, "G_splash_h = [%s]\n", print_r($G_splash_h, TRUE));
65     fprintf(STDERR, "G_splash_idx = [%s]\n", print_r($G_splash_idx, TRUE));
66     fprintf(STDERR, "G_splash_interval = [%s]\n", print_r($G_splash_interval, TRUE));
67     fprintf(STDERR, "G_splash_timeout = [%s]\n", print_r($G_splash_timeout, TRUE));
68     fprintf(STDERR, "G_splash_w = [%s]\n", print_r($G_splash_w, TRUE));
69     fprintf(STDERR, "G_topbanner = [%s]\n", print_r($G_topbanner, TRUE));
70     fprintf(STDERR, "G_with_donors = [%s]\n", print_r($G_with_donors, TRUE));
71     fprintf(STDERR, "G_with_poll = [%s]\n", print_r($G_with_poll, TRUE));
72     fprintf(STDERR, "G_sidebanner = [%s]\n", print_r($G_sidebanner, TRUE));
73     fprintf(STDERR, "G_sidebanner_idx = [%s]\n", print_r($G_sidebanner_idx, TRUE));
74     fprintf(STDERR, "G_with_splash = [%s]\n", print_r($G_with_splash, TRUE));
75     fprintf(STDERR, "G_with_topbanner = [%s]\n", print_r($G_with_topbanner, TRUE));
76 }
77
78 function pid_save()
79 {
80     $pid = getmypid();
81     $fname = LEGAL_PATH."/brisk.pid";
82
83     if (file_exists($fname)) {
84         log_crit("WARN: brisk.pid already exists");
85     }
86     file_put_contents($fname, sprintf("%d\n", $pid));
87 }
88
89 function pid_remove()
90 {
91     $fname = LEGAL_PATH."/brisk.pid";
92
93     if (file_exists($fname)) {
94         unlink($fname);
95     }
96 }
97
98 function post_manage(&$post, $line)
99 {
100     $a = explode('&', $line);
101     for ($i = 0 ; $i < count($a) ; $i++) {
102         $b = explode('=', $a[$i]);
103         if (isset($b[0])) {
104             if (isset($b[1])) {
105                 $post[$b[0]] = urldecode($b[1]);
106             }
107             else {
108                 $post[$b[0]] = "";
109             }
110         }
111     }
112 }
113
114 function spu_process_info($stream_info, &$method, &$header, &$get, &$post, &$cookie, &$rest, &$cont)
115 {
116     $check_post = FALSE;
117     $header = array();
118     $get = array();
119     $post = array();
120     $rest = 0;
121     foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
122         printf("LINE: [%s]\n", $line);
123         if ($check_post) {
124             if (!isset($header['The-Request'])) {
125                 return FALSE;
126             }
127             $req = explode(" ", $header['The-Request']);
128             $method = $req[0];
129
130             if (isset($header['Cookie'])) {
131
132                 // 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)]
133
134                 $cookies = explode("; ", $header['Cookie']);
135                 for ($i = 0 ; $i < count($cookies) ; $i++) {
136                     $name = mb_strstr($cookies[$i], "=", TRUE, 'UTF-8');
137                     if ($name == FALSE) {
138                         if (mb_strlen($cookies[$i]) > 0) {
139                             $cookie[$cookies[$i]] = "";
140                         }
141                         else {
142                             printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
143                         }
144                         continue;
145                     }
146
147                     $value = mb_substr($cookies[$i], mb_strlen($name)+1, 10140, 'UTF-8');
148                     $cookie[$name] = urldecode($value);
149                 }
150             }
151             // GET params management
152             $get_vars = explode('?', $req[1], 2);
153             $path = $get_vars[0];
154             if (count($get_vars) > 1) {
155                 $a = explode('&', $get_vars[1]);
156                 printf("A COUNT: [%s] %d\n", $a[0], count($a));
157                 for ($i = 0 ; $i < count($a) ; $i++) {
158                     $b = explode('=', $a[$i]);
159                     $get[$b[0]] = urldecode($b[1]);
160                 }
161             }
162             // POST params management
163             if ($req[0] == 'POST') {
164                 $conttype_all = explode(";", $header['Content-Type']);
165                 $header['Content-Type'] = $conttype_all[0];
166                 // $path_all[1-] other things like charset and so on
167
168                 // if (content-type is wrong || content-length isn't set)
169                 //     return false
170
171                 if ($header['Content-Type'] != 'application/x-www-form-urlencoded' 
172                     || !isset($header['Content-Length'])) {
173                     return FALSE;
174                 }
175                 $post_len = mb_strlen($line, "ASCII");
176                 printf("INFO: postlen: %d\n", $post_len);
177                 $rest = (int)($header['Content-Length']) - $post_len;
178
179                 if ($rest == 0) {
180                     post_manage($post, $line);
181                 }
182                 else {
183                     $cont = $line;
184                 }
185             }
186             break;
187         }
188         if ($line == "") {
189             $check_post = TRUE;
190             continue;
191         }
192         $split = explode(":", $line, 2);
193         $hea_id = trim(mb_convert_case($split[0], MB_CASE_TITLE, 'UTF-8'));
194         $header[$hea_id] = $split[1];
195     }
196     return $path;
197 }
198
199 function gpcs_var($name, $get, $post, $cookie)
200 {
201     if (isset($GLOBALS[$name])) 
202         return FALSE;
203     else if (isset($cookie[$name])) 
204         return ($cookie[$name]);
205     else if (isset($post[$name])) 
206         return ($post[$name]);
207     else if (isset($get[$name])) 
208         return ($get[$name]);
209
210     return FALSE;
211 }
212
213 function headers_render($header, $len)
214 {
215     $cookies = "";
216
217     if (isset($header['cookies'])) {
218         $cookies = $header['cookies']->render();
219         unset($header['cookies']);
220     }
221     if (isset($header['Location'])) {
222         $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
223     }
224     else if (isset($header['HTTP-Response'])) {
225         $s = sprintf("HTTP/1.1 %s\r\n", $header['HTTP-Response']);
226         foreach($header as $key => $value) {
227             if (strtolower($key) == "http-response")
228                 continue;
229             $s .= sprintf("%s: %s\r\n", $key, $value);
230         }
231         if ($len >= 0) {
232             $s .= sprintf("Content-Length: %ld\r\n", $len);
233         }
234     }
235     else {
236         $s = "HTTP/1.1 200 OK\r\n";
237
238         if (!isset($header['Date']))
239             $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
240         if (!isset($header['Connection']))
241             $s .= "Connection: close\r\n";
242         if (!isset($header['Content-Type']))
243             $s .= "Content-Type: text/html\r\n";
244         foreach($header as $key => $value) {
245             $s .= sprintf("%s: %s\r\n", $key, $value);
246         }
247         if ($len >= 0) {
248             $s .= sprintf("Content-Length: %d\r\n", $len);
249         }
250         else {
251             $s .= "Cache-Control: no-cache, must-revalidate\r\n";
252             $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
253             if (!isset($header['Content-Encoding'])) {
254                 $s .= "Content-Encoding: chunked\r\n";
255             }
256             $s .= "Transfer-Encoding: chunked\r\n";
257         }
258         $s .= $cookies;
259     }
260     $s .= "\r\n";
261
262     return ($s);
263 }
264
265 /*
266  *  Caching system using ob php system to cache old style pages
267  *  to a var and than send it with more calm
268  */
269
270 function shutta()
271 {
272   log_rd2("SHUTTA [".connection_status()."] !");
273 }
274
275 register_shutdown_function('shutta');
276
277 /*
278  *  MAIN
279  */
280
281 function get_encoding($header)
282 {
283     $enc = "plain";
284     if (isset($header['Accept-Encoding'])) {
285         $acc = explode(',', $header['Accept-Encoding']);
286
287         if (array_search('gzip', $acc) !== FALSE) {
288             $enc = 'gzip';
289         }
290         else if (array_search('deflate', $acc) !== FALSE) {
291             $enc = 'deflate';
292         }
293     }
294
295     return ($enc);
296 }
297
298 class Cookie {
299     var $attr;
300     // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
301     // string $name  [, string $value  [, int $expire = 0  [, string $path  [, string $domain  [, bool $secure = false  [, bool $httponly = false  ]]]]]] )
302     function Cookie()
303     {
304         $this->attr = array();
305     }
306
307     static function create($name)
308     {
309         $thiz = new Cookie();
310
311         $thiz->attr[$name] = "";
312
313         $argc = func_num_args();
314         for ($i = 1 ; $i < $argc ; $i++) {
315             $arg = func_get_arg($i);
316             switch ($i) {
317             case 1:
318                 $thiz->attr[$name] = urlencode($arg);
319                 break;
320             case 2:
321                 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
322                 break;
323             case 3:
324                 $thiz->attr['Path'] = $arg;
325                 break;
326             case 4:
327                 $thiz->attr['Domain'] = $arg;
328                 break;
329             case 5:
330                 if ($arg == TRUE) {
331                     $thiz->attr['Secure'] = NULL;
332                 }
333                 break;
334             case 6:
335                 if ($arg == TRUE) {
336                     $thiz->attr['HttpOnly'] = NULL;
337                 }
338                 break;
339             default:
340                 return FALSE;
341             }
342         }
343
344         return $thiz;
345     }
346
347     function render()
348     {
349         $r = "Set-Cookie: ";
350         $isfirst = TRUE;
351
352         foreach ($this->attr as $k => $v) {
353             if ($v == NULL) {
354                 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
355             }
356             else {
357                 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
358             }
359             $isfirst = FALSE;
360         }
361         $r .= "\r\n";
362
363         return $r;
364     }
365 }
366
367 class Cookies {
368     var $cookies;
369
370     function Cookies()
371     {
372         $this->cookies = array();
373     }
374
375     function add($name)
376     {
377         if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
378             return (FALSE);
379
380         array_push($this->cookies, $cookie);
381
382         return (TRUE);
383     }
384
385     function render()
386     {
387         $r = "";
388         foreach ($this->cookies as $cookie) {
389             $r .= $cookie->render();
390         }
391
392         return ($r);
393     }
394 }
395
396
397 class Sac_a_push {
398     // maybe fixed_fd is unuseful
399     static $fixed_fd = 3;
400     static $cnt_master = NULL;
401     static $cnt_slave  = NULL;
402     
403     var $file_socket;
404     var $unix_socket;
405     var $direct_socket;   // socket where read direct commands
406     var $socks;
407     var $s2u;             // user associated with input socket
408     var $s2p;             // pending page associated with input socket
409     var $pending_pages;
410     var $is_daemon;
411
412     var $list_web;
413     var $list_cmd;
414     var $in;
415
416     var $debug;
417     var $blocking_mode;
418
419     var $app;
420
421     var $curtime;
422
423     var $rndstr;
424     var $main_loop;
425
426     function Sac_a_push()
427     {
428     }
429
430     function sig_handler($sig)
431     {
432         switch ($sig) {
433         case SIGINT:
434             exit(1);
435             break;
436         case SIGTERM:
437             if (static::$cnt_master != NULL) {
438                     fwrite(static::$cnt_master, "\nshutdown\n");
439                     fflush(static::$cnt_master);
440             }
441             else {
442                 exit(1);
443             }
444             break;
445         case SIGHUP: 
446             if (static::$cnt_master != NULL) {
447                 fwrite(static::$cnt_master, "\nreload\n");
448                 fflush(static::$cnt_master);
449             }
450             break;
451         }
452     }
453
454     static function create(&$app, $sockname, $debug, $blocking_mode, $argv)
455     {        
456         $thiz = new Sac_a_push();
457         
458         $thiz->app = $app;
459         $thiz->file_socket = $sockname;
460         $thiz->unix_socket = "unix://$sockname";
461         $thiz->direct_socket = "unix://${sockname}2";
462         $thiz->debug = $debug;
463         $thiz->socks = array();
464         $thiz->s2u  = array();
465         $thiz->s2p  = array();
466         $thiz->pending_pages = array();
467         $thiz->is_daemon = FALSE;
468
469         if (array_search("-d", $argv) !== FALSE || array_search("--daemon", $argv) !== FALSE) {
470             $thiz->is_daemon = TRUE;
471         }
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         if (file_exists($thiz->file_socket."2")) {
499             unlink($thiz->file_socket."2");
500         }
501     
502         $old_umask = umask(0);
503         if (($thiz->list_web = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
504             return (FALSE);
505         }
506         if (($thiz->list_cmd = stream_socket_server($thiz->direct_socket, $err, $errs)) === FALSE) {
507             return (FALSE);
508         }
509         umask($old_umask);
510         stream_set_blocking($thiz->list_web, $thiz->blocking_mode); # Set the stream to non-blocking
511         stream_set_blocking($thiz->list_cmd, $thiz->blocking_mode); # Set the stream to non-blocking
512
513         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
514             return(FALSE);
515         }
516
517         $thiz->main_loop = FALSE;
518
519         return ($thiz);
520     }
521
522     function socks_set($sock, $user, $pendpage)
523     {
524         $id = intval($sock);
525
526         $this->socks[$id] = $sock;
527         if ($user != NULL)
528             $this->s2u[$id]   = $user;
529         if ($pendpage != NULL)
530             $this->s2p[$id]   = $pendpage;
531     }
532
533     function socks_unset($sock)
534     {
535         $id = intval($sock);
536
537         if (isset($this->s2u[$id]))
538             unset($this->s2u[$id]);
539         if (isset($this->s2p[$id]))
540             unset($this->s2p[$id]);
541         unset($this->socks[$id]);
542     }
543
544     function pendpage_try_addcont(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
545     {
546         $pendpage = PendingPage::pendingpage_continue(&$new_socket, $this->curtime, $tout, $method,
547                                                            $header,           $get, $post, $cookie,
548                                                              $path,          $addr, $rest, $cont);
549
550         $pendpage->try_flush($this->curtime);
551         // Add $pendpage to the pendpage array (in any case)
552         fprintf(STDERR, "IMPORTANT: Pendadd: %d\n", $pendpage->status);
553         $this->pendpage_add($pendpage);
554     }
555
556     function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
557     {
558         $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
559
560         if ($pendpage->try_flush($this->curtime) == FALSE) {
561             // Add $pendpage to the pendpage array
562             $this->pendpage_add($pendpage);
563         }
564     }
565
566     function pendpage_add($pendpage)
567     {
568         array_push($this->pending_pages, $pendpage);
569         $this->socks_set($pendpage->socket_get(), NULL, $pendpage);
570     }
571
572     function pendpage_rem($pendpage)
573     {
574         $sock = $pendpage->socket_get();
575         if (($key = array_search($pendpage, $this->pending_pages)) !== FALSE) {
576             unset($this->pending_pages[$key]);
577         }
578         else {
579             fprintf(STDERR, "WARNING: pendpage not found\n");
580         }
581         $this->socks_unset($sock);
582         fprintf(STDERR, "PP_REM: %d\n", intval($sock));
583     }
584
585
586     function pendpage_try_addwait(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
587     {
588         $pendpage = PendingPage::pendingpage_waiting($new_socket, $this->curtime, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont);
589         /*
590         if ($pendpage->try_flush($this->curtime) == FALSE) {
591             // Add $pendpage to the pendpage array
592             */
593         $this->pendpage_add($pendpage);
594         /*
595         }
596         */
597     }
598
599     function garbage_manager($force)
600     {
601         $this->app->garbage_manager($force);
602
603         foreach ($this->socks as $k => $sock) {
604             $id = intval($sock);
605             if (isset($this->s2u[$id])) {
606                 if ($this->s2u[$id]->sess == '') {
607                     if ($this->s2u[$id]->rd_socket_get() != NULL) {
608                         $this->s2u[$id]->rd_socket_set(NULL);
609                     }
610                     unset($this->socks[$id]);
611                     unset($this->s2u[$id]);
612                     fclose($sock);
613                     printf("CLOSE ON GARBAGE MANAGER\n");
614                 }
615             }
616         }
617     }
618
619     function run()
620     {
621         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
622
623         GLOBAL $G_alarm_passwd, $G_ban_list, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
624         GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
625         GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
626         GLOBAL $G_room_roadmap, $G_shutdown;
627         GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
628         GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
629         GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
630         GLOBAL $G_with_splash, $G_sidebanner, $G_sidebanner_idx;
631         GLOBAL $G_with_topbanner;
632         GLOBAL $G_tos_vers, $G_tos_fname, $G_tos_dtsoft, $G_tos_dthard, $G_tos_idx, $G_doc_path;
633
634         if ($this->main_loop) {
635             return (FALSE);
636         }
637         
638         $this->main_loop = TRUE;
639         
640         while ($this->main_loop) {
641             $this->app->sess_cur_set(FALSE);
642             $this->curtime = time();
643             fprintf(STDERR, "IN LOOP: Current opened: %d  pending_pages: %d\n", count($this->socks), count($this->pending_pages));
644             
645             /* Prepare the read array */
646             /* // when we manage it ... */
647             /* if ($shutdown)  */
648             /*     $read   = array_merge(array("$in" => $in), $socks); */
649             /* else */
650             $pre_read = array_merge(array(intval($this->list_web) => $this->list_web,
651                                           intval($this->list_cmd) => $this->list_cmd,
652                                           intval(static::$cnt_slave) => static::$cnt_slave),
653                                     $this->socks);
654             if ($this->is_daemon == FALSE) {
655                 $read = array_merge($pre_read, array(intval($this->in) => $this->in));
656             }
657             else {
658                 $read = $pre_read;
659             }
660             
661             if ($this->debug > 1) {
662                 printf("PRE_SELECT\n");
663                 print_r($read);
664             }
665             $write  = NULL;
666             $except = NULL;
667             $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
668         
669             if ($num_changed_sockets == 0) {
670                 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
671             } 
672             else if ($num_changed_sockets > 0) {
673                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
674                 if ($this->debug > 1) {
675                     print_r($read);
676                 }
677                 /* At least at one of the sockets something interesting happened */
678                 foreach ($read as $i => $sock) {
679                     $id = intval($sock);
680                     $manage_page = FALSE;
681                     /* is_resource check is required because there is the possibility that
682                        during new request an old connection is closed */
683                     if (!is_resource($sock)) {
684                         continue;
685                     }
686                     if ($sock === $this->list_web) {
687                         printf("NUOVA CONNEX\n");
688                         if (($new_unix = stream_socket_accept($this->list_web)) == FALSE) {
689                             printf("SOCKET_ACCEPT FAILED\n");
690                             continue;
691                         }
692                         $stream_info = "";
693                         $method      = "";
694                         $get         = array();
695                         $post        = array();
696                         $cookie      = array();
697                         $rest        = 0;
698                         $cont        = "";
699                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
700                             printf("NEW_SOCKET: %d\n", intval($new_socket));
701                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
702                             printf("RECEIVED HEADER:\n%s", $stream_info);
703                             if (($path = spu_process_info($stream_info, $method, $header,
704                                                           $get, $post, $cookie, $rest, $cont))
705                                 == FALSE) {
706                                 fprintf(STDERR, "TODO: fix wrong header management\n");
707                             }
708                             $addr = stream_socket_get_name($new_socket, TRUE);
709                             printf("PATH: [%s]\n", $path);
710                             if ($method == "POST" && $rest > 0) {
711                                 if (isset($header['Expect']) && $header['Expect'] == '100-continue') {
712                                     fprintf(STDERR, "\nPOSTA DE CHE\n\n");
713                                     $this->pendpage_try_addcont($new_socket, 20,
714                                                                 $method, $header, $get, $post, $cookie,
715                                                                 $path, $addr, $rest, $cont);
716                                 }
717                                 else {
718                                     $this->pendpage_try_addwait($new_socket, 20,
719                                                                 $method, $header, $get, $post, $cookie,
720                                                                 $path, $addr, $rest, $cont);
721                                 }
722                             }
723                             else {
724                                 $manage_page = TRUE;
725                             }
726
727                             printf("number of sockets after %d\n", count($this->socks));
728                         }
729                         else {
730                             printf("WARNING: ancillary_getstream failed\n");
731                         }
732                     }
733                     else if ($sock === $this->list_cmd) {
734                         printf("NUOVA DIRECT CONNEX\n");
735                         if (($new_unix = stream_socket_accept($this->list_cmd)) == FALSE) {
736                             printf("SOCKET_ACCEPT FAILED\n");
737                             continue;
738                         }
739                         stream_set_blocking($new_unix, $this->blocking_mode);
740                         $this->direct_mgmt($new_unix);
741                     } // not socket_list nor socket_list_cmd
742                     else {  // already opened socket
743                         $buf = fread($sock, 4096);
744                         // if socket is closed
745                         if ($buf == FALSE || feof($sock)) {
746                             // close socket case
747                             if ($buf == FALSE) {
748                                 printf("INFO: read return false\n");
749                             }
750                             if ($sock === $this->list_web) {
751                                 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
752                                 return(21);
753                             }
754                             else if ($sock === $this->list_cmd) {
755                                 printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
756                                 return(23);
757                             }
758                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
759                                 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
760                                 return(22);
761                             }
762                             else {
763                                 unset($this->socks[$id]);
764                                 if (isset($this->s2u[$id])) {
765                                     // $user_a[$s2u[$id]]->disable();
766                                     if ($this->s2u[$id]->rd_socket_get() != NULL) {
767                                         // try to send close frame (for websocket)
768                                         $clo = $this->s2u[$id]->stream_close();
769                                         $clo_l = mb_strlen($clo, "ASCII");
770                                         @fwrite($sock, $clo, $clo_l);
771                                         $this->s2u[$id]->rd_socket_set(NULL);
772                                     }
773                                     unset($this->s2u[$id]);
774                                 }
775                             }
776                             fclose($sock);
777                             printf("CLOSE ON READ\n");
778
779                             if ($this->debug > 1) {
780                                 printf("post unset\n");
781                                 print_r($this->socks);
782                             }
783                         }  // if ($buf == FALSE || mb_strlen($buf, "ASCII") == 0) {
784                         else { // data on the socket
785                             if ($this->debug > 1) {
786                                 print_r($read);
787                             }
788                             if ($sock === $this->list_web) {
789                                 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
790                             }
791                             else if ($sock === $this->list_cmd) {
792                                 printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
793                             }
794                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
795                                 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
796                                 $line = trim($buf);
797                                 if ($line == "reload") {
798                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
799                                     $this->app->reload(FALSE, $G_ban_list, $G_black_list);
800                                     global_dump();
801                                 }
802                                 else if ($line == "shutdown" || $line == "sd") {
803                                     if ($this->app->dump_data()) {
804                                         return(0);
805                                     }
806                                     else {
807                                         return(1);
808                                     }
809                                 }
810                             }
811                             else {  // data arrived from not special socket
812                                 $key = array_search("$sock", $this->socks);
813                                 fprintf(STDERR, "Arrivati %d bytes dalla socket n. %d\n", mb_strlen($buf, "ASCII"), $key);
814                                 if (isset($this->s2p[$id])) {
815                                     $this->s2p[$id]->rest -= mb_strlen($buf, "ASCII");
816                                     $this->s2p[$id]->cont .= $buf;
817                                     if ($this->s2p[$id]->rest <= 0) {
818                                         $header = $new_socket = $path = $addr = $get = $cookie = 0;
819                                         $post = array();
820
821                                         $this->s2p[$id]->context_get($header, $new_socket, $path, $addr, $get, $post, $cookie);
822                                         $this->pendpage_rem($this->s2p[$id]);
823                                         fprintf(STDERR, "SOCKET RUN: %s\n", $new_socket);
824
825                                         $manage_page = TRUE;
826                                     }
827                                 }
828                             }
829                         }
830                     }
831
832                     if ($manage_page == TRUE) {
833                         printf("M: %s\nHEADER:\n", $method);
834                         print_r($header);
835                         printf("GET:\n");
836                         print_r($get);
837                         printf("POST:\n");
838                         print_r($post);
839                         printf("COOKIE:\n");
840                         print_r($cookie);
841
842                         $header_out = array();
843                         // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
844                         $rret = FALSE;
845                         if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
846                             $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
847                         }
848                         if ($rret == FALSE) {
849                             // FIXME: manage 404 !!!
850                             printf("TODO: fix unknown page\n");
851                         }
852                     }
853                 }
854             }
855
856             $this->garbage_manager(FALSE);
857
858             /* manage unfinished pages */
859             foreach ($this->pending_pages as $k => $pendpage) {
860                 // TODO: try_flush if exists in the class
861                 if ($pendpage->try_flush($this->curtime) == TRUE) {
862                     unset($this->pending_pages[$k]);
863                 }
864             }
865             
866             /*
867                $response:                        raw stream data not sent
868                $content:                         html consistent data (<script bla bla>)
869                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
870             */
871
872             /* manage open streaming */
873             foreach ($this->socks as $k => $sock) {
874                 $id = intval($sock);
875                 if (isset($this->s2u[$id])) {
876                     $user = $this->s2u[$id];
877                     $response = $user->rd_cache_get();
878                     $do_ping = FALSE;
879                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
880                         $do_ping = TRUE;
881                     }
882                     else {
883                         $user->ping_req = FALSE;
884                     }
885
886                     if ($response == "") {
887                         $content = "";
888                         $user->stream_main($content, $get, $post, $cookie);
889                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
890                         if ($do_ping && $user->ping_req == FALSE) {
891                             $content .= $user->stream_keepalive(TRUE);
892                             $user->ping_req = TRUE;
893                         }
894                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
895                             $content = $user->stream_keepalive(FALSE);
896                         }
897                         if ($content != "") {
898                             $response = $user->chunked_content($content);
899                         }
900                     }
901                     
902                     if ($response != "") {
903                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
904                         // echo "SPIA: [".$response."]\n";
905                         $response_l = mb_strlen($response, "ASCII");
906                         $wret = @fwrite($sock, $response, $response_l);
907                         if ($wret < $response_l) {
908                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
909                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
910                         }
911                         else {
912                             $user->rd_cache_set("");
913                         }
914                         fflush($sock);
915                         $user->rd_kalive_reset($this->curtime);
916                     }
917                     
918                     // close socket after a while to prevent client memory consumption
919                     if ($user->rd_endtime_is_expired($this->curtime)) {
920                         if ($this->s2u[$id]->rd_socket_get() != NULL) {
921                             $this->s2u[$id]->rd_socket_set(NULL);
922                         }
923                         unset($this->socks[$id]);
924                         unset($this->s2u[$id]);
925                         $clo = $user->stream_close();
926                         $clo_l = mb_strlen($clo, "ASCII");
927                         @fwrite($sock, $clo, $clo_l);
928                         fclose($sock);
929                         printf("CLOSE ON LOOP\n");
930                     }
931                 }  // if (isset($this->s2u[$id]...
932             }  // foreach ($this->socks...
933             printf("\n");
934             $this->app->cds->process();
935         }  // while (...
936     }  // function run(...
937
938     function direct_command($cmdstr)
939     {
940         GLOBAL $G_alarm_passwd;
941
942         $cmd = cmd_deserialize($cmdstr);
943
944         if (!isset($cmd['cmd'])) {
945             return cmd_return(500, 'no cmd found');
946         }
947         // "cmd" => "userauth", "sess" => 'xxxxxxxxxxx', 'private' => 'it_must_be_correct',
948         //           'the_end' => 'true' );
949         // cmd=userauth&sess=52d796ac08c47&private=yourpasswd192.168.122.152d796ac08c47&the_end=true
950         if ($cmd['cmd'] == 'userauth') {
951             if (!isset($cmd['sess']) || !isset($cmd['private'])) {
952                 return cmd_return(401, 'malformed cmd');
953             }
954             $idx = -1;
955             if (($user = $this->app->get_user($cmd['sess'], &$idx)) == FALSE)
956                 return cmd_return(402, 'user not found');
957
958             if (($user->flags & USER_FLAG_TY_ADMIN) == 0x00)
959                 return cmd_return(403, 'permission denied');
960
961             if (md5($G_alarm_passwd.$user->ip.$user->sess) != $cmd['private'])
962                 return cmd_return(404, 'authentication failed ['.$cmd['private'].']['.$G_alarm_passwd.$user->ip.$user->sess.']');
963
964             return cmd_return(200, 'success');
965         }
966
967         return cmd_return(501, 'no cmd found');
968     }
969
970     function direct_mgmt($socket)
971     {
972         printf("DIRECT: begin\n");
973         $st = DIRECT_ST_READ;
974         $cmd_all = "";
975         $endtime = $this->curtime + 3;
976
977         while(time() <= $endtime) {
978             printf("DIRECT: init loop %d\n", $st);
979             if ($st == DIRECT_ST_READ) {
980                 $buf = fread($socket, 4096);
981                 if ($buf == FALSE && feof($socket)) {
982                     break;
983                 }
984                 else if ($buf != FALSE && strlen($buf) > 0) {
985                     $cmd_all .= $buf;
986
987                     if (substr(trim($cmd_all), -13) == "&the_end=true") {
988                         $output_arr = $this->direct_command($cmd_all);
989                         $output = cmd_serialize($output_arr);
990                         $output_cur = 0;
991                         $output_len = mb_strlen($output, "ASCII");
992                         $st = DIRECT_ST_WRITE;
993                         continue;
994                     }
995                 }
996             }
997             else if ($st == DIRECT_ST_WRITE)  {
998                 $ret = fwrite($socket, $output, $output_len);
999                 if ($ret === FALSE) {
1000                     if (feof($socket)) {
1001                         break;
1002                     }
1003                 }
1004                 else if ($ret > 0 && $ret < $output_len) {
1005                     $output = substr($output, -($output_len - $ret));
1006                     $output_len -= $ret;
1007                     continue;
1008                 }
1009                 else if ($ret == $output_len) {
1010                     fclose($socket);
1011                     return TRUE;
1012                 }
1013             }
1014             usleep(10000);
1015         }
1016
1017         fclose($socket);
1018         return FALSE;
1019     }
1020 } // class Sac_a_push
1021 ?>