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