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/');
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 $s .= "HTTP/1.1 200 OK\r\n";
110 if (!isset($header['Date']))
111 $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
112 if (!isset($header['Connection']))
113 $s .= "Connection: close\r\n";
114 if (!isset($header['Content-Type']))
115 $s .= "Content-Type: text/html\r\n";
116 foreach($header as $key => $value) {
117 $s .= sprintf("%s: %s\r\n", $key, $value);
120 $s .= "Cache-Control: no-cache, must-revalidate\r\n";
121 $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
122 $s .= "Content-Encoding: chunked\r\n";
123 $s .= "Transfer-Encoding: chunked\r\n";
126 $s .= sprintf("Content-Length: %d\r\n", $len);
134 * Caching system using ob php system to cache old style pages
135 * to a var and than send it with more calm
140 log_rd2("SHUTTA [".connection_status()."] !");
143 register_shutdown_function('shutta');
149 function chunked_content($content)
151 $content_l = mb_strlen($content, "ASCII");
153 return (sprintf("%X\r\n%s\r\n", $content_l, $content));
156 function chunked_fini()
158 return sprintf("0\r\n");
162 static $fixed_fd = 2;
184 function Sac_a_push()
188 // Sac_a_push::create("/tmp/brisk.sock", 0, 0
190 static function create(&$app, $sockname, $debug, $blocking_mode)
192 $thiz = new Sac_a_push();
195 $thiz->file_socket = $sockname;
196 $thiz->unix_socket = "unix://$sockname";
197 $thiz->debug = $debug;
198 $thiz->socks = array();
199 $thiz->s2u = array();
200 $thiz->pages_flush = array();
202 $thiz->blocking_mode = 0; // 0 for non-blocking
205 for ($i = 0 ; $i < 4096 ; $i++) {
206 $thiz->rndstr .= chr(mt_rand(65, 90));
209 if (file_exists($thiz->file_socket)) {
210 unlink($thiz->file_socket);
213 $old_umask = umask(0);
214 if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
218 stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
220 if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
224 $thiz->main_loop = FALSE;
229 function socks_set($sock, $user)
233 $this->s2u[$id] = $user;
234 $this->socks[$id] = $sock;
237 function socks_unset($sock)
241 unset($this->s2u[$id]);
242 unset($this->socks[$id]);
245 function pgflush_try_add(&$new_socket, $tout, $header_out, $content)
247 $pgflush = new PageFlush($new_socket, $this->curtime, $tout, $header_out, $content);
249 if ($pgflush->try_flush($this->curtime) == FALSE) {
250 // Add $pgflush to the pgflush array
251 $this->pgflush_add($pgflush);
255 function pgflush_add($pgflush)
257 array_push($this->pages_flush, $pgflush);
262 if ($this->main_loop) {
266 $this->main_loop = TRUE;
268 while ($this->main_loop) {
269 $this->curtime = time();
270 printf("IN LOOP: Current opened: %d pages_flush: %d - ", count($this->socks), count($this->pages_flush));
272 /* Prepare the read array */
273 /* // when we manage it ... */
275 /* $read = array_merge(array("$in" => $in), $socks); */
277 $read = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
280 if ($this->debug > 1) {
281 printf("PRE_SELECT\n");
286 $num_changed_sockets = stream_select($read, $write, $except, 0, 250000);
288 if ($num_changed_sockets == 0) {
289 printf(" no data in 5 secs ");
291 else if ($num_changed_sockets > 0) {
292 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
293 if ($this->debug > 1) {
296 /* At least at one of the sockets something interesting happened */
297 foreach ($read as $i => $sock) {
298 /* is_resource check is required because there is the possibility that
299 during new request an old connection is closed */
300 if (!is_resource($sock)) {
303 if ($sock === $this->list) {
304 printf("NUOVA CONNEX\n");
305 $new_unix = stream_socket_accept($this->list);
311 if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
312 printf("NEW_SOCKET: %d\n", intval($new_socket));
313 stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
314 printf("RECEIVED HEADER:\n%s", $stream_info);
315 $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
316 printf("PATH: [%s]\n", $path);
317 printf("M: %s\nHEADER:\n", $method);
326 $addr = stream_socket_get_name($new_socket, TRUE);
327 $header_out = array();
329 $this->app->request_mgr($this, $header_out, $new_socket, $path, $addr, $get, $post, $cookie);
330 printf("number of sockets after %d\n", count($this->socks));
333 printf("WARNING: ancillary_getstream failed\n");
337 if (($buf = fread($sock, 512)) === FALSE) {
338 printf("error read\n");
341 else if (strlen($buf) === 0) {
342 if ($sock === $this->list) {
343 printf("Arrivati %d bytes da list\n", strlen($buf));
345 else if ($sock === $this->in) {
346 printf("Arrivati %d bytes da stdin\n", strlen($buf));
349 // $user_a[$s2u[intval($sock)]]->disable();
350 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
351 $this->s2u[intval($sock)]->rd_socket_set(NULL);
353 unset($this->socks[intval($sock)]);
354 unset($this->s2u[intval($sock)]);
356 printf("CLOSE ON READ\n");
358 if ($this->debug > 1) {
359 printf("post unset\n");
360 print_r($this->socks);
367 if ($sock === $this->list) {
368 printf("Arrivati %d bytes da list\n", strlen($buf));
370 else if ($sock === $this->in) {
371 printf("Arrivati %d bytes da stdin\n", strlen($buf));
374 $key = array_search("$sock", $this->socks);
375 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
383 /* manage unfinished pages */
384 foreach ($this->pages_flush as $k => $pgflush) {
385 if ($pgflush->try_flush($this->curtime) == TRUE) {
386 unset($this->pages_flush[$k]);
390 /* manage open streaming */
391 foreach ($this->socks as $k => $sock) {
392 if (isset($this->s2u[intval($sock)])) {
393 $user = $this->s2u[intval($sock)];
394 $response = $user->rd_cache_get();
395 if ($response == "") {
397 $user->stream_main($content, $get, $post, $cookie);
399 if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
400 $content = $user->stream_keepalive();
402 if ($content != "") {
403 $response = chunked_content($content);
407 if ($response != "") {
408 echo "SPIA: [".substr($response, 0, 60)."...]\n";
409 $response_l = mb_strlen($response, "ASCII");
410 $wret = @fwrite($sock, $response);
411 if ($wret < $response_l) {
412 printf("TROUBLE WITH FWRITE: %d\n", $wret);
413 $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
416 $user->rd_cache_set("");
419 $user->rd_kalive_reset($this->curtime);
422 // close socket after a while to prevent client memory consumption
423 if ($user->rd_endtime_is_expired($this->curtime)) {
424 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
425 $this->s2u[intval($sock)]->rd_socket_set(NULL);
427 unset($this->socks[intval($sock)]);
428 unset($this->s2u[intval($sock)]);
430 printf("CLOSE ON LOOP\n");
433 } // foreach ($this->socks...
436 } // function run(...