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);
28 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
34 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
35 // printf("LINE: [%s]\n", $line);
37 if (!isset($header['The-Request'])) {
40 $req = explode(" ", $header['The-Request']);
43 if (isset($header['Cookie'])) {
44 $cookies = explode(";", $header['Cookie']);
45 for ($i = 0 ; $i < count($cookies) ; $i++) {
46 $nameval = explode("=", trim($cookies[$i]));
47 if (count($nameval) != 2) {
48 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
51 $cookie[$nameval[0]] = urldecode($nameval[1]);
54 // GET params management
55 $get_vars = explode('?', $req[1], 2);
57 if (count($get_vars) > 1) {
58 $a = explode('&', $get_vars[1]);
59 printf("A COUNT: [%s] %d\n", $a[0], count($a));
60 for ($i = 0 ; $i < count($a) ; $i++) {
61 $b = explode('=', $a[$i]);
62 $get[$b[0]] = urldecode($b[1]);
65 // POST params management
66 if ($req[0] == 'POST') {
67 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
68 || !isset($header['Content-Length'])) {
71 $post_len = mb_strlen($line, "latin1");
72 $a = explode('&', $line);
73 for ($i = 0 ; $i < count($a) ; $i++) {
74 $b = explode('=', $a[$i]);
75 $post[$b[0]] = urldecode($b[1]);
77 printf("INFO: postlen: %d\n", $post_len);
85 $split = explode(":", $line, 2);
86 $header[$split[0]] = $split[1];
91 function gpcs_var($name, $get, $post, $cookie)
93 if (isset($GLOBALS[$name]))
95 else if (isset($cookie[$name]))
96 return ($cookie[$name]);
97 else if (isset($post[$name]))
98 return ($post[$name]);
99 else if (isset($get[$name]))
100 return ($get[$name]);
105 function headers_render($header, $len)
109 if (isset($header['cookies'])) {
110 $cookies = $header['cookies']->render();
111 unset($header['cookies']);
113 if (isset($header['Location'])) {
114 $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
117 $s = "HTTP/1.1 200 OK\r\n";
119 if (!isset($header['Date']))
120 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
121 if (!isset($header['Connection']))
122 $s .= "Connection: close\r\n";
123 if (!isset($header['Content-Type']))
124 $s .= "Content-Type: text/html\r\n";
125 foreach($header as $key => $value) {
126 $s .= sprintf("%s: %s\r\n", $key, $value);
129 $s .= sprintf("Content-Length: %d\r\n", $len);
132 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
133 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
134 if (!isset($header['Content-Encoding'])) {
135 $s .= "Content-Encoding: chunked\r\n";
137 $s .= "Transfer-Encoding: chunked\r\n";
147 * Caching system using ob php system to cache old style pages
148 * to a var and than send it with more calm
153 log_rd2("SHUTTA [".connection_status()."] !");
156 register_shutdown_function('shutta');
162 function chunked_content($zls, $content)
165 $cont_comp = $zls->compress_chunk($content);
168 $cont_comp = $content;
170 $cont_comp_l = mb_strlen($cont_comp, "ASCII");
171 printf("CHUNK: [%s]\n", $content);
173 return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
176 function chunked_fini()
178 return sprintf("0\r\n");
181 function get_encoding($header)
184 if (isset($header['Accept-Encoding'])) {
185 $acc = explode(',', $header['Accept-Encoding']);
187 if (array_search('gzip', $acc) !== FALSE) {
190 else if (array_search('deflate', $acc) !== FALSE) {
200 // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
201 // string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
204 $this->attr = array();
207 static function create($name)
209 $thiz = new Cookie();
211 $thiz->attr[$name] = "";
213 $argc = func_num_args();
214 for ($i = 1 ; $i < $argc ; $i++) {
215 $arg = func_get_arg($i);
218 $thiz->attr[$name] = urlencode($arg);
221 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
224 $thiz->attr['Path'] = $arg;
227 $thiz->attr['Domain'] = $arg;
231 $thiz->attr['Secure'] = NULL;
236 $thiz->attr['HttpOnly'] = NULL;
252 foreach ($this->attr as $k => $v) {
254 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
257 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
272 $this->cookies = array();
277 if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
280 array_push($this->cookies, $cookie);
288 foreach ($this->cookies as $cookie) {
289 $r .= $cookie->render();
298 static $fixed_fd = 2;
319 function Sac_a_push()
323 // Sac_a_push::create("/tmp/brisk.sock", 0, 0
325 static function create(&$app, $sockname, $debug, $blocking_mode)
327 $thiz = new Sac_a_push();
330 $thiz->file_socket = $sockname;
331 $thiz->unix_socket = "unix://$sockname";
332 $thiz->debug = $debug;
333 $thiz->socks = array();
334 $thiz->s2u = array();
335 $thiz->pages_flush = array();
337 $thiz->blocking_mode = 0; // 0 for non-blocking
340 for ($i = 0 ; $i < 4096 ; $i++) {
342 $thiz->rndstr .= "\n";
344 $thiz->rndstr .= chr(mt_rand(65, 90));
347 if (file_exists($thiz->file_socket)) {
348 unlink($thiz->file_socket);
351 $old_umask = umask(0);
352 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
356 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
358 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
362 $thiz->main_loop = FALSE;
367 function socks_set($sock, $user)
371 $this->s2u[$id] = $user;
372 $this->socks[$id] = $sock;
375 function socks_unset($sock)
379 unset($this->s2u[$id]);
380 unset($this->socks[$id]);
383 function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
385 $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
387 if ($pgflush->try_flush($this->curtime) == FALSE) {
388 // Add $pgflush to the pgflush array
389 $this->pgflush_add($pgflush);
393 function pgflush_add($pgflush)
395 array_push($this->pages_flush, $pgflush);
398 function garbage_manager($force)
400 $this->app->garbage_manager($force);
402 foreach ($this->socks as $k => $sock) {
403 if ($this->s2u[intval($sock)]->sess == '') {
404 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
405 $this->s2u[intval($sock)]->rd_socket_set(NULL);
407 unset($this->socks[intval($sock)]);
408 unset($this->s2u[intval($sock)]);
410 printf("CLOSE ON GARBAGE MANAGER\n");
417 GLOBAL $DOCUMENT_ROOT, $HTTP_HOST, $G_with_splash;
419 if ($this->main_loop) {
423 $this->main_loop = TRUE;
425 while ($this->main_loop) {
426 $this->curtime = time();
427 printf("IN LOOP: Current opened: %d pages_flush: %d - ", count($this->socks), count($this->pages_flush));
429 /* Prepare the read array */
430 /* // when we manage it ... */
432 /* $read = array_merge(array("$in" => $in), $socks); */
434 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
437 if ($this->debug > 1) {
438 printf("PRE_SELECT\n");
443 $num_changed_sockets = stream_select($read, $write, $except, 0, 500000);
445 if ($num_changed_sockets == 0) {
446 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
448 else if ($num_changed_sockets > 0) {
449 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
450 if ($this->debug > 1) {
453 /* At least at one of the sockets something interesting happened */
454 foreach ($read as $i => $sock) {
455 /* is_resource check is required because there is the possibility that
456 during new request an old connection is closed */
457 if (!is_resource($sock)) {
460 if ($sock === $this->list) {
461 printf("NUOVA CONNEX\n");
462 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
463 printf("SOCKET_ACCEPT FAILED\n");
471 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
472 printf("NEW_SOCKET: %d\n", intval($new_socket));
473 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
474 printf("RECEIVED HEADER:\n%s", $stream_info);
475 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
476 printf("PATH: [%s]\n", $path);
477 printf("M: %s\nHEADER:\n", $method);
485 $addr = stream_socket_get_name($new_socket, TRUE);
486 $header_out = array();
488 $subs = SITE_PREFIX."briskin5/";
489 $subs_l = strlen($subs);
491 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
492 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
494 if ($rret == FALSE) {
495 // FIXME: manage 404 !!!
496 printf("TODO: fix unknown page\n");
498 printf("number of sockets after %d\n", count($this->socks));
501 printf("WARNING: ancillary_getstream failed\n");
505 $buf = fread($sock, 512);
506 // if socket is closed
507 if ($buf == FALSE || strlen($buf) == 0) {
509 printf("ERROR READING\n");
511 if ($sock === $this->list) {
512 printf("Arrivati %d bytes da list\n", strlen($buf));
515 else if ($sock === $this->in) {
516 printf("Arrivati %d bytes da stdin\n", strlen($buf));
520 // $user_a[$s2u[intval($sock)]]->disable();
521 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
522 $this->s2u[intval($sock)]->rd_socket_set(NULL);
524 unset($this->socks[intval($sock)]);
525 unset($this->s2u[intval($sock)]);
528 printf("CLOSE ON READ\n");
530 if ($this->debug > 1) {
531 printf("post unset\n");
532 print_r($this->socks);
536 if ($this->debug > 1) {
539 if ($sock === $this->list) {
540 printf("Arrivati %d bytes da list\n", strlen($buf));
542 else if ($sock === $this->in) {
543 printf("Arrivati %d bytes da stdin\n", strlen($buf));
545 if ($line == "reload") {
546 require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
550 $key = array_search("$sock", $this->socks);
551 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
558 $this->garbage_manager(FALSE);
560 /* manage unfinished pages */
561 foreach ($this->pages_flush as $k => $pgflush) {
562 if ($pgflush->try_flush($this->curtime) == TRUE) {
563 unset($this->pages_flush[$k]);
568 $response: raw stream data not sent
569 $content: html consistent data (<script bla bla>)
570 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
573 /* manage open streaming */
574 foreach ($this->socks as $k => $sock) {
575 if (isset($this->s2u[intval($sock)])) {
576 $user = $this->s2u[intval($sock)];
577 $response = $user->rd_cache_get();
579 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
583 $user->ping_req = FALSE;
586 if ($response == "") {
588 $user->stream_main($content, $get, $post, $cookie);
589 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
590 if ($do_ping && $user->ping_req == FALSE) {
591 $content .= $user->stream_keepalive(TRUE);
592 $user->ping_req = TRUE;
594 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
595 $content = $user->stream_keepalive(FALSE);
597 if ($content != "") {
598 $response = chunked_content($user->rd_zls_get(), $content);
602 if ($response != "") {
603 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
604 echo "SPIA: [".$response."]\n";
605 $response_l = mb_strlen($response, "ASCII");
606 $wret = @fwrite($sock, $response);
607 if ($wret < $response_l) {
608 printf("TROUBLE WITH FWRITE: %d\n", $wret);
609 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
612 $user->rd_cache_set("");
615 $user->rd_kalive_reset($this->curtime);
618 // close socket after a while to prevent client memory consumption
619 if ($user->rd_endtime_is_expired($this->curtime)) {
620 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
621 $this->s2u[intval($sock)]->rd_socket_set(NULL);
623 unset($this->socks[intval($sock)]);
624 unset($this->s2u[intval($sock)]);
626 printf("CLOSE ON LOOP\n");
629 } // foreach ($this->socks...
632 } // function run(...