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