server-side ping management fixed
[brisk.git] / web / Obj / sac-a-push.phh
1 <?php
2
3 /*
4  *  brisk - spush/sac-a-push.phh
5  *
6  *  Copyright (C) 2012 Matteo Nastasi
7  *                          mailto: nastasi@alternativeoutput.it 
8  *                                  matteo.nastasi@milug.org
9  *                          web: http://www.alternativeoutput.it
10  *
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.
15  *
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.
23  *
24  */
25
26 define('SITE_PREFIX', '/brisk/');
27 define('SITE_PREFIX_LEN', 7);
28
29 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
30 {
31     $check_post = FALSE;
32     $header = array();
33     $get = array();
34     $post = array();
35     foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
36         // printf("LINE: [%s]\n", $line);
37         if ($check_post) {
38             if (!isset($header['The-Request'])) {
39                 return FALSE;
40             }
41             $req = explode(" ", $header['The-Request']);
42             $method = $req[0];
43
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]);
50                         continue;
51                     }
52                     $cookie[$nameval[0]] = urldecode($nameval[1]);
53                 }
54             }
55             // GET params management
56             $get_vars = explode('?', $req[1], 2);
57             $path =   $get_vars[0];
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]);
64                 }
65             }
66             // POST params management
67             if ($req[0] == 'POST') {
68                 if ($header['Content-Type'] != 'application/x-www-form-urlencoded' 
69                     || !isset($header['Content-Length'])) {
70                     return FALSE;
71                 }
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]);
77                 }
78                 printf("INFO: postlen: %d\n", $post_len);
79             }
80             break;
81         }
82         if ($line == "") {
83             $check_post = TRUE;
84             continue;
85         }
86         $split = explode(":", $line, 2);
87         $header[$split[0]] = $split[1];        
88     }
89     return $path;
90 }
91
92 function gpcs_var($name, $get, $post, $cookie)
93 {
94     if (isset($GLOBALS[$name])) 
95         return FALSE;
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]);
102
103     return FALSE;
104 }
105
106 function headers_render($header, $len)
107 {
108     $s = "";
109     if (isset($header['Location'])) {
110         return sprintf("HTTP/1.1 302 OK\r\nLocation: %s\r\n\r\n", $header['Location']);
111     }
112     else {
113         $s .= "HTTP/1.1 200 OK\r\n";
114     }
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);
123     }
124     if ($len == -1) {
125         $s .= "Cache-Control: no-cache, must-revalidate\r\n";
126         $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
127         $s .= "Content-Encoding: chunked\r\n";
128         $s .= "Transfer-Encoding: chunked\r\n";
129     }
130     else if ($len > 0) {
131         $s .= sprintf("Content-Length: %d\r\n", $len);
132     }
133     $s .= "\r\n";
134
135     return ($s);
136 }
137
138 /*
139  *  Caching system using ob php system to cache old style pages
140  *  to a var and than send it with more calm
141  */
142
143 function shutta()
144 {
145   log_rd2("SHUTTA [".connection_status()."] !");
146 }
147
148 register_shutdown_function('shutta');
149
150 /*
151  *  MAIN
152  */
153
154 function chunked_content($content)
155 {
156     $content_l = mb_strlen($content, "ASCII");
157
158     return (sprintf("%X\r\n%s\r\n", $content_l, $content));
159 }
160
161 function chunked_fini()
162 {
163     return sprintf("0\r\n");
164 }
165
166 class Sac_a_push {
167     static $fixed_fd = 2;
168     
169     var $file_socket;
170     var $unix_socket;
171     var $socks;
172     var $s2u;
173     var $pages_flush;
174
175     var $list;
176     var $in;
177
178     var $debug;
179     var $blocking_mode;
180
181     var $app;
182     var $bin5;
183
184     var $curtime;
185
186     var $rndstr;
187     var $main_loop;
188
189     function Sac_a_push()
190     {
191     }
192
193     // Sac_a_push::create("/tmp/brisk.sock", 0, 0
194
195     static function create(&$app, $sockname, $debug, $blocking_mode)
196     {        
197         $thiz = new Sac_a_push();
198         
199         $thiz->app = $app;
200         $thiz->file_socket = $sockname;
201         $thiz->unix_socket = "unix://$sockname";
202         $thiz->debug = $debug;
203         $thiz->socks = array();
204         $thiz->s2u  = array();
205         $thiz->pages_flush = array();
206
207         $thiz->blocking_mode = 0; // 0 for non-blocking
208
209         $thiz->rndstr = "";
210         for ($i = 0 ; $i < 4096 ; $i++) {
211             $thiz->rndstr .= chr(mt_rand(65, 90));
212         }
213         
214         if (file_exists($thiz->file_socket)) {
215             unlink($thiz->file_socket);
216         }
217     
218         $old_umask = umask(0);
219         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
220             return (FALSE);
221         }
222         umask($old_umask);
223         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
224
225         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
226             return(FALSE);
227         }
228
229         $thiz->main_loop = FALSE;
230
231         return ($thiz);
232     }
233
234     function socks_set($sock, $user)
235     {
236         $id = intval($sock);
237
238         $this->s2u[$id]   = $user;
239         $this->socks[$id] = $sock;
240     }
241
242     function socks_unset($sock)
243     {
244         $id = intval($sock);
245
246         unset($this->s2u[$id]);
247         unset($this->socks[$id]);
248     }
249
250     function pgflush_try_add(&$new_socket, $tout, $header_out, $content)
251     {
252         $pgflush = new PageFlush($new_socket, $this->curtime, $tout, $header_out, $content);
253
254         if ($pgflush->try_flush($this->curtime) == FALSE) {
255             // Add $pgflush to the pgflush array
256             $this->pgflush_add($pgflush);
257         }
258     }
259
260     function pgflush_add($pgflush)
261     {
262         array_push($this->pages_flush, $pgflush);
263     }
264
265     function run()
266     {
267         if ($this->main_loop) {
268             return (FALSE);
269         }
270         
271         $this->main_loop = TRUE;
272         
273         while ($this->main_loop) {
274             $this->curtime = time();
275             printf("IN LOOP: Current opened: %d  pages_flush: %d - ", count($this->socks), count($this->pages_flush));
276             
277             /* Prepare the read array */
278             /* // when we manage it ... */
279             /* if ($shutdown)  */
280             /*     $read   = array_merge(array("$in" => $in), $socks); */
281             /* else */
282             $read   = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
283                                   $this->socks);
284             
285             if ($this->debug > 1) {
286                 printf("PRE_SELECT\n");
287                 print_r($read);
288             }
289             $write  = NULL;
290             $except = NULL;
291             $num_changed_sockets = stream_select($read, $write, $except, 5, 0);
292         
293             if ($num_changed_sockets == 0) {
294                 printf(" no data in 5 secs ");
295             } 
296             else if ($num_changed_sockets > 0) {
297                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
298                 if ($this->debug > 1) {
299                     print_r($read);
300                 }
301                 /* At least at one of the sockets something interesting happened */
302                 foreach ($read as $i => $sock) {
303                     /* is_resource check is required because there is the possibility that
304                        during new request an old connection is closed */
305                     if (!is_resource($sock)) {
306                         continue;
307                     }
308                     if ($sock === $this->list) {
309                         printf("NUOVA CONNEX\n");
310                         $new_unix = stream_socket_accept($this->list);
311                         $stream_info = "";
312                         $method      = "";
313                         $get         = array();
314                         $post        = array();
315                         $cookie      = array();
316                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
317                             printf("NEW_SOCKET: %d\n", intval($new_socket));
318                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
319                             printf("RECEIVED HEADER:\n%s", $stream_info);
320                             $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
321                             printf("PATH: [%s]\n", $path);
322                             printf("M: %s\nHEADER:\n", $method);
323                             print_r($header);
324                             printf("GET:\n");
325                             print_r($get);
326                             printf("POST:\n");
327                             print_r($post);
328                             printf("COOKIE:\n");
329                             print_r($cookie);
330
331                             $addr = stream_socket_get_name($new_socket, TRUE);
332                             $header_out = array();
333
334                             $subs = SITE_PREFIX."briskin5/";
335                             $subs_l = strlen($subs);
336                             $rret = FALSE;
337                             if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
338                                 $rret = $this->app->request_mgr($this, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
339                             }
340                             if ($rret == FALSE) { 
341                                 // FIXME: manage 404 !!!
342                                 printf("TODO: fix unknown page\n");
343                             }
344                             printf("number of sockets after %d\n", count($this->socks));
345                         }
346                         else {
347                             printf("WARNING: ancillary_getstream failed\n");
348                         }
349                     }
350                     else {
351                         if (($buf = fread($sock, 512)) === FALSE) {
352                             printf("error read\n");
353                         }
354                         else if (strlen($buf) === 0) {
355                             if ($sock === $this->list) {
356                                 printf("Arrivati %d bytes da list\n", strlen($buf));
357                             }
358                             else if ($sock === $this->in) {
359                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
360                             }
361                             else {
362                                 // $user_a[$s2u[intval($sock)]]->disable();
363                                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
364                                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
365                                 }
366                                 unset($this->socks[intval($sock)]);
367                                 unset($this->s2u[intval($sock)]);
368                                 fclose($sock);
369                                 printf("CLOSE ON READ\n");
370                             }
371                             if ($this->debug > 1) {
372                                 printf("post unset\n");
373                                 print_r($this->socks);
374                             }
375                         }
376                         else {
377                             if ($this->debug > 1) {
378                                 print_r($read);
379                             }
380                             if ($sock === $this->list) {
381                                 printf("Arrivati %d bytes da list\n", strlen($buf));
382                             }
383                             else if ($sock === $this->in) {
384                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
385                             }
386                             else {
387                                 $key = array_search("$sock", $this->socks);
388                                 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
389                             }
390                         }
391                     }
392                 }
393             }
394             
395
396             $this->app->garbage_manager(FALSE);
397
398
399             /* manage unfinished pages */
400             foreach ($this->pages_flush as $k => $pgflush) {
401                 if ($pgflush->try_flush($this->curtime) == TRUE) {
402                     unset($this->pages_flush[$k]);
403                 }
404             }
405             
406             /*
407                $response:                        raw stream data not sent
408                $content:                         html consistent data (<script bla bla>)
409                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
410             */
411
412             /* manage open streaming */
413             foreach ($this->socks as $k => $sock) {
414                 if (isset($this->s2u[intval($sock)])) {
415                     $user = $this->s2u[intval($sock)];
416                     $response = $user->rd_cache_get();
417                     if (($this->curtime - $user->lacc) <= (EXPIRE_TIME_RD / 2)) {
418                         $user->ping_req = FALSE;
419                     }
420                     if ($response == "") {
421                         $content = "";
422                         $user->stream_main($content, $get, $post, $cookie);
423                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
424                         if ($user->ping_req == FALSE
425                             && (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 2))) {
426                             $content .= $user->stream_keepalive(TRUE);
427                             $user->ping_req = TRUE;
428                         }
429                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
430                             $content = $user->stream_keepalive(FALSE);
431                         }
432                         if ($content != "") {
433                             $response = chunked_content($content);
434                         }
435                     }
436                     
437                     if ($response != "") {
438                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
439                         echo "SPIA: [".$response."...]\n";
440                         $response_l = mb_strlen($response, "ASCII");
441                         $wret = @fwrite($sock, $response);
442                         if ($wret < $response_l) {
443                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
444                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
445                         }
446                         else {
447                             $user->rd_cache_set("");
448                         }
449                         fflush($sock);
450                         $user->rd_kalive_reset($this->curtime);
451                     }
452                     
453                     // close socket after a while to prevent client memory consumption
454                     if ($user->rd_endtime_is_expired($this->curtime)) {
455                         if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
456                             $this->s2u[intval($sock)]->rd_socket_set(NULL);
457                         }
458                         unset($this->socks[intval($sock)]);
459                         unset($this->s2u[intval($sock)]);
460                         fclose($sock);
461                         printf("CLOSE ON LOOP\n");
462                     }
463                 }
464             }  // foreach ($this->socks...
465             printf("\n");
466         }  // while (...
467     }  // function run(...
468 }
469
470 ?>