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