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;
378 var $s2u; // user associated with input socket
379 var $s2p; // pending page associated with input socket
395 function Sac_a_push()
399 function sig_handler($sig)
406 if (static::$cnt_master != NULL) {
407 fwrite(static::$cnt_master, "\nshutdown\n");
408 fflush(static::$cnt_master);
415 if (static::$cnt_master != NULL) {
416 fwrite(static::$cnt_master, "\nreload\n");
417 fflush(static::$cnt_master);
423 static function create(&$app, $sockname, $debug, $blocking_mode)
425 $thiz = new Sac_a_push();
428 $thiz->file_socket = $sockname;
429 $thiz->unix_socket = "unix://$sockname";
430 $thiz->debug = $debug;
431 $thiz->socks = array();
432 $thiz->s2u = array();
433 $thiz->s2p = array();
434 $thiz->pending_pages = array();
436 // create a couple of sockets for control management
437 if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
438 STREAM_IPPROTO_IP)) == FALSE) {
441 static::$cnt_master = $sockpair[0];
442 static::$cnt_slave = $sockpair[1];
444 pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
445 pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
446 pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
448 $thiz->blocking_mode = 0; // 0 for non-blocking
451 for ($i = 0 ; $i < 4096 ; $i++) {
453 $thiz->rndstr .= " ";
455 $thiz->rndstr .= chr(mt_rand(65, 90));
458 if (file_exists($thiz->file_socket)) {
459 unlink($thiz->file_socket);
462 $old_umask = umask(0);
463 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
467 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
469 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
473 $thiz->main_loop = FALSE;
478 function socks_set($sock, $user, $pendpage)
482 $this->socks[$id] = $sock;
484 $this->s2u[$id] = $user;
485 if ($pendpage != NULL)
486 $this->s2p[$id] = $pendpage;
489 function socks_unset($sock)
493 if (isset($this->s2u[$id]))
494 unset($this->s2u[$id]);
495 if (isset($this->s2p[$id]))
496 unset($this->s2p[$id]);
497 unset($this->socks[$id]);
500 function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
502 $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
504 if ($pendpage->try_flush($this->curtime) == FALSE) {
505 // Add $pendpage to the pendpage array
506 $this->pendpage_add($pendpage);
510 function pendpage_add($pendpage)
512 array_push($this->pending_pages, $pendpage);
515 function garbage_manager($force)
517 $this->app->garbage_manager($force);
519 foreach ($this->socks as $k => $sock) {
521 if (isset($this->s2u[$id])) {
522 if ($this->s2u[$id]->sess == '') {
523 if ($this->s2u[$id]->rd_socket_get() != NULL) {
524 $this->s2u[$id]->rd_socket_set(NULL);
526 unset($this->socks[$id]);
527 unset($this->s2u[$id]);
529 printf("CLOSE ON GARBAGE MANAGER\n");
537 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
539 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
540 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
541 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
542 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
543 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
544 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
545 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
546 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
547 GLOBAL $G_with_topbanner;
549 if ($this->main_loop) {
553 $this->main_loop = TRUE;
555 while ($this->main_loop) {
556 $this->curtime = time();
557 printf("IN LOOP: Current opened: %d pending_pages: %d - ", count($this->socks), count($this->pending_pages));
559 /* Prepare the read array */
560 /* // when we manage it ... */
562 /* $read = array_merge(array("$in" => $in), $socks); */
564 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in,
565 intval(static::$cnt_slave) => static::$cnt_slave),
568 if ($this->debug > 1) {
569 printf("PRE_SELECT\n");
574 $num_changed_sockets = @stream_select($read, $write, $except, 5, 500000);
576 if ($num_changed_sockets == 0) {
577 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
579 else if ($num_changed_sockets > 0) {
580 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
581 if ($this->debug > 1) {
584 /* At least at one of the sockets something interesting happened */
585 foreach ($read as $i => $sock) {
587 $manage_page = FALSE;
588 /* is_resource check is required because there is the possibility that
589 during new request an old connection is closed */
590 if (!is_resource($sock)) {
593 if ($sock === $this->list) {
594 printf("NUOVA CONNEX\n");
595 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
596 printf("SOCKET_ACCEPT FAILED\n");
604 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
605 printf("NEW_SOCKET: %d\n", intval($new_socket));
606 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
607 printf("RECEIVED HEADER:\n%s", $stream_info);
608 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
609 $addr = stream_socket_get_name($new_socket, TRUE);
610 printf("PATH: [%s]\n", $path);
611 printf("M: %s\nHEADER:\n", $method);
612 if ($method == "POST") {
613 // ADD PUSH INTO FD ARRAY AS WAITING DATA
614 // Passing all infos from spu_process_info as arguments:
616 // MAYBE: $stream_info,
617 // $method, $header, $get, $post, $cookie
618 // $s_a_p (this), $new_socket, substr($path, SITE_PREFIX_LEN),
631 $header_out = array();
633 // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
635 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
636 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
638 if ($rret == FALSE) {
639 // FIXME: manage 404 !!!
640 printf("TODO: fix unknown page\n");
642 printf("number of sockets after %d\n", count($this->socks));
645 printf("WARNING: ancillary_getstream failed\n");
649 $buf = fread($sock, 512);
650 // if socket is closed
651 if ($buf == FALSE || strlen($buf) == 0) {
654 printf("ERROR READING\n");
656 if ($sock === $this->list) {
657 printf("Arrivati %d bytes da list\n", strlen($buf));
660 else if ($sock === $this->in || $sock === static::$cnt_slave) {
661 printf("Arrivati %d bytes da stdin\n", strlen($buf));
665 unset($this->socks[$id]);
666 if (isset($this->s2u[$id])) {
667 // $user_a[$s2u[$id]]->disable();
668 if ($this->s2u[$id]->rd_socket_get() != NULL) {
669 $this->s2u[$id]->rd_socket_set(NULL);
671 unset($this->s2u[$id]);
675 printf("CLOSE ON READ\n");
677 if ($this->debug > 1) {
678 printf("post unset\n");
679 print_r($this->socks);
683 if ($this->debug > 1) {
686 if ($sock === $this->list) {
687 printf("Arrivati %d bytes da list\n", strlen($buf));
689 else if ($sock === $this->in || $sock === static::$cnt_slave) {
690 printf("Arrivati %d bytes da stdin\n", strlen($buf));
692 if ($line == "reload") {
693 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
697 else if ($line == "shutdown") {
698 if ($this->app->dump_data()) {
707 $key = array_search("$sock", $this->socks);
708 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
712 // TODO: MOVE HERE request_mgr to factorize new_sockets and POST closed
713 // $rret = $this->app->request_mgr
717 $this->garbage_manager(FALSE);
719 /* manage unfinished pages */
720 foreach ($this->pending_pages as $k => $pgflush) {
721 // TODO: try_flush if exists in the class
722 if ($pgflush->try_flush($this->curtime) == TRUE) {
723 unset($this->pending_pages[$k]);
728 $response: raw stream data not sent
729 $content: html consistent data (<script bla bla>)
730 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
733 /* manage open streaming */
734 foreach ($this->socks as $k => $sock) {
736 if (isset($this->s2u[$id])) {
737 $user = $this->s2u[$id];
738 $response = $user->rd_cache_get();
740 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
744 $user->ping_req = FALSE;
747 if ($response == "") {
749 $user->stream_main($content, $get, $post, $cookie);
750 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
751 if ($do_ping && $user->ping_req == FALSE) {
752 $content .= $user->stream_keepalive(TRUE);
753 $user->ping_req = TRUE;
755 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
756 $content = $user->stream_keepalive(FALSE);
758 if ($content != "") {
759 $response = chunked_content($user->rd_zls_get(), $content);
763 if ($response != "") {
764 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
765 echo "SPIA: [".$response."]\n";
766 $response_l = mb_strlen($response, "ASCII");
767 $wret = @fwrite($sock, $response);
768 if ($wret < $response_l) {
769 printf("TROUBLE WITH FWRITE: %d\n", $wret);
770 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
773 $user->rd_cache_set("");
776 $user->rd_kalive_reset($this->curtime);
779 // close socket after a while to prevent client memory consumption
780 if ($user->rd_endtime_is_expired($this->curtime)) {
781 if ($this->s2u[$id]->rd_socket_get() != NULL) {
782 $this->s2u[$id]->rd_socket_set(NULL);
784 unset($this->socks[$id]);
785 unset($this->s2u[$id]);
787 printf("CLOSE ON LOOP\n");
790 } // foreach ($this->socks...
793 } // function run(...