3 * brisk - spush/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));
75 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
81 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
82 // printf("LINE: [%s]\n", $line);
84 if (!isset($header['The-Request'])) {
87 $req = explode(" ", $header['The-Request']);
90 if (isset($header['Cookie'])) {
91 $cookies = explode(";", $header['Cookie']);
92 for ($i = 0 ; $i < count($cookies) ; $i++) {
93 $nameval = explode("=", trim($cookies[$i]));
94 if (count($nameval) != 2) {
95 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
98 $cookie[$nameval[0]] = urldecode($nameval[1]);
101 // GET params management
102 $get_vars = explode('?', $req[1], 2);
103 $path = $get_vars[0];
104 if (count($get_vars) > 1) {
105 $a = explode('&', $get_vars[1]);
106 printf("A COUNT: [%s] %d\n", $a[0], count($a));
107 for ($i = 0 ; $i < count($a) ; $i++) {
108 $b = explode('=', $a[$i]);
109 $get[$b[0]] = urldecode($b[1]);
112 // POST params management
113 if ($req[0] == 'POST') {
114 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
115 || !isset($header['Content-Length'])) {
118 $post_len = mb_strlen($line, "latin1");
119 $a = explode('&', $line);
120 for ($i = 0 ; $i < count($a) ; $i++) {
121 $b = explode('=', $a[$i]);
122 $post[$b[0]] = urldecode($b[1]);
124 printf("INFO: postlen: %d\n", $post_len);
132 $split = explode(":", $line, 2);
133 $header[$split[0]] = $split[1];
138 function gpcs_var($name, $get, $post, $cookie)
140 if (isset($GLOBALS[$name]))
142 else if (isset($cookie[$name]))
143 return ($cookie[$name]);
144 else if (isset($post[$name]))
145 return ($post[$name]);
146 else if (isset($get[$name]))
147 return ($get[$name]);
152 function headers_render($header, $len)
156 if (isset($header['cookies'])) {
157 $cookies = $header['cookies']->render();
158 unset($header['cookies']);
160 if (isset($header['Location'])) {
161 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
164 $s = "HTTP/1.1 200 OK\r\n";
166 if (!isset($header['Date']))
167 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
168 if (!isset($header['Connection']))
169 $s .= "Connection: close\r\n";
170 if (!isset($header['Content-Type']))
171 $s .= "Content-Type: text/html\r\n";
172 foreach($header as $key => $value) {
173 $s .= sprintf("%s: %s\r\n", $key, $value);
176 $s .= sprintf("Content-Length: %d\r\n", $len);
179 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
180 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
181 if (!isset($header['Content-Encoding'])) {
182 $s .= "Content-Encoding: chunked\r\n";
184 $s .= "Transfer-Encoding: chunked\r\n";
194 * Caching system using ob php system to cache old style pages
195 * to a var and than send it with more calm
200 log_rd2("SHUTTA [".connection_status()."] !");
203 register_shutdown_function('shutta');
209 function chunked_content($zls, $content)
212 $cont_comp = $zls->compress_chunk($content);
215 $cont_comp = $content;
217 $cont_comp_l = mb_strlen($cont_comp, "ASCII");
218 printf("CHUNK: [%s]\n", $content);
220 return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
223 function chunked_fini()
225 return sprintf("0\r\n");
228 function get_encoding($header)
231 if (isset($header['Accept-Encoding'])) {
232 $acc = explode(',', $header['Accept-Encoding']);
234 if (array_search('gzip', $acc) !== FALSE) {
237 else if (array_search('deflate', $acc) !== FALSE) {
247 // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
248 // string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
251 $this->attr = array();
254 static function create($name)
256 $thiz = new Cookie();
258 $thiz->attr[$name] = "";
260 $argc = func_num_args();
261 for ($i = 1 ; $i < $argc ; $i++) {
262 $arg = func_get_arg($i);
265 $thiz->attr[$name] = urlencode($arg);
268 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
271 $thiz->attr['Path'] = $arg;
274 $thiz->attr['Domain'] = $arg;
278 $thiz->attr['Secure'] = NULL;
283 $thiz->attr['HttpOnly'] = NULL;
299 foreach ($this->attr as $k => $v) {
301 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
304 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
319 $this->cookies = array();
324 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
327 array_push($this->cookies, $cookie);
335 foreach ($this->cookies as $cookie) {
336 $r .= $cookie->render();
345 static $fixed_fd = 2;
366 function Sac_a_push()
370 // Sac_a_push::create("/tmp/brisk.sock", 0, 0
372 static function create(&$app, $sockname, $debug, $blocking_mode)
374 $thiz = new Sac_a_push();
377 $thiz->file_socket = $sockname;
378 $thiz->unix_socket = "unix://$sockname";
379 $thiz->debug = $debug;
380 $thiz->socks = array();
381 $thiz->s2u = array();
382 $thiz->pages_flush = array();
384 $thiz->blocking_mode = 0; // 0 for non-blocking
387 for ($i = 0 ; $i < 4096 ; $i++) {
389 $thiz->rndstr .= " ";
391 $thiz->rndstr .= chr(mt_rand(65, 90));
394 if (file_exists($thiz->file_socket)) {
395 unlink($thiz->file_socket);
398 $old_umask = umask(0);
399 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
403 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
405 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
409 $thiz->main_loop = FALSE;
414 function socks_set($sock, $user)
418 $this->s2u[$id] = $user;
419 $this->socks[$id] = $sock;
422 function socks_unset($sock)
426 unset($this->s2u[$id]);
427 unset($this->socks[$id]);
430 function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
432 $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
434 if ($pgflush->try_flush($this->curtime) == FALSE) {
435 // Add $pgflush to the pgflush array
436 $this->pgflush_add($pgflush);
440 function pgflush_add($pgflush)
442 array_push($this->pages_flush, $pgflush);
445 function garbage_manager($force)
447 $this->app->garbage_manager($force);
449 foreach ($this->socks as $k => $sock) {
450 if ($this->s2u[intval($sock)]->sess == '') {
451 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
452 $this->s2u[intval($sock)]->rd_socket_set(NULL);
454 unset($this->socks[intval($sock)]);
455 unset($this->s2u[intval($sock)]);
457 printf("CLOSE ON GARBAGE MANAGER\n");
464 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
466 GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
467 GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
468 GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
469 GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
470 GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
471 GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
472 GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
473 GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
474 GLOBAL $G_with_topbanner;
476 if ($this->main_loop) {
480 $this->main_loop = TRUE;
482 while ($this->main_loop) {
483 $this->curtime = time();
484 printf("IN LOOP: Current opened: %d pages_flush: %d - ", count($this->socks), count($this->pages_flush));
486 /* Prepare the read array */
487 /* // when we manage it ... */
489 /* $read = array_merge(array("$in" => $in), $socks); */
491 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
494 if ($this->debug > 1) {
495 printf("PRE_SELECT\n");
500 $num_changed_sockets = stream_select($read, $write, $except, 0, 500000);
502 if ($num_changed_sockets == 0) {
503 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
505 else if ($num_changed_sockets > 0) {
506 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
507 if ($this->debug > 1) {
510 /* At least at one of the sockets something interesting happened */
511 foreach ($read as $i => $sock) {
512 /* is_resource check is required because there is the possibility that
513 during new request an old connection is closed */
514 if (!is_resource($sock)) {
517 if ($sock === $this->list) {
518 printf("NUOVA CONNEX\n");
519 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
520 printf("SOCKET_ACCEPT FAILED\n");
528 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
529 printf("NEW_SOCKET: %d\n", intval($new_socket));
530 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
531 printf("RECEIVED HEADER:\n%s", $stream_info);
532 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
533 printf("PATH: [%s]\n", $path);
534 printf("M: %s\nHEADER:\n", $method);
542 $addr = stream_socket_get_name($new_socket, TRUE);
543 $header_out = array();
545 $subs = SITE_PREFIX."briskin5/";
546 $subs_l = strlen($subs);
548 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
549 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
551 if ($rret == FALSE) {
552 // FIXME: manage 404 !!!
553 printf("TODO: fix unknown page\n");
555 printf("number of sockets after %d\n", count($this->socks));
558 printf("WARNING: ancillary_getstream failed\n");
562 $buf = fread($sock, 512);
563 // if socket is closed
564 if ($buf == FALSE || strlen($buf) == 0) {
566 printf("ERROR READING\n");
568 if ($sock === $this->list) {
569 printf("Arrivati %d bytes da list\n", strlen($buf));
572 else if ($sock === $this->in) {
573 printf("Arrivati %d bytes da stdin\n", strlen($buf));
577 // $user_a[$s2u[intval($sock)]]->disable();
578 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
579 $this->s2u[intval($sock)]->rd_socket_set(NULL);
581 unset($this->socks[intval($sock)]);
582 unset($this->s2u[intval($sock)]);
585 printf("CLOSE ON READ\n");
587 if ($this->debug > 1) {
588 printf("post unset\n");
589 print_r($this->socks);
593 if ($this->debug > 1) {
596 if ($sock === $this->list) {
597 printf("Arrivati %d bytes da list\n", strlen($buf));
599 else if ($sock === $this->in) {
600 printf("Arrivati %d bytes da stdin\n", strlen($buf));
602 if ($line == "reload") {
603 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
607 else if ($line == "shutdown") {
608 if ($this->app->dump_data()) {
617 $key = array_search("$sock", $this->socks);
618 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
625 $this->garbage_manager(FALSE);
627 /* manage unfinished pages */
628 foreach ($this->pages_flush as $k => $pgflush) {
629 if ($pgflush->try_flush($this->curtime) == TRUE) {
630 unset($this->pages_flush[$k]);
635 $response: raw stream data not sent
636 $content: html consistent data (<script bla bla>)
637 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
640 /* manage open streaming */
641 foreach ($this->socks as $k => $sock) {
642 if (isset($this->s2u[intval($sock)])) {
643 $user = $this->s2u[intval($sock)];
644 $response = $user->rd_cache_get();
646 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
650 $user->ping_req = FALSE;
653 if ($response == "") {
655 $user->stream_main($content, $get, $post, $cookie);
656 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
657 if ($do_ping && $user->ping_req == FALSE) {
658 $content .= $user->stream_keepalive(TRUE);
659 $user->ping_req = TRUE;
661 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
662 $content = $user->stream_keepalive(FALSE);
664 if ($content != "") {
665 $response = chunked_content($user->rd_zls_get(), $content);
669 if ($response != "") {
670 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
671 echo "SPIA: [".$response."]\n";
672 $response_l = mb_strlen($response, "ASCII");
673 $wret = @fwrite($sock, $response);
674 if ($wret < $response_l) {
675 printf("TROUBLE WITH FWRITE: %d\n", $wret);
676 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
679 $user->rd_cache_set("");
682 $user->rd_kalive_reset($this->curtime);
685 // close socket after a while to prevent client memory consumption
686 if ($user->rd_endtime_is_expired($this->curtime)) {
687 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
688 $this->s2u[intval($sock)]->rd_socket_set(NULL);
690 unset($this->socks[intval($sock)]);
691 unset($this->s2u[intval($sock)]);
693 printf("CLOSE ON LOOP\n");
696 } // foreach ($this->socks...
699 } // function run(...