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);
29 function global_dump()
31 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
32 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
33 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
34 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
35 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
36 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
37 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
38 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
39 GLOBAL $G_with_topbanner;
41 fprintf(STDERR, "G_alarm_passwd = [%s]\n", print_r($G_alarm_passwd, TRUE));
42 fprintf(STDERR, "G_black_list = [%s]\n", print_r($G_black_list, TRUE));
43 fprintf(STDERR, "G_btrace_pref_sub = [%s]\n", print_r($G_btrace_pref_sub, TRUE));
44 fprintf(STDERR, "G_dbauth = [%s]\n", print_r($G_dbauth, TRUE));
45 fprintf(STDERR, "G_dbpfx = [%s]\n", print_r($G_dbpfx, TRUE));
46 fprintf(STDERR, "G_donors_all = [%s]\n", print_r($G_donors_all, TRUE));
47 fprintf(STDERR, "G_donors_cur = [%s]\n", print_r($G_donors_cur, TRUE));
48 fprintf(STDERR, "G_is_local = [%s]\n", print_r($G_is_local, TRUE));
49 fprintf(STDERR, "G_lang = [%s]\n", print_r($G_lang, TRUE));
50 fprintf(STDERR, "G_poll_entries = [%s]\n", print_r($G_poll_entries, TRUE));
51 fprintf(STDERR, "G_poll_name = [%s]\n", print_r($G_poll_name, TRUE));
52 fprintf(STDERR, "G_poll_title = [%s]\n", print_r($G_poll_title, TRUE));
53 fprintf(STDERR, "G_proxy_white_list = [%s]\n", print_r($G_proxy_white_list, TRUE));
54 fprintf(STDERR, "G_room_roadmap = [%s]\n", print_r($G_room_roadmap, TRUE));
55 fprintf(STDERR, "G_shutdown = [%s]\n", print_r($G_shutdown, TRUE));
56 fprintf(STDERR, "G_sidebanner = [%s]\n", print_r($G_sidebanner, TRUE));
57 fprintf(STDERR, "G_sidebanner2 = [%s]\n", print_r($G_sidebanner2, TRUE));
58 fprintf(STDERR, "G_splash_content = [%s]\n", print_r($G_splash_content, TRUE));
59 fprintf(STDERR, "G_splash_contents = [%s]\n", print_r($G_splash_contents, TRUE));
60 fprintf(STDERR, "G_splash_cont_idx = [%s]\n", print_r($G_splash_cont_idx, TRUE));
61 fprintf(STDERR, "G_splash_h = [%s]\n", print_r($G_splash_h, TRUE));
62 fprintf(STDERR, "G_splash_idx = [%s]\n", print_r($G_splash_idx, TRUE));
63 fprintf(STDERR, "G_splash_interval = [%s]\n", print_r($G_splash_interval, TRUE));
64 fprintf(STDERR, "G_splash_timeout = [%s]\n", print_r($G_splash_timeout, TRUE));
65 fprintf(STDERR, "G_splash_w = [%s]\n", print_r($G_splash_w, TRUE));
66 fprintf(STDERR, "G_topbanner = [%s]\n", print_r($G_topbanner, TRUE));
67 fprintf(STDERR, "G_with_donors = [%s]\n", print_r($G_with_donors, TRUE));
68 fprintf(STDERR, "G_with_poll = [%s]\n", print_r($G_with_poll, TRUE));
69 fprintf(STDERR, "G_with_sidebanner = [%s]\n", print_r($G_with_sidebanner, TRUE));
70 fprintf(STDERR, "G_with_sidebanner2 = [%s]\n", print_r($G_with_sidebanner2, TRUE));
71 fprintf(STDERR, "G_with_splash = [%s]\n", print_r($G_with_splash, TRUE));
72 fprintf(STDERR, "G_with_topbanner = [%s]\n", print_r($G_with_topbanner, TRUE));
78 $fname = LEGAL_PATH."/brisk.pid";
80 if (file_exists($fname)) {
81 log_crit("WARN: brisk.pid already exists");
83 file_put_contents($fname, sprintf("%d\n", $pid));
88 $fname = LEGAL_PATH."/brisk.pid";
90 if (file_exists($fname)) {
95 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
101 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
102 // printf("LINE: [%s]\n", $line);
104 if (!isset($header['The-Request'])) {
107 $req = explode(" ", $header['The-Request']);
110 if (isset($header['Cookie'])) {
111 $cookies = explode(";", $header['Cookie']);
112 for ($i = 0 ; $i < count($cookies) ; $i++) {
113 $nameval = explode("=", trim($cookies[$i]));
114 if (count($nameval) != 2) {
115 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
118 $cookie[$nameval[0]] = urldecode($nameval[1]);
121 // GET params management
122 $get_vars = explode('?', $req[1], 2);
123 $path = $get_vars[0];
124 if (count($get_vars) > 1) {
125 $a = explode('&', $get_vars[1]);
126 printf("A COUNT: [%s] %d\n", $a[0], count($a));
127 for ($i = 0 ; $i < count($a) ; $i++) {
128 $b = explode('=', $a[$i]);
129 $get[$b[0]] = urldecode($b[1]);
132 // POST params management
133 if ($req[0] == 'POST') {
134 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
135 || !isset($header['Content-Length'])) {
138 $post_len = mb_strlen($line, "latin1");
139 $a = explode('&', $line);
140 for ($i = 0 ; $i < count($a) ; $i++) {
141 $b = explode('=', $a[$i]);
142 $post[$b[0]] = urldecode($b[1]);
144 printf("INFO: postlen: %d\n", $post_len);
152 $split = explode(":", $line, 2);
153 $header[$split[0]] = $split[1];
158 function gpcs_var($name, $get, $post, $cookie)
160 if (isset($GLOBALS[$name]))
162 else if (isset($cookie[$name]))
163 return ($cookie[$name]);
164 else if (isset($post[$name]))
165 return ($post[$name]);
166 else if (isset($get[$name]))
167 return ($get[$name]);
172 function headers_render($header, $len)
176 if (isset($header['cookies'])) {
177 $cookies = $header['cookies']->render();
178 unset($header['cookies']);
180 if (isset($header['Location'])) {
181 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
184 $s = "HTTP/1.1 200 OK\r\n";
186 if (!isset($header['Date']))
187 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
188 if (!isset($header['Connection']))
189 $s .= "Connection: close\r\n";
190 if (!isset($header['Content-Type']))
191 $s .= "Content-Type: text/html\r\n";
192 foreach($header as $key => $value) {
193 $s .= sprintf("%s: %s\r\n", $key, $value);
196 $s .= sprintf("Content-Length: %d\r\n", $len);
199 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
200 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
201 if (!isset($header['Content-Encoding'])) {
202 $s .= "Content-Encoding: chunked\r\n";
204 $s .= "Transfer-Encoding: chunked\r\n";
214 * Caching system using ob php system to cache old style pages
215 * to a var and than send it with more calm
220 log_rd2("SHUTTA [".connection_status()."] !");
223 register_shutdown_function('shutta');
229 function chunked_content($zls, $content)
232 $cont_comp = $zls->compress_chunk($content);
235 $cont_comp = $content;
237 $cont_comp_l = mb_strlen($cont_comp, "ASCII");
238 printf("CHUNK: [%s]\n", $content);
240 return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
243 function chunked_fini()
245 return sprintf("0\r\n");
248 function get_encoding($header)
251 if (isset($header['Accept-Encoding'])) {
252 $acc = explode(',', $header['Accept-Encoding']);
254 if (array_search('gzip', $acc) !== FALSE) {
257 else if (array_search('deflate', $acc) !== FALSE) {
267 // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
268 // string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
271 $this->attr = array();
274 static function create($name)
276 $thiz = new Cookie();
278 $thiz->attr[$name] = "";
280 $argc = func_num_args();
281 for ($i = 1 ; $i < $argc ; $i++) {
282 $arg = func_get_arg($i);
285 $thiz->attr[$name] = urlencode($arg);
288 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
291 $thiz->attr['Path'] = $arg;
294 $thiz->attr['Domain'] = $arg;
298 $thiz->attr['Secure'] = NULL;
303 $thiz->attr['HttpOnly'] = NULL;
319 foreach ($this->attr as $k => $v) {
321 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
324 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
339 $this->cookies = array();
344 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
347 array_push($this->cookies, $cookie);
355 foreach ($this->cookies as $cookie) {
356 $r .= $cookie->render();
365 static $fixed_fd = 2;
386 function Sac_a_push()
390 // Sac_a_push::create("/tmp/brisk.sock", 0, 0
392 static function create(&$app, $sockname, $debug, $blocking_mode)
394 $thiz = new Sac_a_push();
397 $thiz->file_socket = $sockname;
398 $thiz->unix_socket = "unix://$sockname";
399 $thiz->debug = $debug;
400 $thiz->socks = array();
401 $thiz->s2u = array();
402 $thiz->pages_flush = array();
404 $thiz->blocking_mode = 0; // 0 for non-blocking
407 for ($i = 0 ; $i < 4096 ; $i++) {
409 $thiz->rndstr .= " ";
411 $thiz->rndstr .= chr(mt_rand(65, 90));
414 if (file_exists($thiz->file_socket)) {
415 unlink($thiz->file_socket);
418 $old_umask = umask(0);
419 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
423 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
425 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
429 $thiz->main_loop = FALSE;
434 function socks_set($sock, $user)
438 $this->s2u[$id] = $user;
439 $this->socks[$id] = $sock;
442 function socks_unset($sock)
446 unset($this->s2u[$id]);
447 unset($this->socks[$id]);
450 function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
452 $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
454 if ($pgflush->try_flush($this->curtime) == FALSE) {
455 // Add $pgflush to the pgflush array
456 $this->pgflush_add($pgflush);
460 function pgflush_add($pgflush)
462 array_push($this->pages_flush, $pgflush);
465 function garbage_manager($force)
467 $this->app->garbage_manager($force);
469 foreach ($this->socks as $k => $sock) {
470 if ($this->s2u[intval($sock)]->sess == '') {
471 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
472 $this->s2u[intval($sock)]->rd_socket_set(NULL);
474 unset($this->socks[intval($sock)]);
475 unset($this->s2u[intval($sock)]);
477 printf("CLOSE ON GARBAGE MANAGER\n");
484 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
486 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
487 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
488 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
489 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
490 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
491 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
492 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
493 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
494 GLOBAL $G_with_topbanner;
496 if ($this->main_loop) {
500 $this->main_loop = TRUE;
502 while ($this->main_loop) {
503 $this->curtime = time();
504 printf("IN LOOP: Current opened: %d pages_flush: %d - ", count($this->socks), count($this->pages_flush));
506 /* Prepare the read array */
507 /* // when we manage it ... */
509 /* $read = array_merge(array("$in" => $in), $socks); */
511 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
514 if ($this->debug > 1) {
515 printf("PRE_SELECT\n");
520 $num_changed_sockets = stream_select($read, $write, $except, 0, 500000);
522 if ($num_changed_sockets == 0) {
523 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
525 else if ($num_changed_sockets > 0) {
526 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
527 if ($this->debug > 1) {
530 /* At least at one of the sockets something interesting happened */
531 foreach ($read as $i => $sock) {
532 /* is_resource check is required because there is the possibility that
533 during new request an old connection is closed */
534 if (!is_resource($sock)) {
537 if ($sock === $this->list) {
538 printf("NUOVA CONNEX\n");
539 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
540 printf("SOCKET_ACCEPT FAILED\n");
548 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
549 printf("NEW_SOCKET: %d\n", intval($new_socket));
550 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
551 printf("RECEIVED HEADER:\n%s", $stream_info);
552 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
553 printf("PATH: [%s]\n", $path);
554 printf("M: %s\nHEADER:\n", $method);
562 $addr = stream_socket_get_name($new_socket, TRUE);
563 $header_out = array();
565 $subs = SITE_PREFIX."briskin5/";
566 $subs_l = strlen($subs);
568 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
569 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
571 if ($rret == FALSE) {
572 // FIXME: manage 404 !!!
573 printf("TODO: fix unknown page\n");
575 printf("number of sockets after %d\n", count($this->socks));
578 printf("WARNING: ancillary_getstream failed\n");
582 $buf = fread($sock, 512);
583 // if socket is closed
584 if ($buf == FALSE || strlen($buf) == 0) {
586 printf("ERROR READING\n");
588 if ($sock === $this->list) {
589 printf("Arrivati %d bytes da list\n", strlen($buf));
592 else if ($sock === $this->in) {
593 printf("Arrivati %d bytes da stdin\n", strlen($buf));
597 // $user_a[$s2u[intval($sock)]]->disable();
598 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
599 $this->s2u[intval($sock)]->rd_socket_set(NULL);
601 unset($this->socks[intval($sock)]);
602 unset($this->s2u[intval($sock)]);
605 printf("CLOSE ON READ\n");
607 if ($this->debug > 1) {
608 printf("post unset\n");
609 print_r($this->socks);
613 if ($this->debug > 1) {
616 if ($sock === $this->list) {
617 printf("Arrivati %d bytes da list\n", strlen($buf));
619 else if ($sock === $this->in) {
620 printf("Arrivati %d bytes da stdin\n", strlen($buf));
622 if ($line == "reload") {
623 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
627 else if ($line == "shutdown") {
628 if ($this->app->dump_data()) {
637 $key = array_search("$sock", $this->socks);
638 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
645 $this->garbage_manager(FALSE);
647 /* manage unfinished pages */
648 foreach ($this->pages_flush as $k => $pgflush) {
649 if ($pgflush->try_flush($this->curtime) == TRUE) {
650 unset($this->pages_flush[$k]);
655 $response: raw stream data not sent
656 $content: html consistent data (<script bla bla>)
657 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
660 /* manage open streaming */
661 foreach ($this->socks as $k => $sock) {
662 if (isset($this->s2u[intval($sock)])) {
663 $user = $this->s2u[intval($sock)];
664 $response = $user->rd_cache_get();
666 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
670 $user->ping_req = FALSE;
673 if ($response == "") {
675 $user->stream_main($content, $get, $post, $cookie);
676 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
677 if ($do_ping && $user->ping_req == FALSE) {
678 $content .= $user->stream_keepalive(TRUE);
679 $user->ping_req = TRUE;
681 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
682 $content = $user->stream_keepalive(FALSE);
684 if ($content != "") {
685 $response = chunked_content($user->rd_zls_get(), $content);
689 if ($response != "") {
690 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
691 echo "SPIA: [".$response."]\n";
692 $response_l = mb_strlen($response, "ASCII");
693 $wret = @fwrite($sock, $response);
694 if ($wret < $response_l) {
695 printf("TROUBLE WITH FWRITE: %d\n", $wret);
696 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
699 $user->rd_cache_set("");
702 $user->rd_kalive_reset($this->curtime);
705 // close socket after a while to prevent client memory consumption
706 if ($user->rd_endtime_is_expired($this->curtime)) {
707 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
708 $this->s2u[intval($sock)]->rd_socket_set(NULL);
710 unset($this->socks[intval($sock)]);
711 unset($this->s2u[intval($sock)]);
713 printf("CLOSE ON LOOP\n");
716 } // foreach ($this->socks...
719 } // function run(...