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