4 * brisk - spush/sac-a-push.phh
6 * Copyright (C) 2012 Matteo Nastasi
7 * mailto: nastasi@alternativeoutput.it
8 * matteo.nastasi@milug.org
9 * web: http://www.alternativeoutput.it
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details. You should have received a
20 * copy of the GNU General Public License along with this program; if
21 * not, write to the Free Software Foundation, Inc, 59 Temple Place -
22 * Suite 330, Boston, MA 02111-1307, USA.
26 define('SITE_PREFIX', '/brisk/');
27 define('SITE_PREFIX_LEN', 7);
29 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
35 foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
36 // printf("LINE: [%s]\n", $line);
38 if (!isset($header['The-Request'])) {
41 $req = explode(" ", $header['The-Request']);
44 if (isset($header['Cookie'])) {
45 $cookies = explode(";", $header['Cookie']);
46 for ($i = 0 ; $i < count($cookies) ; $i++) {
47 $nameval = explode("=", trim($cookies[$i]));
48 if (count($nameval) != 2) {
49 printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
52 $cookie[$nameval[0]] = urldecode($nameval[1]);
55 // GET params management
56 $get_vars = explode('?', $req[1], 2);
58 if (count($get_vars) > 1) {
59 $a = explode('&', $get_vars[1]);
60 printf("A COUNT: [%s] %d\n", $a[0], count($a));
61 for ($i = 0 ; $i < count($a) ; $i++) {
62 $b = explode('=', $a[$i]);
63 $get[$b[0]] = urldecode($b[1]);
66 // POST params management
67 if ($req[0] == 'POST') {
68 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
69 || !isset($header['Content-Length'])) {
72 $post_len = mb_strlen($line, "latin1");
73 $a = explode('&', $line);
74 for ($i = 0 ; $i < count($a) ; $i++) {
75 $b = explode('=', $a[$i]);
76 $post[$b[0]] = urldecode($b[1]);
78 printf("INFO: postlen: %d\n", $post_len);
86 $split = explode(":", $line, 2);
87 $header[$split[0]] = $split[1];
92 function gpcs_var($name, $get, $post, $cookie)
94 if (isset($GLOBALS[$name]))
96 else if (isset($cookie[$name]))
97 return ($cookie[$name]);
98 else if (isset($post[$name]))
99 return ($post[$name]);
100 else if (isset($get[$name]))
101 return ($get[$name]);
106 function headers_render($header, $len)
109 if (isset($header['Location'])) {
110 return sprintf("HTTP/1.1 302 OK\r\nLocation: %s\r\n\r\n", $header['Location']);
113 $s .= "HTTP/1.1 200 OK\r\n";
115 if (!isset($header['Date']))
116 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
117 if (!isset($header['Connection']))
118 $s .= "Connection: close\r\n";
119 if (!isset($header['Content-Type']))
120 $s .= "Content-Type: text/html\r\n";
121 foreach($header as $key => $value) {
122 $s .= sprintf("%s: %s\r\n", $key, $value);
125 $s .= sprintf("Content-Length: %d\r\n", $len);
128 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
129 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
130 if (!isset($header['Content-Encoding'])) {
131 $s .= "Content-Encoding: chunked\r\n";
133 $s .= "Transfer-Encoding: chunked\r\n";
141 * Caching system using ob php system to cache old style pages
142 * to a var and than send it with more calm
147 log_rd2("SHUTTA [".connection_status()."] !");
150 register_shutdown_function('shutta');
156 function chunked_content($zls, $content)
159 $cont_comp = $zls->compress_chunk($content);
162 $cont_comp = $content;
164 $cont_comp_l = mb_strlen($cont_comp, "ASCII");
165 printf("CHUNK: [%s]\n", $content);
167 return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
170 function chunked_fini()
172 return sprintf("0\r\n");
175 function get_encoding($header)
178 if (isset($header['Accept-Encoding'])) {
179 $acc = explode(',', $header['Accept-Encoding']);
181 if (array_search('gzip', $acc) !== FALSE) {
184 else if (array_search('deflate', $acc) !== FALSE) {
194 static $fixed_fd = 2;
216 function Sac_a_push()
220 // Sac_a_push::create("/tmp/brisk.sock", 0, 0
222 static function create(&$app, $sockname, $debug, $blocking_mode)
224 $thiz = new Sac_a_push();
227 $thiz->file_socket = $sockname;
228 $thiz->unix_socket = "unix://$sockname";
229 $thiz->debug = $debug;
230 $thiz->socks = array();
231 $thiz->s2u = array();
232 $thiz->pages_flush = array();
234 $thiz->blocking_mode = 0; // 0 for non-blocking
237 for ($i = 0 ; $i < 4096 ; $i++) {
239 $thiz->rndstr .= "\n";
241 $thiz->rndstr .= chr(mt_rand(65, 90));
244 if (file_exists($thiz->file_socket)) {
245 unlink($thiz->file_socket);
248 $old_umask = umask(0);
249 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
253 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
255 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
259 $thiz->main_loop = FALSE;
264 function socks_set($sock, $user)
268 $this->s2u[$id] = $user;
269 $this->socks[$id] = $sock;
272 function socks_unset($sock)
276 unset($this->s2u[$id]);
277 unset($this->socks[$id]);
280 function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
282 $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
284 if ($pgflush->try_flush($this->curtime) == FALSE) {
285 // Add $pgflush to the pgflush array
286 $this->pgflush_add($pgflush);
290 function pgflush_add($pgflush)
292 array_push($this->pages_flush, $pgflush);
295 function garbage_manager($force)
297 $this->app->garbage_manager($force);
299 foreach ($this->socks as $k => $sock) {
300 if ($this->s2u[intval($sock)]->sess == '') {
301 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
302 $this->s2u[intval($sock)]->rd_socket_set(NULL);
304 unset($this->socks[intval($sock)]);
305 unset($this->s2u[intval($sock)]);
307 printf("CLOSE ON GARBAGE MANAGER\n");
314 if ($this->main_loop) {
318 $this->main_loop = TRUE;
320 while ($this->main_loop) {
321 $this->curtime = time();
322 printf("IN LOOP: Current opened: %d pages_flush: %d - ", count($this->socks), count($this->pages_flush));
324 /* Prepare the read array */
325 /* // when we manage it ... */
327 /* $read = array_merge(array("$in" => $in), $socks); */
329 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
332 if ($this->debug > 1) {
333 printf("PRE_SELECT\n");
338 $num_changed_sockets = stream_select($read, $write, $except, 0, 500000);
340 if ($num_changed_sockets == 0) {
341 printf(" no data in 5 secs ");
343 else if ($num_changed_sockets > 0) {
344 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
345 if ($this->debug > 1) {
348 /* At least at one of the sockets something interesting happened */
349 foreach ($read as $i => $sock) {
350 /* is_resource check is required because there is the possibility that
351 during new request an old connection is closed */
352 if (!is_resource($sock)) {
355 if ($sock === $this->list) {
356 printf("NUOVA CONNEX\n");
357 if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
358 printf("SOCKET_ACCEPT FAILED\n");
366 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
367 printf("NEW_SOCKET: %d\n", intval($new_socket));
368 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
369 printf("RECEIVED HEADER:\n%s", $stream_info);
370 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
371 printf("PATH: [%s]\n", $path);
372 printf("M: %s\nHEADER:\n", $method);
381 $addr = stream_socket_get_name($new_socket, TRUE);
382 $header_out = array();
384 $enc = get_encoding($header);
386 $subs = SITE_PREFIX."briskin5/";
387 $subs_l = strlen($subs);
389 if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
390 $rret = $this->app->request_mgr($this, $enc, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
392 if ($rret == FALSE) {
393 // FIXME: manage 404 !!!
394 printf("TODO: fix unknown page\n");
396 printf("number of sockets after %d\n", count($this->socks));
399 printf("WARNING: ancillary_getstream failed\n");
403 $buf = fread($sock, 512);
404 if ($buf == FALSE || strlen($buf) == 0) {
406 printf("ERROR READING\n");
408 if ($sock === $this->list) {
409 printf("Arrivati %d bytes da list\n", strlen($buf));
412 else if ($sock === $this->in) {
413 printf("Arrivati %d bytes da stdin\n", strlen($buf));
417 // $user_a[$s2u[intval($sock)]]->disable();
418 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
419 $this->s2u[intval($sock)]->rd_socket_set(NULL);
421 unset($this->socks[intval($sock)]);
422 unset($this->s2u[intval($sock)]);
425 printf("CLOSE ON READ\n");
427 if ($this->debug > 1) {
428 printf("post unset\n");
429 print_r($this->socks);
433 if ($this->debug > 1) {
436 if ($sock === $this->list) {
437 printf("Arrivati %d bytes da list\n", strlen($buf));
439 else if ($sock === $this->in) {
440 printf("Arrivati %d bytes da stdin\n", strlen($buf));
443 $key = array_search("$sock", $this->socks);
444 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
451 $this->garbage_manager(FALSE);
453 /* manage unfinished pages */
454 foreach ($this->pages_flush as $k => $pgflush) {
455 if ($pgflush->try_flush($this->curtime) == TRUE) {
456 unset($this->pages_flush[$k]);
461 $response: raw stream data not sent
462 $content: html consistent data (<script bla bla>)
463 $user->stream_keepalive($w_ping) ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
466 /* manage open streaming */
467 foreach ($this->socks as $k => $sock) {
468 if (isset($this->s2u[intval($sock)])) {
469 $user = $this->s2u[intval($sock)];
470 $response = $user->rd_cache_get();
472 if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
476 $user->ping_req = FALSE;
479 if ($response == "") {
481 $user->stream_main($content, $get, $post, $cookie);
482 printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
483 if ($do_ping && $user->ping_req == FALSE) {
484 $content .= $user->stream_keepalive(TRUE);
485 $user->ping_req = TRUE;
487 else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
488 $content = $user->stream_keepalive(FALSE);
490 if ($content != "") {
491 $response = chunked_content($user->rd_zls_get(), $content);
495 if ($response != "") {
496 // echo "SPIA: [".substr($response, 0, 60)."...]\n";
497 echo "SPIA: [".$response."]\n";
498 $response_l = mb_strlen($response, "ASCII");
499 $wret = @fwrite($sock, $response);
500 if ($wret < $response_l) {
501 printf("TROUBLE WITH FWRITE: %d\n", $wret);
502 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
505 $user->rd_cache_set("");
508 $user->rd_kalive_reset($this->curtime);
511 // close socket after a while to prevent client memory consumption
512 if ($user->rd_endtime_is_expired($this->curtime)) {
513 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
514 $this->s2u[intval($sock)]->rd_socket_set(NULL);
516 unset($this->socks[intval($sock)]);
517 unset($this->s2u[intval($sock)]);
519 printf("CLOSE ON LOOP\n");
522 } // foreach ($this->socks...
525 } // function run(...