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 /* this list is created with bin/get_globals.sh */
34 $_globals_list = array(
35 'G_admin_mail', 'G_alarm_passwd', 'G_all_points', 'G_ban_list', 'G_base',
36 'G_black_list', 'G_brisk_version', 'G_btrace_pref_sub', 'G_cloud_smasher',
37 'G_crypt_key', 'G_dbasetype', 'G_dbauth', 'G_dbpfx', 'G_doc_path',
38 'G_proto', 'G_domain', 'G_donors_all', 'G_donors_cur', 'G_is_local', 'G_lang', 'G_lng',
39 'G_mail_seed', 'G_notguar_code', 'G_PG_cons', 'G_PG_cons_n', 'G_PG_vow',
40 'G_PG_vow_n', 'G_poll_entries', 'G_poll_name', 'G_poll_title',
41 'G_provider_proxy', 'G_proxy_white_list', 'G_room_about', 'G_room_help',
42 'G_room_passwdhowto', 'G_room_roadmap',
43 'G_selfreg_mask', 'G_selfreg_tout', 'G_shutdown', 'G_sidebanner',
44 'G_sidebanner_idx', 'G_splash_content', 'G_splash_contents',
45 'G_splash_cont_idx', 'G_splash_h', 'G_splash_idx', 'G_splash_interval',
46 'G_splash_timeout', 'G_splash_w', 'G_topbanner', 'G_tos_dthard',
47 'G_tos_dtsoft', 'G_tos_fname', 'G_tos_idx', 'G_tos_vers', 'G_webbase');
49 function global_dump()
51 GLOBAL $G_alarm_passwd, $G_ban_list, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
52 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
53 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
54 GLOBAL $G_room_roadmap, $G_shutdown;
55 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
56 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
57 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
58 GLOBAL $G_with_splash, $G_sidebanner, $G_sidebanner_idx;
59 GLOBAL $G_with_topbanner, $G_selfreg_tout, $G_selfreg_mask;
61 fprintf(STDERR, "G_alarm_passwd = [%s]\n", print_r($G_alarm_passwd, TRUE));
62 fprintf(STDERR, "G_ban_list = [%s]\n", print_r($G_ban_list, TRUE));
63 fprintf(STDERR, "G_black_list = [%s]\n", print_r($G_black_list, TRUE));
64 fprintf(STDERR, "G_btrace_pref_sub = [%s]\n", print_r($G_btrace_pref_sub, TRUE));
65 fprintf(STDERR, "G_dbauth = [%s]\n", print_r($G_dbauth, TRUE));
66 fprintf(STDERR, "G_dbpfx = [%s]\n", print_r($G_dbpfx, TRUE));
67 fprintf(STDERR, "G_donors_all = [%s]\n", print_r($G_donors_all, TRUE));
68 fprintf(STDERR, "G_donors_cur = [%s]\n", print_r($G_donors_cur, TRUE));
69 fprintf(STDERR, "G_is_local = [%s]\n", print_r($G_is_local, TRUE));
70 fprintf(STDERR, "G_lang = [%s]\n", print_r($G_lang, TRUE));
71 fprintf(STDERR, "G_poll_entries = [%s]\n", print_r($G_poll_entries, TRUE));
72 fprintf(STDERR, "G_poll_name = [%s]\n", print_r($G_poll_name, TRUE));
73 fprintf(STDERR, "G_poll_title = [%s]\n", print_r($G_poll_title, TRUE));
74 fprintf(STDERR, "G_proxy_white_list = [%s]\n", print_r($G_proxy_white_list, TRUE));
75 fprintf(STDERR, "G_room_roadmap = [%s]\n", print_r($G_room_roadmap, TRUE));
76 fprintf(STDERR, "G_shutdown = [%s]\n", print_r($G_shutdown, TRUE));
77 fprintf(STDERR, "G_splash_content = [%s]\n", print_r($G_splash_content, TRUE));
78 fprintf(STDERR, "G_splash_contents = [%s]\n", print_r($G_splash_contents, TRUE));
79 fprintf(STDERR, "G_splash_cont_idx = [%s]\n", print_r($G_splash_cont_idx, TRUE));
80 fprintf(STDERR, "G_splash_h = [%s]\n", print_r($G_splash_h, TRUE));
81 fprintf(STDERR, "G_splash_idx = [%s]\n", print_r($G_splash_idx, TRUE));
82 fprintf(STDERR, "G_splash_interval = [%s]\n", print_r($G_splash_interval, TRUE));
83 fprintf(STDERR, "G_splash_timeout = [%s]\n", print_r($G_splash_timeout, TRUE));
84 fprintf(STDERR, "G_splash_w = [%s]\n", print_r($G_splash_w, TRUE));
85 fprintf(STDERR, "G_topbanner = [%s]\n", print_r($G_topbanner, TRUE));
86 fprintf(STDERR, "G_with_donors = [%s]\n", print_r($G_with_donors, TRUE));
87 fprintf(STDERR, "G_with_poll = [%s]\n", print_r($G_with_poll, TRUE));
88 fprintf(STDERR, "G_sidebanner = [%s]\n", print_r($G_sidebanner, TRUE));
89 fprintf(STDERR, "G_sidebanner_idx = [%s]\n", print_r($G_sidebanner_idx, TRUE));
90 fprintf(STDERR, "G_with_splash = [%s]\n", print_r($G_with_splash, TRUE));
91 fprintf(STDERR, "G_with_topbanner = [%s]\n", print_r($G_with_topbanner, TRUE));
92 fprintf(STDERR, "G_selfreg_mask = [%x]\n", print_r($G_selfreg_mask, TRUE));
94 fprintf(STDERR, "G_selfreg_tout = [%s]\n", print_r($G_selfreg_tout, TRUE));
101 $fname = LEGAL_PATH."/brisk.pid";
103 if (file_exists($fname)) {
104 log_crit("WARN: brisk.pid already exists");
106 file_put_contents($fname, sprintf("%d\n", $pid));
109 function pid_remove()
111 $fname = LEGAL_PATH."/brisk.pid";
113 if (file_exists($fname)) {
118 function post_manage(&$post, $line)
120 $a = explode('&', $line);
121 for ($i = 0 ; $i < count($a) ; $i++) {
122 $b = explode('=', $a[$i]);
125 $post[$b[0]] = urldecode($b[1]);
134 function spu_process_info($stream_info, &$method, &$header, &$get, &$post, &$cookie, &$rest, &$cont)
141 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
142 printf("LINE: [%s]\n", $line);
144 if (!isset($header['The-Request'])) {
147 $req = explode(" ", $header['The-Request']);
150 if (isset($header['Cookie'])) {
152 // LINE: [Cookie:sess=50e053a9511ef; CO_splashdate4=1356420646; CO_list=all; table_idx=7; table_token=510d494986925; lang=it; CO_bin5_pref_ring_endauct=false; CO_splashdate5=1358372822; CO_splashdate1=1363203374; CO_splashdate2=1363374826; __utma=43654517.209888411.1356605271.1356605271.1356605271.1; __utmz=43654517.1356605271.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)]
154 $cookies = explode("; ", $header['Cookie']);
155 for ($i = 0 ; $i < count($cookies) ; $i++) {
156 $name = mb_strstr($cookies[$i], "=", TRUE, 'UTF-8');
157 if ($name == FALSE) {
158 if (mb_strlen($cookies[$i]) > 0) {
159 $cookie[$cookies[$i]] = "";
162 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
167 $value = mb_substr($cookies[$i], mb_strlen($name)+1, 10140, 'UTF-8');
168 $cookie[$name] = urldecode($value);
171 // GET params management
172 $get_vars = explode('?', $req[1], 2);
173 $path = $get_vars[0];
174 if (count($get_vars) > 1) {
175 $a = explode('&', $get_vars[1]);
176 printf("A COUNT: [%s] %d\n", $a[0], count($a));
177 for ($i = 0 ; $i < count($a) ; $i++) {
178 $b = explode('=', $a[$i]);
181 $get[$b[0]] = urldecode($b[1]);
184 // POST params management
185 if ($req[0] == 'POST') {
186 $conttype_all = explode(";", $header['Content-Type']);
187 $header['Content-Type'] = $conttype_all[0];
188 // $path_all[1-] other things like charset and so on
190 // if (content-type is wrong || content-length isn't set)
193 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
194 || !isset($header['Content-Length'])) {
197 $post_len = mb_strlen($line, "ASCII");
198 printf("INFO: postlen: %d\n", $post_len);
199 $rest = (int)($header['Content-Length']) - $post_len;
202 post_manage($post, $line);
214 $split = explode(":", $line, 2);
215 $hea_id = trim(mb_convert_case($split[0], MB_CASE_TITLE, 'UTF-8'));
216 $header[$hea_id] = $split[1];
221 function gpcs_var($name, $get, $post, $cookie)
223 if (isset($GLOBALS[$name]))
225 else if (isset($cookie[$name]))
226 return ($cookie[$name]);
227 else if (isset($post[$name]))
228 return ($post[$name]);
229 else if (isset($get[$name]))
230 return ($get[$name]);
235 function headers_render($header, $len)
239 if (isset($header['cookies'])) {
240 $cookies = $header['cookies']->render();
241 unset($header['cookies']);
243 if (isset($header['Location'])) {
244 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
246 else if (isset($header['HTTP-Response'])) {
247 $s = sprintf("HTTP/1.1 %s\r\n", $header['HTTP-Response']);
248 foreach($header as $key => $value) {
249 if (strtolower($key) == "http-response")
251 $s .= sprintf("%s: %s\r\n", $key, $value);
254 $s .= sprintf("Content-Length: %ld\r\n", $len);
258 $s = "HTTP/1.1 200 OK\r\n";
260 if (!isset($header['Date']))
261 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
262 if (!isset($header['Connection']))
263 $s .= "Connection: close\r\n";
264 if (!isset($header['Content-Type']))
265 $s .= "Content-Type: text/html\r\n";
266 foreach($header as $key => $value) {
267 $s .= sprintf("%s: %s\r\n", $key, $value);
270 $s .= sprintf("Content-Length: %d\r\n", $len);
273 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
274 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
275 if (!isset($header['Content-Encoding'])) {
276 $s .= "Content-Encoding: chunked\r\n";
278 $s .= "Transfer-Encoding: chunked\r\n";
288 * Caching system using ob php system to cache old style pages
289 * to a var and than send it with more calm
294 log_rd2("SHUTTA [".connection_status()."] !");
297 register_shutdown_function('shutta');
303 function get_encoding($header)
306 if (isset($header['Accept-Encoding'])) {
307 $acc = explode(',', $header['Accept-Encoding']);
309 if (array_search('gzip', $acc) !== FALSE) {
312 else if (array_search('deflate', $acc) !== FALSE) {
322 // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
323 // string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
326 $this->attr = array();
329 static function create($name)
331 $thiz = new Cookie();
333 $thiz->attr[$name] = "";
335 $argc = func_num_args();
336 for ($i = 1 ; $i < $argc ; $i++) {
337 $arg = func_get_arg($i);
340 $thiz->attr[$name] = urlencode($arg);
343 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
346 $thiz->attr['Path'] = $arg;
349 $thiz->attr['Domain'] = $arg;
353 $thiz->attr['Secure'] = NULL;
358 $thiz->attr['HttpOnly'] = NULL;
374 foreach ($this->attr as $k => $v) {
376 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
379 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
394 $this->cookies = array();
399 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
402 array_push($this->cookies, $cookie);
410 foreach ($this->cookies as $cookie) {
411 $r .= $cookie->render();
420 // maybe fixed_fd is unuseful
421 static $fixed_fd = 3;
422 static $cnt_master = NULL;
423 static $cnt_slave = NULL;
425 var $provider_proxy; // list of provider/browser that offer proxy service
429 var $direct_socket; // socket where read direct commands
431 var $s2u; // user associated with input socket
432 var $s2p; // pending page associated with input socket
450 function Sac_a_push()
454 function sig_handler($sig)
461 if (static::$cnt_master != NULL) {
462 fwrite(static::$cnt_master, "\nshutdown\n");
463 fflush(static::$cnt_master);
470 if (static::$cnt_master != NULL) {
471 fwrite(static::$cnt_master, "\nreload\n");
472 fflush(static::$cnt_master);
478 static function create(&$app, $sockname, $debug, $blocking_mode, $provider_proxy, $argv)
480 $thiz = new Sac_a_push();
484 $thiz->provider_proxy = ProviderProxy::create();
486 $thiz->file_socket = $sockname;
487 $thiz->unix_socket = "unix://$sockname";
488 $thiz->direct_socket = "unix://${sockname}2";
489 $thiz->debug = $debug;
490 $thiz->socks = array();
491 $thiz->s2u = array();
492 $thiz->s2p = array();
493 $thiz->pending_pages = array();
494 $thiz->is_daemon = FALSE;
496 if (array_search("-d", $argv) !== FALSE || array_search("--daemon", $argv) !== FALSE) {
497 $thiz->is_daemon = TRUE;
500 // create a couple of sockets for control management
501 if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
502 STREAM_IPPROTO_IP)) == FALSE) {
505 static::$cnt_master = $sockpair[0];
506 static::$cnt_slave = $sockpair[1];
508 pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
509 pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
510 pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
512 $thiz->blocking_mode = 0; // 0 for non-blocking
515 for ($i = 0 ; $i < 4096 ; $i++) {
517 $thiz->rndstr .= " ";
519 $thiz->rndstr .= chr(mt_rand(65, 90));
522 if (file_exists($thiz->file_socket)) {
523 unlink($thiz->file_socket);
525 if (file_exists($thiz->file_socket."2")) {
526 unlink($thiz->file_socket."2");
529 $old_umask = umask(0);
530 if (($thiz->list_web = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
533 if (($thiz->list_cmd = stream_socket_server($thiz->direct_socket, $err, $errs)) === FALSE) {
537 stream_set_blocking($thiz->list_web, $thiz->blocking_mode); # Set the stream to non-blocking
538 stream_set_blocking($thiz->list_cmd, $thiz->blocking_mode); # Set the stream to non-blocking
540 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
544 $thiz->main_loop = FALSE;
545 $thiz->reload(TRUE, $provider_proxy);
550 function socks_set($sock, $user, $pendpage)
554 $this->socks[$id] = $sock;
556 $this->s2u[$id] = $user;
557 if ($pendpage != NULL)
558 $this->s2p[$id] = $pendpage;
561 function socks_unset($sock)
565 if (isset($this->s2u[$id]))
566 unset($this->s2u[$id]);
567 if (isset($this->s2p[$id]))
568 unset($this->s2p[$id]);
569 unset($this->socks[$id]);
572 function pendpage_try_addcont(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
574 $pendpage = PendingPage::pendingpage_continue( $new_socket, $this->curtime, $tout, $method,
575 $header, $get, $post, $cookie,
576 $path, $addr, $rest, $cont);
578 $pendpage->try_flush($this->curtime);
579 // Add $pendpage to the pendpage array (in any case)
580 fprintf(STDERR, "IMPORTANT: Pendadd: %d\n", $pendpage->status);
581 $this->pendpage_add($pendpage);
584 function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
586 $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
588 if ($pendpage->try_flush($this->curtime) == FALSE) {
589 // Add $pendpage to the pendpage array
590 $this->pendpage_add($pendpage);
594 function pendpage_add($pendpage)
596 array_push($this->pending_pages, $pendpage);
597 $this->socks_set($pendpage->socket_get(), NULL, $pendpage);
600 function pendpage_rem($pendpage)
602 $sock = $pendpage->socket_get();
603 if (($key = array_search($pendpage, $this->pending_pages)) !== FALSE) {
604 unset($this->pending_pages[$key]);
607 fprintf(STDERR, "WARNING: pendpage not found\n");
609 $this->socks_unset($sock);
610 fprintf(STDERR, "PP_REM: %d\n", intval($sock));
614 function pendpage_try_addwait(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
616 $pendpage = PendingPage::pendingpage_waiting($new_socket, $this->curtime, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont);
618 if ($pendpage->try_flush($this->curtime) == FALSE) {
619 // Add $pendpage to the pendpage array
621 $this->pendpage_add($pendpage);
627 function garbage_manager($force)
629 $this->app->garbage_manager($force);
631 foreach ($this->socks as $k => $sock) {
633 if (isset($this->s2u[$id])) {
634 $user = $this->s2u[$id];
635 if ($user->the_end) {
636 if (($user->rd_toflush == FALSE && $user->rd_step == $user->step)
637 || $user->rd_endtime_is_expired($this->curtime)) {
638 if ($user->rd_socket_get() != NULL) {
639 $user->rd_socket_set(NULL);
641 unset($this->socks[$id]);
642 unset($this->s2u[$id]);
644 printf("CLOSE ON GARBAGE MANAGER\n");
649 $this->app->users_cleanup();
652 function check_globals()
654 GLOBAL $_globals_list;
655 foreach ($_globals_list as $g) {
656 if (!array_search($g, $GLOBALS) || !isset($GLOBALS[$g])) {
657 error_log(sprintf("Global [%s] not declared", $g));
666 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
668 GLOBAL $G_alarm_passwd, $G_ban_list, $G_black_list, $G_cloud_smasher, $G_provider_proxy;
669 GLOBAL $G_btrace_pref_sub, $G_dbauth;
670 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
671 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
672 GLOBAL $G_room_roadmap, $G_shutdown;
673 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
674 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
675 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
676 GLOBAL $G_with_splash, $G_sidebanner, $G_sidebanner_idx;
677 GLOBAL $G_with_topbanner;
678 GLOBAL $G_tos_vers, $G_tos_fname, $G_tos_dtsoft, $G_tos_dthard, $G_tos_idx, $G_doc_path;
680 if (!$this->check_globals()) {
681 fprintf(STDERR, "Take a look to the phplog file, GLOBALS missing!\n");
685 if ($this->main_loop) {
689 $this->main_loop = TRUE;
691 while ($this->main_loop) {
692 $this->app->sess_cur_set(FALSE);
693 $this->curtime = time();
694 fprintf(STDERR, "IN LOOP: Current opened: %d pending_pages: %d\n", count($this->socks), count($this->pending_pages));
696 /* Prepare the read array */
697 /* // when we manage it ... */
699 /* $read = array_merge(array("$in" => $in), $socks); */
701 $pre_read = array_merge(array(intval($this->list_web) => $this->list_web,
702 intval($this->list_cmd) => $this->list_cmd,
703 intval(static::$cnt_slave) => static::$cnt_slave),
705 if ($this->is_daemon == FALSE) {
706 $read = array_merge($pre_read, array(intval($this->in) => $this->in));
712 if ($this->debug > 1) {
713 printf("PRE_SELECT\n");
718 $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
720 if ($num_changed_sockets == 0) {
721 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
723 else if ($num_changed_sockets > 0) {
724 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
725 if ($this->debug > 1) {
728 /* At least at one of the sockets something interesting happened */
729 foreach ($read as $i => $sock) {
731 $manage_page = FALSE;
732 /* is_resource check is required because there is the possibility that
733 during new request an old connection is closed */
734 if (!is_resource($sock)) {
737 if ($sock === $this->list_web) {
738 printf("NUOVA CONNEX\n");
739 if (($new_unix = stream_socket_accept($this->list_web)) == FALSE) {
740 printf("SOCKET_ACCEPT FAILED\n");
750 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
751 printf("NEW_SOCKET: %d\n", intval($new_socket));
752 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
753 // error_log(sprintf("RECEIVED HEADER:\n%s", $stream_info));
754 if (($path = spu_process_info($stream_info, $method, $header,
755 $get, $post, $cookie, $rest, $cont))
757 fprintf(STDERR, "TODO: fix wrong header management\n");
760 // We try to get real IP from header (passed by proxy) and then fallback to direct connection IP
761 // error_log(sprintf("addr: [%s]", $addr));
762 // error_log(sprintf("X-Real-Ip: [%s]", array_key_exists('X-Real-Ip', $header) ? $header['X-Real-Ip'] : "Not exists"));
763 if (array_key_exists('X-Real-Ip', $header)) {
764 $addr = $header['X-Real-Ip'];
767 $addr = addrtoipv4(stream_socket_get_name($new_socket, TRUE));
770 // FOR TEST $header['X-Forwarded-For'] = '154.155.22.33';
771 $addr = $this->pproxy_realip($header, $addr);
773 printf("PATH: [%s] [%s]\n", $path, print_r($header, TRUE));
774 if ($method == "POST" && $rest > 0) {
775 if (isset($header['Expect']) && $header['Expect'] == '100-continue') {
776 fprintf(STDERR, "\nPOSTA DE CHE\n\n");
777 $this->pendpage_try_addcont($new_socket, 20,
778 $method, $header, $get, $post, $cookie,
779 $path, $addr, $rest, $cont);
782 $this->pendpage_try_addwait($new_socket, 20,
783 $method, $header, $get, $post, $cookie,
784 $path, $addr, $rest, $cont);
791 printf("number of sockets after %d\n", count($this->socks));
794 printf("WARNING: ancillary_getstream failed\n");
797 else if ($sock === $this->list_cmd) {
798 printf("NUOVA DIRECT CONNEX\n");
799 if (($new_unix = stream_socket_accept($this->list_cmd)) == FALSE) {
800 printf("SOCKET_ACCEPT FAILED\n");
803 stream_set_blocking($new_unix, $this->blocking_mode);
804 $this->direct_mgmt($new_unix);
805 } // not socket_list nor socket_list_cmd
806 else { // already opened socket
807 $buf = fread($sock, 4096);
808 // if socket is closed
809 if ($buf == FALSE || feof($sock)) {
812 printf("INFO: read return false\n");
814 if ($sock === $this->list_web) {
815 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
818 else if ($sock === $this->list_cmd) {
819 printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
822 else if ($sock === $this->in || $sock === static::$cnt_slave) {
823 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
827 unset($this->socks[$id]);
828 if (isset($this->s2u[$id])) {
829 // $user_a[$s2u[$id]]->disable();
830 if ($this->s2u[$id]->rd_socket_get() != NULL) {
831 // try to send close frame (for websocket)
832 $clo = $this->s2u[$id]->stream_close();
833 $clo_l = mb_strlen($clo, "ASCII");
834 @fwrite($sock, $clo, $clo_l);
835 $this->s2u[$id]->rd_socket_set(NULL);
837 unset($this->s2u[$id]);
841 printf("CLOSE ON READ\n");
843 if ($this->debug > 1) {
844 printf("post unset\n");
845 print_r($this->socks);
847 } // if ($buf == FALSE || mb_strlen($buf, "ASCII") == 0) {
848 else { // data on the socket
849 if ($this->debug > 1) {
852 if ($sock === $this->list_web) {
853 printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
855 else if ($sock === $this->list_cmd) {
856 printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
858 else if ($sock === $this->in || $sock === static::$cnt_slave) {
859 printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
861 if ($line == "reload") {
862 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
863 $this->reload(FALSE, $G_provider_proxy);
864 $this->app->reload(FALSE, $G_ban_list, $G_black_list,
866 if (!$this->check_globals()) {
867 fprintf(STDERR, "Take a look to the phplog file, GLOBALS missing!\n");
872 else if ($line == "shutdown" || $line == "sd") {
873 if ($this->app->dump_data()) {
881 else { // data arrived from not special socket
882 $key = array_search("$sock", $this->socks);
883 fprintf(STDERR, "Arrivati %d bytes dalla socket n. %d\n", mb_strlen($buf, "ASCII"), $key);
884 if (isset($this->s2p[$id])) {
885 $this->s2p[$id]->rest -= mb_strlen($buf, "ASCII");
886 $this->s2p[$id]->cont .= $buf;
887 if ($this->s2p[$id]->rest <= 0) {
888 $header = $new_socket = $path = $addr = $get = $cookie = 0;
891 $this->s2p[$id]->context_get($header, $new_socket, $path, $addr, $get, $post, $cookie);
892 $this->pendpage_rem($this->s2p[$id]);
893 fprintf(STDERR, "SOCKET RUN: %s\n", $new_socket);
902 if ($manage_page == TRUE) {
903 printf("M: %s\nHEADER:\n", $method);
912 $header_out = array();
913 // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
915 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
916 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
918 if ($rret == FALSE) {
919 // FIXME: manage 404 !!!
920 printf("TODO: fix unknown page\n");
927 $this->garbage_manager(FALSE);
929 /* manage unfinished pages */
930 foreach ($this->pending_pages as $k => $pendpage) {
931 // TODO: try_flush if exists in the class
932 if ($pendpage->try_flush($this->curtime) == TRUE) {
933 unset($this->pending_pages[$k]);
938 $response: raw stream data not sent
939 $content: html consistent data (<script bla bla>)
940 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
943 /* manage open streaming */
944 foreach ($this->socks as $k => $sock) {
946 if (isset($this->s2u[$id])) {
947 $user = $this->s2u[$id];
949 if ($user->rd_toflush) {
950 if (fflush($sock) == FALSE)
953 $user->rd_toflush = FALSE;
955 $response = $user->rd_cache_get();
957 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
961 $user->ping_req = FALSE;
964 if ($response == "") {
966 $user->stream_main($content, $get, $post, $cookie);
967 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
968 if ($do_ping && $user->ping_req == FALSE) {
969 $content .= $user->stream_keepalive(TRUE);
970 $user->ping_req = TRUE;
972 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
973 $content = $user->stream_keepalive(FALSE);
975 if ($content != "") {
976 $response = $user->chunked_content($content);
980 if ($response != "") {
981 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
982 // echo "SPIA: [".$response."]\n";
983 $response_l = mb_strlen($response, "ASCII");
984 $wret = @fwrite($sock, $response, $response_l);
985 if ($wret < $response_l) {
986 printf("TROUBLE WITH FWRITE: %d\n", $wret);
987 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
990 $user->rd_cache_set("");
992 if (fflush($sock) == FALSE) {
993 $user->rd_toflush = TRUE;
996 $user->rd_kalive_reset($this->curtime);
999 // close socket after a while to prevent client memory consumption
1000 if ($user->rd_endtime_is_expired($this->curtime)) {
1001 if ($this->s2u[$id]->rd_socket_get() != NULL) {
1002 $this->s2u[$id]->rd_socket_set(NULL);
1004 unset($this->socks[$id]);
1005 unset($this->s2u[$id]);
1006 $clo = $user->stream_close();
1007 $clo_l = mb_strlen($clo, "ASCII");
1008 @fwrite($sock, $clo, $clo_l);
1010 printf("CLOSE ON LOOP\n");
1012 } // if (isset($this->s2u[$id]...
1013 } // foreach ($this->socks...
1015 if (defined('CURL_DE_SAC_VERS')) {
1016 $this->app->cds->process();
1019 } // function run(...
1021 function pproxy_realip(&$header, $ip_str)
1023 return ($this->provider_proxy->realip($header, $ip_str));
1026 function reload($is_first, $prov_proxy)
1028 fprintf(STDERR, "SAP RELOAD STUFF (%d)\n", count($prov_proxy));
1030 $this->provider_proxy->update($prov_proxy);
1033 function direct_command($cmdstr)
1035 GLOBAL $G_alarm_passwd;
1037 $cmd = cmd_deserialize($cmdstr);
1039 if (!isset($cmd['cmd'])) {
1040 return cmd_return(500, 'no cmd found');
1042 // "cmd" => "userauth", "sess" => 'xxxxxxxxxxx', 'private' => 'it_must_be_correct',
1043 // 'the_end' => 'true' );
1044 // cmd=userauth&sess=52d796ac08c47&private=yourpasswd192.168.122.152d796ac08c47&the_end=true
1045 if ($cmd['cmd'] == 'userauth') {
1046 if (!isset($cmd['sess']) || !isset($cmd['private'])) {
1047 return cmd_return(401, 'malformed cmd');
1050 if (($user = $this->app->get_user($cmd['sess'], $idx)) == FALSE)
1051 return cmd_return(402, 'user not found');
1053 if (($user->flags & USER_FLAG_TY_ADMIN) == 0x00)
1054 return cmd_return(403, 'permission denied');
1056 if (md5($G_alarm_passwd.$user->ip.$user->sess) != $cmd['private'])
1057 return cmd_return(404, 'authentication failed ['.$cmd['private'].']['.$G_alarm_passwd.$user->ip.$user->sess.']');
1059 return cmd_return(200, 'success');
1062 return cmd_return(501, 'no cmd found');
1065 function direct_mgmt($socket)
1067 printf("DIRECT: begin\n");
1068 $st = DIRECT_ST_READ;
1070 $endtime = $this->curtime + 3;
1072 while(time() <= $endtime) {
1073 printf("DIRECT: init loop %d\n", $st);
1074 if ($st == DIRECT_ST_READ) {
1075 $buf = fread($socket, 4096);
1076 if ($buf == FALSE && feof($socket)) {
1079 else if ($buf != FALSE && strlen($buf) > 0) {
1082 if (substr(trim($cmd_all), -13) == "&the_end=true") {
1083 $output_arr = $this->direct_command($cmd_all);
1084 $output = cmd_serialize($output_arr);
1086 $output_len = mb_strlen($output, "ASCII");
1087 $st = DIRECT_ST_WRITE;
1092 else if ($st == DIRECT_ST_WRITE) {
1093 $ret = fwrite($socket, $output, $output_len);
1094 if ($ret === FALSE) {
1095 if (feof($socket)) {
1099 else if ($ret > 0 && $ret < $output_len) {
1100 $output = substr($output, -($output_len - $ret));
1101 $output_len -= $ret;
1104 else if ($ret == $output_len) {
1115 } // class Sac_a_push