3 * brisk - Obj/sac-a-push.phh
5 * Copyright (C) 2012 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);
30 function global_dump()
32 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
33 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
34 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
35 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
36 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
37 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
38 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
39 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
40 GLOBAL $G_with_topbanner;
42 fprintf(STDERR, "G_alarm_passwd = [%s]\n", print_r($G_alarm_passwd, TRUE));
43 fprintf(STDERR, "G_black_list = [%s]\n", print_r($G_black_list, TRUE));
44 fprintf(STDERR, "G_btrace_pref_sub = [%s]\n", print_r($G_btrace_pref_sub, TRUE));
45 fprintf(STDERR, "G_dbauth = [%s]\n", print_r($G_dbauth, TRUE));
46 fprintf(STDERR, "G_dbpfx = [%s]\n", print_r($G_dbpfx, TRUE));
47 fprintf(STDERR, "G_donors_all = [%s]\n", print_r($G_donors_all, TRUE));
48 fprintf(STDERR, "G_donors_cur = [%s]\n", print_r($G_donors_cur, TRUE));
49 fprintf(STDERR, "G_is_local = [%s]\n", print_r($G_is_local, TRUE));
50 fprintf(STDERR, "G_lang = [%s]\n", print_r($G_lang, TRUE));
51 fprintf(STDERR, "G_poll_entries = [%s]\n", print_r($G_poll_entries, TRUE));
52 fprintf(STDERR, "G_poll_name = [%s]\n", print_r($G_poll_name, TRUE));
53 fprintf(STDERR, "G_poll_title = [%s]\n", print_r($G_poll_title, TRUE));
54 fprintf(STDERR, "G_proxy_white_list = [%s]\n", print_r($G_proxy_white_list, TRUE));
55 fprintf(STDERR, "G_room_roadmap = [%s]\n", print_r($G_room_roadmap, TRUE));
56 fprintf(STDERR, "G_shutdown = [%s]\n", print_r($G_shutdown, TRUE));
57 fprintf(STDERR, "G_sidebanner = [%s]\n", print_r($G_sidebanner, TRUE));
58 fprintf(STDERR, "G_sidebanner2 = [%s]\n", print_r($G_sidebanner2, TRUE));
59 fprintf(STDERR, "G_splash_content = [%s]\n", print_r($G_splash_content, TRUE));
60 fprintf(STDERR, "G_splash_contents = [%s]\n", print_r($G_splash_contents, TRUE));
61 fprintf(STDERR, "G_splash_cont_idx = [%s]\n", print_r($G_splash_cont_idx, TRUE));
62 fprintf(STDERR, "G_splash_h = [%s]\n", print_r($G_splash_h, TRUE));
63 fprintf(STDERR, "G_splash_idx = [%s]\n", print_r($G_splash_idx, TRUE));
64 fprintf(STDERR, "G_splash_interval = [%s]\n", print_r($G_splash_interval, TRUE));
65 fprintf(STDERR, "G_splash_timeout = [%s]\n", print_r($G_splash_timeout, TRUE));
66 fprintf(STDERR, "G_splash_w = [%s]\n", print_r($G_splash_w, TRUE));
67 fprintf(STDERR, "G_topbanner = [%s]\n", print_r($G_topbanner, TRUE));
68 fprintf(STDERR, "G_with_donors = [%s]\n", print_r($G_with_donors, TRUE));
69 fprintf(STDERR, "G_with_poll = [%s]\n", print_r($G_with_poll, TRUE));
70 fprintf(STDERR, "G_with_sidebanner = [%s]\n", print_r($G_with_sidebanner, TRUE));
71 fprintf(STDERR, "G_with_sidebanner2 = [%s]\n", print_r($G_with_sidebanner2, TRUE));
72 fprintf(STDERR, "G_with_splash = [%s]\n", print_r($G_with_splash, TRUE));
73 fprintf(STDERR, "G_with_topbanner = [%s]\n", print_r($G_with_topbanner, TRUE));
79 $fname = LEGAL_PATH."/brisk.pid";
81 if (file_exists($fname)) {
82 log_crit("WARN: brisk.pid already exists");
84 file_put_contents($fname, sprintf("%d\n", $pid));
89 $fname = LEGAL_PATH."/brisk.pid";
91 if (file_exists($fname)) {
96 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
102 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
103 // printf("LINE: [%s]\n", $line);
105 if (!isset($header['The-Request'])) {
108 $req = explode(" ", $header['The-Request']);
111 if (isset($header['Cookie'])) {
112 $cookies = explode(";", $header['Cookie']);
113 for ($i = 0 ; $i < count($cookies) ; $i++) {
114 $nameval = explode("=", trim($cookies[$i]));
115 if (count($nameval) != 2) {
116 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
119 $cookie[$nameval[0]] = urldecode($nameval[1]);
122 // GET params management
123 $get_vars = explode('?', $req[1], 2);
124 $path = $get_vars[0];
125 if (count($get_vars) > 1) {
126 $a = explode('&', $get_vars[1]);
127 printf("A COUNT: [%s] %d\n", $a[0], count($a));
128 for ($i = 0 ; $i < count($a) ; $i++) {
129 $b = explode('=', $a[$i]);
130 $get[$b[0]] = urldecode($b[1]);
133 // POST params management
134 if ($req[0] == 'POST') {
135 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
136 || !isset($header['Content-Length'])) {
139 $post_len = mb_strlen($line, "latin1");
140 $a = explode('&', $line);
141 for ($i = 0 ; $i < count($a) ; $i++) {
142 $b = explode('=', $a[$i]);
143 $post[$b[0]] = urldecode($b[1]);
145 printf("INFO: postlen: %d\n", $post_len);
153 $split = explode(":", $line, 2);
154 $header[$split[0]] = $split[1];
159 function gpcs_var($name, $get, $post, $cookie)
161 if (isset($GLOBALS[$name]))
163 else if (isset($cookie[$name]))
164 return ($cookie[$name]);
165 else if (isset($post[$name]))
166 return ($post[$name]);
167 else if (isset($get[$name]))
168 return ($get[$name]);
173 function headers_render($header, $len)
177 if (isset($header['cookies'])) {
178 $cookies = $header['cookies']->render();
179 unset($header['cookies']);
181 if (isset($header['Location'])) {
182 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
185 $s = "HTTP/1.1 200 OK\r\n";
187 if (!isset($header['Date']))
188 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
189 if (!isset($header['Connection']))
190 $s .= "Connection: close\r\n";
191 if (!isset($header['Content-Type']))
192 $s .= "Content-Type: text/html\r\n";
193 foreach($header as $key => $value) {
194 $s .= sprintf("%s: %s\r\n", $key, $value);
197 $s .= sprintf("Content-Length: %d\r\n", $len);
200 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
201 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
202 if (!isset($header['Content-Encoding'])) {
203 $s .= "Content-Encoding: chunked\r\n";
205 $s .= "Transfer-Encoding: chunked\r\n";
215 * Caching system using ob php system to cache old style pages
216 * to a var and than send it with more calm
221 log_rd2("SHUTTA [".connection_status()."] !");
224 register_shutdown_function('shutta');
230 function chunked_content($zls, $content)
233 $cont_comp = $zls->compress_chunk($content);
236 $cont_comp = $content;
238 $cont_comp_l = mb_strlen($cont_comp, "ASCII");
239 printf("CHUNK: [%s]\n", $content);
241 return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
244 function chunked_fini()
246 return sprintf("0\r\n");
249 function get_encoding($header)
252 if (isset($header['Accept-Encoding'])) {
253 $acc = explode(',', $header['Accept-Encoding']);
255 if (array_search('gzip', $acc) !== FALSE) {
258 else if (array_search('deflate', $acc) !== FALSE) {
268 // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
269 // string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
272 $this->attr = array();
275 static function create($name)
277 $thiz = new Cookie();
279 $thiz->attr[$name] = "";
281 $argc = func_num_args();
282 for ($i = 1 ; $i < $argc ; $i++) {
283 $arg = func_get_arg($i);
286 $thiz->attr[$name] = urlencode($arg);
289 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
292 $thiz->attr['Path'] = $arg;
295 $thiz->attr['Domain'] = $arg;
299 $thiz->attr['Secure'] = NULL;
304 $thiz->attr['HttpOnly'] = NULL;
320 foreach ($this->attr as $k => $v) {
322 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
325 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
340 $this->cookies = array();
345 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
348 array_push($this->cookies, $cookie);
356 foreach ($this->cookies as $cookie) {
357 $r .= $cookie->render();
366 // maybe fixed_fd is unuseful
367 static $fixed_fd = 3;
368 static $cnt_master = NULL;
369 static $cnt_slave = NULL;
390 function Sac_a_push()
394 function sig_handler($sig)
401 if (static::$cnt_master != NULL) {
402 fwrite(static::$cnt_master, "\nshutdown\n");
403 fflush(static::$cnt_master);
410 if (static::$cnt_master != NULL) {
411 fwrite(static::$cnt_master, "\nreload\n");
412 fflush(static::$cnt_master);
418 static function create(&$app, $sockname, $debug, $blocking_mode)
420 $thiz = new Sac_a_push();
423 $thiz->file_socket = $sockname;
424 $thiz->unix_socket = "unix://$sockname";
425 $thiz->debug = $debug;
426 $thiz->socks = array();
427 $thiz->s2u = array();
428 $thiz->pages_flush = array();
430 // create a couple of sockets for control management
431 if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
432 STREAM_IPPROTO_IP)) == FALSE) {
435 static::$cnt_master = $sockpair[0];
436 static::$cnt_slave = $sockpair[1];
438 pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
439 pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
440 pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
442 $thiz->blocking_mode = 0; // 0 for non-blocking
445 for ($i = 0 ; $i < 4096 ; $i++) {
447 $thiz->rndstr .= " ";
449 $thiz->rndstr .= chr(mt_rand(65, 90));
452 if (file_exists($thiz->file_socket)) {
453 unlink($thiz->file_socket);
456 $old_umask = umask(0);
457 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
461 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
463 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
467 $thiz->main_loop = FALSE;
472 function socks_set($sock, $user)
476 $this->s2u[$id] = $user;
477 $this->socks[$id] = $sock;
480 function socks_unset($sock)
484 unset($this->s2u[$id]);
485 unset($this->socks[$id]);
488 function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
490 $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
492 if ($pgflush->try_flush($this->curtime) == FALSE) {
493 // Add $pgflush to the pgflush array
494 $this->pgflush_add($pgflush);
498 function pgflush_add($pgflush)
500 array_push($this->pages_flush, $pgflush);
503 function garbage_manager($force)
505 $this->app->garbage_manager($force);
507 foreach ($this->socks as $k => $sock) {
508 if ($this->s2u[intval($sock)]->sess == '') {
509 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
510 $this->s2u[intval($sock)]->rd_socket_set(NULL);
512 unset($this->socks[intval($sock)]);
513 unset($this->s2u[intval($sock)]);
515 printf("CLOSE ON GARBAGE MANAGER\n");
522 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
524 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
525 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
526 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
527 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
528 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
529 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
530 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
531 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
532 GLOBAL $G_with_topbanner;
534 if ($this->main_loop) {
538 $this->main_loop = TRUE;
540 while ($this->main_loop) {
541 $this->curtime = time();
542 printf("IN LOOP: Current opened: %d pages_flush: %d - ", count($this->socks), count($this->pages_flush));
544 /* Prepare the read array */
545 /* // when we manage it ... */
547 /* $read = array_merge(array("$in" => $in), $socks); */
549 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in,
550 intval(static::$cnt_slave) => static::$cnt_slave),
553 if ($this->debug > 1) {
554 printf("PRE_SELECT\n");
559 $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
561 if ($num_changed_sockets == 0) {
562 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
564 else if ($num_changed_sockets > 0) {
565 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
566 if ($this->debug > 1) {
569 /* At least at one of the sockets something interesting happened */
570 foreach ($read as $i => $sock) {
571 /* is_resource check is required because there is the possibility that
572 during new request an old connection is closed */
573 if (!is_resource($sock)) {
576 if ($sock === $this->list) {
577 printf("NUOVA CONNEX\n");
578 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
579 printf("SOCKET_ACCEPT FAILED\n");
587 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
588 printf("NEW_SOCKET: %d\n", intval($new_socket));
589 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
590 printf("RECEIVED HEADER:\n%s", $stream_info);
591 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
592 printf("PATH: [%s]\n", $path);
593 printf("M: %s\nHEADER:\n", $method);
601 $addr = stream_socket_get_name($new_socket, TRUE);
602 $header_out = array();
604 $subs = SITE_PREFIX."briskin5/";
605 $subs_l = strlen($subs);
607 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
608 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
610 if ($rret == FALSE) {
611 // FIXME: manage 404 !!!
612 printf("TODO: fix unknown page\n");
614 printf("number of sockets after %d\n", count($this->socks));
617 printf("WARNING: ancillary_getstream failed\n");
621 $buf = fread($sock, 512);
622 // if socket is closed
623 if ($buf == FALSE || strlen($buf) == 0) {
625 printf("ERROR READING\n");
627 if ($sock === $this->list) {
628 printf("Arrivati %d bytes da list\n", strlen($buf));
631 else if ($sock === $this->in || $sock === static::$cnt_slave) {
632 printf("Arrivati %d bytes da stdin\n", strlen($buf));
636 // $user_a[$s2u[intval($sock)]]->disable();
637 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
638 $this->s2u[intval($sock)]->rd_socket_set(NULL);
640 unset($this->socks[intval($sock)]);
641 unset($this->s2u[intval($sock)]);
644 printf("CLOSE ON READ\n");
646 if ($this->debug > 1) {
647 printf("post unset\n");
648 print_r($this->socks);
652 if ($this->debug > 1) {
655 if ($sock === $this->list) {
656 printf("Arrivati %d bytes da list\n", strlen($buf));
658 else if ($sock === $this->in || $sock === static::$cnt_slave) {
659 printf("Arrivati %d bytes da stdin\n", strlen($buf));
661 if ($line == "reload") {
662 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
666 else if ($line == "shutdown") {
667 if ($this->app->dump_data()) {
676 $key = array_search("$sock", $this->socks);
677 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
684 $this->garbage_manager(FALSE);
686 /* manage unfinished pages */
687 foreach ($this->pages_flush as $k => $pgflush) {
688 if ($pgflush->try_flush($this->curtime) == TRUE) {
689 unset($this->pages_flush[$k]);
694 $response: raw stream data not sent
695 $content: html consistent data (<script bla bla>)
696 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
699 /* manage open streaming */
700 foreach ($this->socks as $k => $sock) {
701 if (isset($this->s2u[intval($sock)])) {
702 $user = $this->s2u[intval($sock)];
703 $response = $user->rd_cache_get();
705 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
709 $user->ping_req = FALSE;
712 if ($response == "") {
714 $user->stream_main($content, $get, $post, $cookie);
715 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
716 if ($do_ping && $user->ping_req == FALSE) {
717 $content .= $user->stream_keepalive(TRUE);
718 $user->ping_req = TRUE;
720 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
721 $content = $user->stream_keepalive(FALSE);
723 if ($content != "") {
724 $response = chunked_content($user->rd_zls_get(), $content);
728 if ($response != "") {
729 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
730 echo "SPIA: [".$response."]\n";
731 $response_l = mb_strlen($response, "ASCII");
732 $wret = @fwrite($sock, $response);
733 if ($wret < $response_l) {
734 printf("TROUBLE WITH FWRITE: %d\n", $wret);
735 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
738 $user->rd_cache_set("");
741 $user->rd_kalive_reset($this->curtime);
744 // close socket after a while to prevent client memory consumption
745 if ($user->rd_endtime_is_expired($this->curtime)) {
746 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
747 $this->s2u[intval($sock)]->rd_socket_set(NULL);
749 unset($this->socks[intval($sock)]);
750 unset($this->s2u[intval($sock)]);
752 printf("CLOSE ON LOOP\n");
755 } // foreach ($this->socks...
758 } // function run(...