3 * brisk - Obj/sac-a-push.phh
5 * Copyright (C) 2012-2014 Matteo Nastasi
6 * mailto: nastasi@alternativeoutput.it
7 * matteo.nastasi@milug.org
8 * web: http://www.alternativeoutput.it
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.
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.
25 define('SITE_PREFIX', '/brisk/');
26 define('SITE_PREFIX_LEN', 7);
28 define('DIRECT_ST_READ', 1);
29 define('DIRECT_ST_WRITE', 2);
33 function global_dump()
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;
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));
81 $fname = LEGAL_PATH."/brisk.pid";
83 if (file_exists($fname)) {
84 log_crit("WARN: brisk.pid already exists");
86 file_put_contents($fname, sprintf("%d\n", $pid));
91 $fname = LEGAL_PATH."/brisk.pid";
93 if (file_exists($fname)) {
98 function post_manage(&$post, $line)
100 $a = explode('&', $line);
101 for ($i = 0 ; $i < count($a) ; $i++) {
102 $b = explode('=', $a[$i]);
105 $post[$b[0]] = urldecode($b[1]);
114 function spu_process_info($stream_info, &$method, &$header, &$get, &$post, &$cookie, &$rest, &$cont)
121 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
122 printf("LINE: [%s]\n", $line);
124 if (!isset($header['The-Request'])) {
127 $req = explode(" ", $header['The-Request']);
130 if (isset($header['Cookie'])) {
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)]
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]] = "";
142 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
147 $value = mb_substr($cookies[$i], mb_strlen($name)+1, 10140, 'UTF-8');
148 $cookie[$name] = urldecode($value);
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]);
161 $get[$b[0]] = urldecode($b[1]);
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
170 // if (content-type is wrong || content-length isn't set)
173 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
174 || !isset($header['Content-Length'])) {
177 $post_len = mb_strlen($line, "ASCII");
178 printf("INFO: postlen: %d\n", $post_len);
179 $rest = (int)($header['Content-Length']) - $post_len;
182 post_manage($post, $line);
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];
201 function gpcs_var($name, $get, $post, $cookie)
203 if (isset($GLOBALS[$name]))
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]);
215 function headers_render($header, $len)
219 if (isset($header['cookies'])) {
220 $cookies = $header['cookies']->render();
221 unset($header['cookies']);
223 if (isset($header['Location'])) {
224 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
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")
231 $s .= sprintf("%s: %s\r\n", $key, $value);
234 $s .= sprintf("Content-Length: %ld\r\n", $len);
238 $s = "HTTP/1.1 200 OK\r\n";
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);
250 $s .= sprintf("Content-Length: %d\r\n", $len);
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";
258 $s .= "Transfer-Encoding: chunked\r\n";
268 * Caching system using ob php system to cache old style pages
269 * to a var and than send it with more calm
274 log_rd2("SHUTTA [".connection_status()."] !");
277 register_shutdown_function('shutta');
283 function get_encoding($header)
286 if (isset($header['Accept-Encoding'])) {
287 $acc = explode(',', $header['Accept-Encoding']);
289 if (array_search('gzip', $acc) !== FALSE) {
292 else if (array_search('deflate', $acc) !== FALSE) {
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 ]]]]]] )
306 $this->attr = array();
309 static function create($name)
311 $thiz = new Cookie();
313 $thiz->attr[$name] = "";
315 $argc = func_num_args();
316 for ($i = 1 ; $i < $argc ; $i++) {
317 $arg = func_get_arg($i);
320 $thiz->attr[$name] = urlencode($arg);
323 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
326 $thiz->attr['Path'] = $arg;
329 $thiz->attr['Domain'] = $arg;
333 $thiz->attr['Secure'] = NULL;
338 $thiz->attr['HttpOnly'] = NULL;
354 foreach ($this->attr as $k => $v) {
356 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
359 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
374 $this->cookies = array();
379 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
382 array_push($this->cookies, $cookie);
390 foreach ($this->cookies as $cookie) {
391 $r .= $cookie->render();
400 // maybe fixed_fd is unuseful
401 static $fixed_fd = 3;
402 static $cnt_master = NULL;
403 static $cnt_slave = NULL;
407 var $direct_socket; // socket where read direct commands
409 var $s2u; // user associated with input socket
410 var $s2p; // pending page associated with input socket
428 function Sac_a_push()
432 function sig_handler($sig)
439 if (static::$cnt_master != NULL) {
440 fwrite(static::$cnt_master, "\nshutdown\n");
441 fflush(static::$cnt_master);
448 if (static::$cnt_master != NULL) {
449 fwrite(static::$cnt_master, "\nreload\n");
450 fflush(static::$cnt_master);
456 static function create(&$app, $sockname, $debug, $blocking_mode, $argv)
458 $thiz = new Sac_a_push();
461 $thiz->file_socket = $sockname;
462 $thiz->unix_socket = "unix://$sockname";
463 $thiz->direct_socket = "unix://${sockname}2";
464 $thiz->debug = $debug;
465 $thiz->socks = array();
466 $thiz->s2u = array();
467 $thiz->s2p = array();
468 $thiz->pending_pages = array();
469 $thiz->is_daemon = FALSE;
471 if (array_search("-d", $argv) !== FALSE || array_search("--daemon", $argv) !== FALSE) {
472 $thiz->is_daemon = TRUE;
475 // create a couple of sockets for control management
476 if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
477 STREAM_IPPROTO_IP)) == FALSE) {
480 static::$cnt_master = $sockpair[0];
481 static::$cnt_slave = $sockpair[1];
483 pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
484 pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
485 pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
487 $thiz->blocking_mode = 0; // 0 for non-blocking
490 for ($i = 0 ; $i < 4096 ; $i++) {
492 $thiz->rndstr .= " ";
494 $thiz->rndstr .= chr(mt_rand(65, 90));
497 if (file_exists($thiz->file_socket)) {
498 unlink($thiz->file_socket);
500 if (file_exists($thiz->file_socket."2")) {
501 unlink($thiz->file_socket."2");
504 $old_umask = umask(0);
505 if (($thiz->list_web = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
508 if (($thiz->list_cmd = stream_socket_server($thiz->direct_socket, $err, $errs)) === FALSE) {
512 stream_set_blocking($thiz->list_web, $thiz->blocking_mode); # Set the stream to non-blocking
513 stream_set_blocking($thiz->list_cmd, $thiz->blocking_mode); # Set the stream to non-blocking
515 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
519 $thiz->main_loop = FALSE;
524 function socks_set($sock, $user, $pendpage)
528 $this->socks[$id] = $sock;
530 $this->s2u[$id] = $user;
531 if ($pendpage != NULL)
532 $this->s2p[$id] = $pendpage;
535 function socks_unset($sock)
539 if (isset($this->s2u[$id]))
540 unset($this->s2u[$id]);
541 if (isset($this->s2p[$id]))
542 unset($this->s2p[$id]);
543 unset($this->socks[$id]);
546 function pendpage_try_addcont(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
548 $pendpage = PendingPage::pendingpage_continue(&$new_socket, $this->curtime, $tout, $method,
549 $header, $get, $post, $cookie,
550 $path, $addr, $rest, $cont);
552 $pendpage->try_flush($this->curtime);
553 // Add $pendpage to the pendpage array (in any case)
554 fprintf(STDERR, "IMPORTANT: Pendadd: %d\n", $pendpage->status);
555 $this->pendpage_add($pendpage);
558 function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
560 $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
562 if ($pendpage->try_flush($this->curtime) == FALSE) {
563 // Add $pendpage to the pendpage array
564 $this->pendpage_add($pendpage);
568 function pendpage_add($pendpage)
570 array_push($this->pending_pages, $pendpage);
571 $this->socks_set($pendpage->socket_get(), NULL, $pendpage);
574 function pendpage_rem($pendpage)
576 $sock = $pendpage->socket_get();
577 if (($key = array_search($pendpage, $this->pending_pages)) !== FALSE) {
578 unset($this->pending_pages[$key]);
581 fprintf(STDERR, "WARNING: pendpage not found\n");
583 $this->socks_unset($sock);
584 fprintf(STDERR, "PP_REM: %d\n", intval($sock));
588 function pendpage_try_addwait(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
590 $pendpage = PendingPage::pendingpage_waiting($new_socket, $this->curtime, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont);
592 if ($pendpage->try_flush($this->curtime) == FALSE) {
593 // Add $pendpage to the pendpage array
595 $this->pendpage_add($pendpage);
601 function garbage_manager($force)
603 $this->app->garbage_manager($force);
605 foreach ($this->socks as $k => $sock) {
607 if (isset($this->s2u[$id])) {
608 if ($this->s2u[$id]->the_end) {
609 if ($this->s2u[$id]->rd_socket_get() != NULL) {
610 $this->s2u[$id]->rd_socket_set(NULL);
612 unset($this->socks[$id]);
613 unset($this->s2u[$id]);
615 printf("CLOSE ON GARBAGE MANAGER\n");
619 $this->app->users_cleanup();
624 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
626 GLOBAL $G_alarm_passwd, $G_ban_list, $G_black_list, $G_cloud_smasher, $G_provider_proxy;
627 GLOBAL $G_btrace_pref_sub, $G_dbauth;
628 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
629 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
630 GLOBAL $G_room_roadmap, $G_shutdown;
631 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
632 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
633 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
634 GLOBAL $G_with_splash, $G_sidebanner, $G_sidebanner_idx;
635 GLOBAL $G_with_topbanner;
636 GLOBAL $G_tos_vers, $G_tos_fname, $G_tos_dtsoft, $G_tos_dthard, $G_tos_idx, $G_doc_path;
638 if ($this->main_loop) {
642 $this->main_loop = TRUE;
644 while ($this->main_loop) {
645 $this->app->sess_cur_set(FALSE);
646 $this->curtime = time();
647 fprintf(STDERR, "IN LOOP: Current opened: %d pending_pages: %d\n", count($this->socks), count($this->pending_pages));
649 /* Prepare the read array */
650 /* // when we manage it ... */
652 /* $read = array_merge(array("$in" => $in), $socks); */
654 $pre_read = array_merge(array(intval($this->list_web) => $this->list_web,
655 intval($this->list_cmd) => $this->list_cmd,
656 intval(static::$cnt_slave) => static::$cnt_slave),
658 if ($this->is_daemon == FALSE) {
659 $read = array_merge($pre_read, array(intval($this->in) => $this->in));
665 if ($this->debug > 1) {
666 printf("PRE_SELECT\n");
671 $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
673 if ($num_changed_sockets == 0) {
674 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
676 else if ($num_changed_sockets > 0) {
677 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
678 if ($this->debug > 1) {
681 /* At least at one of the sockets something interesting happened */
682 foreach ($read as $i => $sock) {
684 $manage_page = FALSE;
685 /* is_resource check is required because there is the possibility that
686 during new request an old connection is closed */
687 if (!is_resource($sock)) {
690 if ($sock === $this->list_web) {
691 printf("NUOVA CONNEX\n");
692 if (($new_unix = stream_socket_accept($this->list_web)) == FALSE) {
693 printf("SOCKET_ACCEPT FAILED\n");
703 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
704 printf("NEW_SOCKET: %d\n", intval($new_socket));
705 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
706 printf("RECEIVED HEADER:\n%s", $stream_info);
707 if (($path = spu_process_info($stream_info, $method, $header,
708 $get, $post, $cookie, $rest, $cont))
710 fprintf(STDERR, "TODO: fix wrong header management\n");
712 $addr = stream_socket_get_name($new_socket, TRUE);
713 printf("PATH: [%s]\n", $path);
714 if ($method == "POST" && $rest > 0) {
715 if (isset($header['Expect']) && $header['Expect'] == '100-continue') {
716 fprintf(STDERR, "\nPOSTA DE CHE\n\n");
717 $this->pendpage_try_addcont($new_socket, 20,
718 $method, $header, $get, $post, $cookie,
719 $path, $addr, $rest, $cont);
722 $this->pendpage_try_addwait($new_socket, 20,
723 $method, $header, $get, $post, $cookie,
724 $path, $addr, $rest, $cont);
731 printf("number of sockets after %d\n", count($this->socks));
734 printf("WARNING: ancillary_getstream failed\n");
737 else if ($sock === $this->list_cmd) {
738 printf("NUOVA DIRECT CONNEX\n");
739 if (($new_unix = stream_socket_accept($this->list_cmd)) == FALSE) {
740 printf("SOCKET_ACCEPT FAILED\n");
743 stream_set_blocking($new_unix, $this->blocking_mode);
744 $this->direct_mgmt($new_unix);
745 } // not socket_list nor socket_list_cmd
746 else { // already opened socket
747 $buf = fread($sock, 4096);
748 // if socket is closed
749 if ($buf == FALSE || feof($sock)) {
752 printf("INFO: read return false\n");
754 if ($sock === $this->list_web) {
755 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
758 else if ($sock === $this->list_cmd) {
759 printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
762 else if ($sock === $this->in || $sock === static::$cnt_slave) {
763 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
767 unset($this->socks[$id]);
768 if (isset($this->s2u[$id])) {
769 // $user_a[$s2u[$id]]->disable();
770 if ($this->s2u[$id]->rd_socket_get() != NULL) {
771 // try to send close frame (for websocket)
772 $clo = $this->s2u[$id]->stream_close();
773 $clo_l = mb_strlen($clo, "ASCII");
774 @fwrite($sock, $clo, $clo_l);
775 $this->s2u[$id]->rd_socket_set(NULL);
777 unset($this->s2u[$id]);
781 printf("CLOSE ON READ\n");
783 if ($this->debug > 1) {
784 printf("post unset\n");
785 print_r($this->socks);
787 } // if ($buf == FALSE || mb_strlen($buf, "ASCII") == 0) {
788 else { // data on the socket
789 if ($this->debug > 1) {
792 if ($sock === $this->list_web) {
793 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
795 else if ($sock === $this->list_cmd) {
796 printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
798 else if ($sock === $this->in || $sock === static::$cnt_slave) {
799 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
801 if ($line == "reload") {
802 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
803 $this->app->reload(FALSE, $G_ban_list, $G_black_list,
804 $G_cloud_smasher, $G_provider_proxy);
807 else if ($line == "shutdown" || $line == "sd") {
808 if ($this->app->dump_data()) {
816 else { // data arrived from not special socket
817 $key = array_search("$sock", $this->socks);
818 fprintf(STDERR, "Arrivati %d bytes dalla socket n. %d\n", mb_strlen($buf, "ASCII"), $key);
819 if (isset($this->s2p[$id])) {
820 $this->s2p[$id]->rest -= mb_strlen($buf, "ASCII");
821 $this->s2p[$id]->cont .= $buf;
822 if ($this->s2p[$id]->rest <= 0) {
823 $header = $new_socket = $path = $addr = $get = $cookie = 0;
826 $this->s2p[$id]->context_get($header, $new_socket, $path, $addr, $get, $post, $cookie);
827 $this->pendpage_rem($this->s2p[$id]);
828 fprintf(STDERR, "SOCKET RUN: %s\n", $new_socket);
837 if ($manage_page == TRUE) {
838 printf("M: %s\nHEADER:\n", $method);
847 $header_out = array();
848 // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
850 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
851 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
853 if ($rret == FALSE) {
854 // FIXME: manage 404 !!!
855 printf("TODO: fix unknown page\n");
862 $this->garbage_manager(FALSE);
864 /* manage unfinished pages */
865 foreach ($this->pending_pages as $k => $pendpage) {
866 // TODO: try_flush if exists in the class
867 if ($pendpage->try_flush($this->curtime) == TRUE) {
868 unset($this->pending_pages[$k]);
873 $response: raw stream data not sent
874 $content: html consistent data (<script bla bla>)
875 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
878 /* manage open streaming */
879 foreach ($this->socks as $k => $sock) {
881 if (isset($this->s2u[$id])) {
882 $user = $this->s2u[$id];
884 if ($user->rd_toflush) {
885 if (fflush($sock) == FALSE)
888 $user->rd_toflush = FALSE;
890 $response = $user->rd_cache_get();
892 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
896 $user->ping_req = FALSE;
899 if ($response == "") {
901 $user->stream_main($content, $get, $post, $cookie);
902 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
903 if ($do_ping && $user->ping_req == FALSE) {
904 $content .= $user->stream_keepalive(TRUE);
905 $user->ping_req = TRUE;
907 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
908 $content = $user->stream_keepalive(FALSE);
910 if ($content != "") {
911 $response = $user->chunked_content($content);
915 if ($response != "") {
916 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
917 // echo "SPIA: [".$response."]\n";
918 $response_l = mb_strlen($response, "ASCII");
919 $wret = @fwrite($sock, $response, $response_l);
920 if ($wret < $response_l) {
921 printf("TROUBLE WITH FWRITE: %d\n", $wret);
922 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
925 $user->rd_cache_set("");
927 if (fflush($sock) == FALSE) {
928 $user->rd_toflush = TRUE;
931 $user->rd_kalive_reset($this->curtime);
934 // close socket after a while to prevent client memory consumption
935 if ($user->rd_endtime_is_expired($this->curtime)) {
936 if ($this->s2u[$id]->rd_socket_get() != NULL) {
937 $this->s2u[$id]->rd_socket_set(NULL);
939 unset($this->socks[$id]);
940 unset($this->s2u[$id]);
941 $clo = $user->stream_close();
942 $clo_l = mb_strlen($clo, "ASCII");
943 @fwrite($sock, $clo, $clo_l);
945 printf("CLOSE ON LOOP\n");
947 } // if (isset($this->s2u[$id]...
948 } // foreach ($this->socks...
950 if (defined('CURL_DE_SAC_VERS')) {
951 $this->app->cds->process();
954 } // function run(...
956 function direct_command($cmdstr)
958 GLOBAL $G_alarm_passwd;
960 $cmd = cmd_deserialize($cmdstr);
962 if (!isset($cmd['cmd'])) {
963 return cmd_return(500, 'no cmd found');
965 // "cmd" => "userauth", "sess" => 'xxxxxxxxxxx', 'private' => 'it_must_be_correct',
966 // 'the_end' => 'true' );
967 // cmd=userauth&sess=52d796ac08c47&private=yourpasswd192.168.122.152d796ac08c47&the_end=true
968 if ($cmd['cmd'] == 'userauth') {
969 if (!isset($cmd['sess']) || !isset($cmd['private'])) {
970 return cmd_return(401, 'malformed cmd');
973 if (($user = $this->app->get_user($cmd['sess'], &$idx)) == FALSE)
974 return cmd_return(402, 'user not found');
976 if (($user->flags & USER_FLAG_TY_ADMIN) == 0x00)
977 return cmd_return(403, 'permission denied');
979 if (md5($G_alarm_passwd.$user->ip.$user->sess) != $cmd['private'])
980 return cmd_return(404, 'authentication failed ['.$cmd['private'].']['.$G_alarm_passwd.$user->ip.$user->sess.']');
982 return cmd_return(200, 'success');
985 return cmd_return(501, 'no cmd found');
988 function direct_mgmt($socket)
990 printf("DIRECT: begin\n");
991 $st = DIRECT_ST_READ;
993 $endtime = $this->curtime + 3;
995 while(time() <= $endtime) {
996 printf("DIRECT: init loop %d\n", $st);
997 if ($st == DIRECT_ST_READ) {
998 $buf = fread($socket, 4096);
999 if ($buf == FALSE && feof($socket)) {
1002 else if ($buf != FALSE && strlen($buf) > 0) {
1005 if (substr(trim($cmd_all), -13) == "&the_end=true") {
1006 $output_arr = $this->direct_command($cmd_all);
1007 $output = cmd_serialize($output_arr);
1009 $output_len = mb_strlen($output, "ASCII");
1010 $st = DIRECT_ST_WRITE;
1015 else if ($st == DIRECT_ST_WRITE) {
1016 $ret = fwrite($socket, $output, $output_len);
1017 if ($ret === FALSE) {
1018 if (feof($socket)) {
1022 else if ($ret > 0 && $ret < $output_len) {
1023 $output = substr($output, -($output_len - $ret));
1024 $output_len -= $ret;
1027 else if ($ret == $output_len) {
1038 } // class Sac_a_push