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, &$rest)
103 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
104 printf("LINE: [%s]\n", $line);
106 if (!isset($header['The-Request'])) {
109 $req = explode(" ", $header['The-Request']);
112 if (isset($header['Cookie'])) {
113 $cookies = explode(";", $header['Cookie']);
114 for ($i = 0 ; $i < count($cookies) ; $i++) {
115 $nameval = explode("=", trim($cookies[$i]));
116 if (count($nameval) != 2) {
117 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
120 $cookie[$nameval[0]] = urldecode($nameval[1]);
123 // GET params management
124 $get_vars = explode('?', $req[1], 2);
125 $path = $get_vars[0];
126 if (count($get_vars) > 1) {
127 $a = explode('&', $get_vars[1]);
128 printf("A COUNT: [%s] %d\n", $a[0], count($a));
129 for ($i = 0 ; $i < count($a) ; $i++) {
130 $b = explode('=', $a[$i]);
131 $get[$b[0]] = urldecode($b[1]);
134 // POST params management
135 if ($req[0] == 'POST') {
136 $conttype_all = explode(";", $header['Content-Type']);
137 $header['Content-Type'] = $conttype_all[0];
138 // $path_all[1-] other things like charset and so on
140 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
141 || !isset($header['Content-Length'])) {
144 $post_len = mb_strlen($line, "ASCII");
145 $a = explode('&', $line);
146 for ($i = 0 ; $i < count($a) ; $i++) {
147 $b = explode('=', $a[$i]);
148 $post[$b[0]] = urldecode($b[1]);
150 printf("INFO: postlen: %d\n", $post_len);
151 $rest = (int)($header['Content-Length']) - $post_len;
159 $split = explode(":", $line, 2);
160 $header[$split[0]] = $split[1];
165 function gpcs_var($name, $get, $post, $cookie)
167 if (isset($GLOBALS[$name]))
169 else if (isset($cookie[$name]))
170 return ($cookie[$name]);
171 else if (isset($post[$name]))
172 return ($post[$name]);
173 else if (isset($get[$name]))
174 return ($get[$name]);
179 function headers_render($header, $len)
183 if (isset($header['cookies'])) {
184 $cookies = $header['cookies']->render();
185 unset($header['cookies']);
187 if (isset($header['Location'])) {
188 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
191 $s = "HTTP/1.1 200 OK\r\n";
193 if (!isset($header['Date']))
194 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
195 if (!isset($header['Connection']))
196 $s .= "Connection: close\r\n";
197 if (!isset($header['Content-Type']))
198 $s .= "Content-Type: text/html\r\n";
199 foreach($header as $key => $value) {
200 $s .= sprintf("%s: %s\r\n", $key, $value);
203 $s .= sprintf("Content-Length: %d\r\n", $len);
206 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
207 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
208 if (!isset($header['Content-Encoding'])) {
209 $s .= "Content-Encoding: chunked\r\n";
211 $s .= "Transfer-Encoding: chunked\r\n";
221 * Caching system using ob php system to cache old style pages
222 * to a var and than send it with more calm
227 log_rd2("SHUTTA [".connection_status()."] !");
230 register_shutdown_function('shutta');
236 function chunked_content($zls, $content)
239 $cont_comp = $zls->compress_chunk($content);
242 $cont_comp = $content;
244 $cont_comp_l = mb_strlen($cont_comp, "ASCII");
245 printf("CHUNK: [%s]\n", $content);
247 return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
250 function chunked_fini()
252 return sprintf("0\r\n");
255 function get_encoding($header)
258 if (isset($header['Accept-Encoding'])) {
259 $acc = explode(',', $header['Accept-Encoding']);
261 if (array_search('gzip', $acc) !== FALSE) {
264 else if (array_search('deflate', $acc) !== FALSE) {
274 // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
275 // string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
278 $this->attr = array();
281 static function create($name)
283 $thiz = new Cookie();
285 $thiz->attr[$name] = "";
287 $argc = func_num_args();
288 for ($i = 1 ; $i < $argc ; $i++) {
289 $arg = func_get_arg($i);
292 $thiz->attr[$name] = urlencode($arg);
295 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
298 $thiz->attr['Path'] = $arg;
301 $thiz->attr['Domain'] = $arg;
305 $thiz->attr['Secure'] = NULL;
310 $thiz->attr['HttpOnly'] = NULL;
326 foreach ($this->attr as $k => $v) {
328 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
331 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
346 $this->cookies = array();
351 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
354 array_push($this->cookies, $cookie);
362 foreach ($this->cookies as $cookie) {
363 $r .= $cookie->render();
372 // maybe fixed_fd is unuseful
373 static $fixed_fd = 3;
374 static $cnt_master = NULL;
375 static $cnt_slave = NULL;
380 var $s2u; // user associated with input socket
381 var $s2p; // pending page associated with input socket
397 function Sac_a_push()
401 function sig_handler($sig)
408 if (static::$cnt_master != NULL) {
409 fwrite(static::$cnt_master, "\nshutdown\n");
410 fflush(static::$cnt_master);
417 if (static::$cnt_master != NULL) {
418 fwrite(static::$cnt_master, "\nreload\n");
419 fflush(static::$cnt_master);
425 static function create(&$app, $sockname, $debug, $blocking_mode)
427 $thiz = new Sac_a_push();
430 $thiz->file_socket = $sockname;
431 $thiz->unix_socket = "unix://$sockname";
432 $thiz->debug = $debug;
433 $thiz->socks = array();
434 $thiz->s2u = array();
435 $thiz->s2p = array();
436 $thiz->pending_pages = array();
438 // create a couple of sockets for control management
439 if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
440 STREAM_IPPROTO_IP)) == FALSE) {
443 static::$cnt_master = $sockpair[0];
444 static::$cnt_slave = $sockpair[1];
446 pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
447 pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
448 pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
450 $thiz->blocking_mode = 0; // 0 for non-blocking
453 for ($i = 0 ; $i < 4096 ; $i++) {
455 $thiz->rndstr .= " ";
457 $thiz->rndstr .= chr(mt_rand(65, 90));
460 if (file_exists($thiz->file_socket)) {
461 unlink($thiz->file_socket);
464 $old_umask = umask(0);
465 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
469 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
471 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
475 $thiz->main_loop = FALSE;
480 function socks_set($sock, $user, $pendpage)
484 $this->socks[$id] = $sock;
486 $this->s2u[$id] = $user;
487 if ($pendpage != NULL)
488 $this->s2p[$id] = $pendpage;
491 function socks_unset($sock)
495 if (isset($this->s2u[$id]))
496 unset($this->s2u[$id]);
497 if (isset($this->s2p[$id]))
498 unset($this->s2p[$id]);
499 unset($this->socks[$id]);
502 function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
504 $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
506 if ($pendpage->try_flush($this->curtime) == FALSE) {
507 // Add $pendpage to the pendpage array
508 $this->pendpage_add($pendpage);
512 function pendpage_add($pendpage)
514 array_push($this->pending_pages, $pendpage);
517 function pendpage_try_addwait(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest)
519 $pendpage = PendingPage::pendingpage_waiting($new_socket, $this->curtime, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest);
521 if ($pendpage->try_flush($this->curtime) == FALSE) {
522 // Add $pendpage to the pendpage array
524 $this->pendpage_add($pendpage);
530 function garbage_manager($force)
532 $this->app->garbage_manager($force);
534 foreach ($this->socks as $k => $sock) {
536 if (isset($this->s2u[$id])) {
537 if ($this->s2u[$id]->sess == '') {
538 if ($this->s2u[$id]->rd_socket_get() != NULL) {
539 $this->s2u[$id]->rd_socket_set(NULL);
541 unset($this->socks[$id]);
542 unset($this->s2u[$id]);
544 printf("CLOSE ON GARBAGE MANAGER\n");
552 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
554 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
555 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
556 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
557 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
558 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
559 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
560 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
561 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
562 GLOBAL $G_with_topbanner;
564 if ($this->main_loop) {
568 $this->main_loop = TRUE;
570 while ($this->main_loop) {
571 $this->curtime = time();
572 printf("IN LOOP: Current opened: %d pending_pages: %d - ", count($this->socks), count($this->pending_pages));
574 /* Prepare the read array */
575 /* // when we manage it ... */
577 /* $read = array_merge(array("$in" => $in), $socks); */
579 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in,
580 intval(static::$cnt_slave) => static::$cnt_slave),
583 if ($this->debug > 1) {
584 printf("PRE_SELECT\n");
589 $num_changed_sockets = @stream_select($read, $write, $except, 5, 500000);
591 if ($num_changed_sockets == 0) {
592 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
594 else if ($num_changed_sockets > 0) {
595 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
596 if ($this->debug > 1) {
599 /* At least at one of the sockets something interesting happened */
600 foreach ($read as $i => $sock) {
602 $manage_page = FALSE;
603 /* is_resource check is required because there is the possibility that
604 during new request an old connection is closed */
605 if (!is_resource($sock)) {
608 if ($sock === $this->list) {
609 printf("NUOVA CONNEX\n");
610 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
611 printf("SOCKET_ACCEPT FAILED\n");
620 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
621 printf("NEW_SOCKET: %d\n", intval($new_socket));
622 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
623 printf("RECEIVED HEADER:\n%s", $stream_info);
624 if (($path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie, $rest))
626 fprintf(STDERR, "TODO: fix wrong header management\n");
628 $addr = stream_socket_get_name($new_socket, TRUE);
629 printf("PATH: [%s]\n", $path);
630 printf("M: %s\nHEADER:\n", $method);
631 if ($method == "POST" && $rest > 0) {
632 fprintf(STDERR, "\nPOSTA DE CHE\n\n");
633 $this->pendpage_try_addwait($new_socket, 20,
634 $method, $header, $get, $post, $cookie,
635 substr($path, SITE_PREFIX_LEN), $addr, $rest);
637 // ADD PUSH INTO FD ARRAY AS WAITING DATA
638 // Passing all infos from spu_process_info as arguments:
640 // MAYBE: $stream_info,
641 // $method, $header, $get, $post, $cookie
642 // $s_a_p (this), $new_socket, substr($path, SITE_PREFIX_LEN),
658 printf("number of sockets after %d\n", count($this->socks));
661 printf("WARNING: ancillary_getstream failed\n");
665 $buf = fread($sock, 512);
666 // if socket is closed
667 if ($buf == FALSE || strlen($buf) == 0) {
670 printf("ERROR READING\n");
672 if ($sock === $this->list) {
673 printf("Arrivati %d bytes da list\n", strlen($buf));
676 else if ($sock === $this->in || $sock === static::$cnt_slave) {
677 printf("Arrivati %d bytes da stdin\n", strlen($buf));
681 unset($this->socks[$id]);
682 if (isset($this->s2u[$id])) {
683 // $user_a[$s2u[$id]]->disable();
684 if ($this->s2u[$id]->rd_socket_get() != NULL) {
685 $this->s2u[$id]->rd_socket_set(NULL);
687 unset($this->s2u[$id]);
691 printf("CLOSE ON READ\n");
693 if ($this->debug > 1) {
694 printf("post unset\n");
695 print_r($this->socks);
699 if ($this->debug > 1) {
702 if ($sock === $this->list) {
703 printf("Arrivati %d bytes da list\n", strlen($buf));
705 else if ($sock === $this->in || $sock === static::$cnt_slave) {
706 printf("Arrivati %d bytes da stdin\n", strlen($buf));
708 if ($line == "reload") {
709 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
713 else if ($line == "shutdown") {
714 if ($this->app->dump_data()) {
723 $key = array_search("$sock", $this->socks);
724 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
729 // TODO: MOVE HERE request_mgr to factorize new_sockets and POST closed
730 // $rret = $this->app->request_mgr
731 if ($manage_page == TRUE) {
732 $header_out = array();
733 // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
735 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
736 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
738 fprintf(STDERR, "\n\n DI QUI PASSA [%s]\n\n", $rret);
739 if ($rret == FALSE) {
740 // FIXME: manage 404 !!!
741 printf("TODO: fix unknown page\n");
747 $this->garbage_manager(FALSE);
749 /* manage unfinished pages */
750 foreach ($this->pending_pages as $k => $pendpage) {
751 // TODO: try_flush if exists in the class
752 if ($pendpage->try_flush($this->curtime) == TRUE) {
753 unset($this->pending_pages[$k]);
758 $response: raw stream data not sent
759 $content: html consistent data (<script bla bla>)
760 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
763 /* manage open streaming */
764 foreach ($this->socks as $k => $sock) {
766 if (isset($this->s2u[$id])) {
767 $user = $this->s2u[$id];
768 $response = $user->rd_cache_get();
770 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
774 $user->ping_req = FALSE;
777 if ($response == "") {
779 $user->stream_main($content, $get, $post, $cookie);
780 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
781 if ($do_ping && $user->ping_req == FALSE) {
782 $content .= $user->stream_keepalive(TRUE);
783 $user->ping_req = TRUE;
785 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
786 $content = $user->stream_keepalive(FALSE);
788 if ($content != "") {
789 $response = chunked_content($user->rd_zls_get(), $content);
793 if ($response != "") {
794 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
795 echo "SPIA: [".$response."]\n";
796 $response_l = mb_strlen($response, "ASCII");
797 $wret = @fwrite($sock, $response);
798 if ($wret < $response_l) {
799 printf("TROUBLE WITH FWRITE: %d\n", $wret);
800 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
803 $user->rd_cache_set("");
806 $user->rd_kalive_reset($this->curtime);
809 // close socket after a while to prevent client memory consumption
810 if ($user->rd_endtime_is_expired($this->curtime)) {
811 if ($this->s2u[$id]->rd_socket_get() != NULL) {
812 $this->s2u[$id]->rd_socket_set(NULL);
814 unset($this->socks[$id]);
815 unset($this->s2u[$id]);
817 printf("CLOSE ON LOOP\n");
820 } // foreach ($this->socks...
823 } // function run(...