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