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 $conttype_all = explode(";", $header['Content-Type']);
136 $header['Content-Type'] = $conttype_all[0];
137 // $path_all[1-] other things like charset and so on
139 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
140 || !isset($header['Content-Length'])) {
143 $post_len = mb_strlen($line, "ASCII");
144 $a = explode('&', $line);
145 for ($i = 0 ; $i < count($a) ; $i++) {
146 $b = explode('=', $a[$i]);
147 $post[$b[0]] = urldecode($b[1]);
149 printf("INFO: postlen: %d\n", $post_len);
157 $split = explode(":", $line, 2);
158 $header[$split[0]] = $split[1];
163 function gpcs_var($name, $get, $post, $cookie)
165 if (isset($GLOBALS[$name]))
167 else if (isset($cookie[$name]))
168 return ($cookie[$name]);
169 else if (isset($post[$name]))
170 return ($post[$name]);
171 else if (isset($get[$name]))
172 return ($get[$name]);
177 function headers_render($header, $len)
181 if (isset($header['cookies'])) {
182 $cookies = $header['cookies']->render();
183 unset($header['cookies']);
185 if (isset($header['Location'])) {
186 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
189 $s = "HTTP/1.1 200 OK\r\n";
191 if (!isset($header['Date']))
192 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
193 if (!isset($header['Connection']))
194 $s .= "Connection: close\r\n";
195 if (!isset($header['Content-Type']))
196 $s .= "Content-Type: text/html\r\n";
197 foreach($header as $key => $value) {
198 $s .= sprintf("%s: %s\r\n", $key, $value);
201 $s .= sprintf("Content-Length: %d\r\n", $len);
204 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
205 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
206 if (!isset($header['Content-Encoding'])) {
207 $s .= "Content-Encoding: chunked\r\n";
209 $s .= "Transfer-Encoding: chunked\r\n";
219 * Caching system using ob php system to cache old style pages
220 * to a var and than send it with more calm
225 log_rd2("SHUTTA [".connection_status()."] !");
228 register_shutdown_function('shutta');
234 function chunked_content($zls, $content)
237 $cont_comp = $zls->compress_chunk($content);
240 $cont_comp = $content;
242 $cont_comp_l = mb_strlen($cont_comp, "ASCII");
243 printf("CHUNK: [%s]\n", $content);
245 return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
248 function chunked_fini()
250 return sprintf("0\r\n");
253 function get_encoding($header)
256 if (isset($header['Accept-Encoding'])) {
257 $acc = explode(',', $header['Accept-Encoding']);
259 if (array_search('gzip', $acc) !== FALSE) {
262 else if (array_search('deflate', $acc) !== FALSE) {
272 // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
273 // string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
276 $this->attr = array();
279 static function create($name)
281 $thiz = new Cookie();
283 $thiz->attr[$name] = "";
285 $argc = func_num_args();
286 for ($i = 1 ; $i < $argc ; $i++) {
287 $arg = func_get_arg($i);
290 $thiz->attr[$name] = urlencode($arg);
293 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
296 $thiz->attr['Path'] = $arg;
299 $thiz->attr['Domain'] = $arg;
303 $thiz->attr['Secure'] = NULL;
308 $thiz->attr['HttpOnly'] = NULL;
324 foreach ($this->attr as $k => $v) {
326 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
329 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
344 $this->cookies = array();
349 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
352 array_push($this->cookies, $cookie);
360 foreach ($this->cookies as $cookie) {
361 $r .= $cookie->render();
370 // maybe fixed_fd is unuseful
371 static $fixed_fd = 3;
372 static $cnt_master = NULL;
373 static $cnt_slave = NULL;
394 function Sac_a_push()
398 function sig_handler($sig)
405 if (static::$cnt_master != NULL) {
406 fwrite(static::$cnt_master, "\nshutdown\n");
407 fflush(static::$cnt_master);
414 if (static::$cnt_master != NULL) {
415 fwrite(static::$cnt_master, "\nreload\n");
416 fflush(static::$cnt_master);
422 static function create(&$app, $sockname, $debug, $blocking_mode)
424 $thiz = new Sac_a_push();
427 $thiz->file_socket = $sockname;
428 $thiz->unix_socket = "unix://$sockname";
429 $thiz->debug = $debug;
430 $thiz->socks = array();
431 $thiz->s2u = array();
432 $thiz->pending_pages = array();
434 // create a couple of sockets for control management
435 if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
436 STREAM_IPPROTO_IP)) == FALSE) {
439 static::$cnt_master = $sockpair[0];
440 static::$cnt_slave = $sockpair[1];
442 pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
443 pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
444 pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
446 $thiz->blocking_mode = 0; // 0 for non-blocking
449 for ($i = 0 ; $i < 4096 ; $i++) {
451 $thiz->rndstr .= " ";
453 $thiz->rndstr .= chr(mt_rand(65, 90));
456 if (file_exists($thiz->file_socket)) {
457 unlink($thiz->file_socket);
460 $old_umask = umask(0);
461 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
465 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
467 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
471 $thiz->main_loop = FALSE;
476 function socks_set($sock, $user)
480 $this->s2u[$id] = $user;
481 $this->socks[$id] = $sock;
484 function socks_unset($sock)
488 unset($this->s2u[$id]);
489 unset($this->socks[$id]);
492 function pendpage_try_addflush($enc, &$new_socket, $tout, $header_out, $content)
494 $pgflush = PendingPage::pendingpage_flushing($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
496 if ($pgflush->try_flush($this->curtime) == FALSE) {
497 // Add $pgflush to the pgflush array
498 $this->pgflush_add($pgflush);
502 function pgflush_add($pgflush)
504 array_push($this->pending_pages, $pgflush);
507 function garbage_manager($force)
509 $this->app->garbage_manager($force);
511 foreach ($this->socks as $k => $sock) {
512 if ($this->s2u[intval($sock)]->sess == '') {
513 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
514 $this->s2u[intval($sock)]->rd_socket_set(NULL);
516 unset($this->socks[intval($sock)]);
517 unset($this->s2u[intval($sock)]);
519 printf("CLOSE ON GARBAGE MANAGER\n");
526 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
528 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
529 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
530 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
531 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
532 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
533 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
534 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
535 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
536 GLOBAL $G_with_topbanner;
538 if ($this->main_loop) {
542 $this->main_loop = TRUE;
544 while ($this->main_loop) {
545 $this->curtime = time();
546 printf("IN LOOP: Current opened: %d pending_pages: %d - ", count($this->socks), count($this->pending_pages));
548 /* Prepare the read array */
549 /* // when we manage it ... */
551 /* $read = array_merge(array("$in" => $in), $socks); */
553 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in,
554 intval(static::$cnt_slave) => static::$cnt_slave),
557 if ($this->debug > 1) {
558 printf("PRE_SELECT\n");
563 $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
565 if ($num_changed_sockets == 0) {
566 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
568 else if ($num_changed_sockets > 0) {
569 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
570 if ($this->debug > 1) {
573 /* At least at one of the sockets something interesting happened */
574 foreach ($read as $i => $sock) {
575 /* is_resource check is required because there is the possibility that
576 during new request an old connection is closed */
577 if (!is_resource($sock)) {
580 if ($sock === $this->list) {
581 printf("NUOVA CONNEX\n");
582 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
583 printf("SOCKET_ACCEPT FAILED\n");
591 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
592 printf("NEW_SOCKET: %d\n", intval($new_socket));
593 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
594 printf("RECEIVED HEADER:\n%s", $stream_info);
595 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
596 $addr = stream_socket_get_name($new_socket, TRUE);
597 printf("PATH: [%s]\n", $path);
598 printf("M: %s\nHEADER:\n", $method);
599 if ($method == "POST") {
600 // ADD PUSH INTO FD ARRAY AS WAITING DATA
601 // Passing all infos from spu_process_info as arguments:
603 // MAYBE: $stream_info,
604 // $method, $header, $get, $post, $cookie
605 // $s_a_p (this), $new_socket, substr($path, SITE_PREFIX_LEN),
615 $header_out = array();
617 // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
619 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
620 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
622 if ($rret == FALSE) {
623 // FIXME: manage 404 !!!
624 printf("TODO: fix unknown page\n");
626 printf("number of sockets after %d\n", count($this->socks));
629 printf("WARNING: ancillary_getstream failed\n");
633 $buf = fread($sock, 512);
634 // if socket is closed
635 if ($buf == FALSE || strlen($buf) == 0) {
638 printf("ERROR READING\n");
640 if ($sock === $this->list) {
641 printf("Arrivati %d bytes da list\n", strlen($buf));
644 else if ($sock === $this->in || $sock === static::$cnt_slave) {
645 printf("Arrivati %d bytes da stdin\n", strlen($buf));
649 // $user_a[$s2u[intval($sock)]]->disable();
650 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
651 $this->s2u[intval($sock)]->rd_socket_set(NULL);
653 unset($this->socks[intval($sock)]);
654 unset($this->s2u[intval($sock)]);
657 printf("CLOSE ON READ\n");
659 if ($this->debug > 1) {
660 printf("post unset\n");
661 print_r($this->socks);
665 if ($this->debug > 1) {
668 if ($sock === $this->list) {
669 printf("Arrivati %d bytes da list\n", strlen($buf));
671 else if ($sock === $this->in || $sock === static::$cnt_slave) {
672 printf("Arrivati %d bytes da stdin\n", strlen($buf));
674 if ($line == "reload") {
675 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
679 else if ($line == "shutdown") {
680 if ($this->app->dump_data()) {
689 $key = array_search("$sock", $this->socks);
690 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
694 // TODO: MOVE HERE request_mgr to factorize new_sockets and POST closed
695 // $rret = $this->app->request_mgr
699 $this->garbage_manager(FALSE);
701 /* manage unfinished pages */
702 foreach ($this->pending_pages as $k => $pgflush) {
703 // TODO: try_flush if exists in the class
704 if ($pgflush->try_flush($this->curtime) == TRUE) {
705 unset($this->pending_pages[$k]);
710 $response: raw stream data not sent
711 $content: html consistent data (<script bla bla>)
712 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
715 /* manage open streaming */
716 foreach ($this->socks as $k => $sock) {
717 if (isset($this->s2u[intval($sock)])) {
718 $user = $this->s2u[intval($sock)];
719 $response = $user->rd_cache_get();
721 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
725 $user->ping_req = FALSE;
728 if ($response == "") {
730 $user->stream_main($content, $get, $post, $cookie);
731 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
732 if ($do_ping && $user->ping_req == FALSE) {
733 $content .= $user->stream_keepalive(TRUE);
734 $user->ping_req = TRUE;
736 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
737 $content = $user->stream_keepalive(FALSE);
739 if ($content != "") {
740 $response = chunked_content($user->rd_zls_get(), $content);
744 if ($response != "") {
745 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
746 echo "SPIA: [".$response."]\n";
747 $response_l = mb_strlen($response, "ASCII");
748 $wret = @fwrite($sock, $response);
749 if ($wret < $response_l) {
750 printf("TROUBLE WITH FWRITE: %d\n", $wret);
751 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
754 $user->rd_cache_set("");
757 $user->rd_kalive_reset($this->curtime);
760 // close socket after a while to prevent client memory consumption
761 if ($user->rd_endtime_is_expired($this->curtime)) {
762 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
763 $this->s2u[intval($sock)]->rd_socket_set(NULL);
765 unset($this->socks[intval($sock)]);
766 unset($this->s2u[intval($sock)]);
768 printf("CLOSE ON LOOP\n");
771 } // foreach ($this->socks...
774 } // function run(...