84f155527f34b5e97130bc13e10e2fa1325c7148
[brisk.git] / web / Obj / sac-a-push.phh
1 <?php
2 /*
3  *  brisk - spush/sac-a-push.phh
4  *
5  *  Copyright (C) 2012 Matteo Nastasi
6  *                          mailto: nastasi@alternativeoutput.it 
7  *                                  matteo.nastasi@milug.org
8  *                          web: http://www.alternativeoutput.it
9  *
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.
14  *
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.
22  *
23  */
24
25 define('SITE_PREFIX', '/brisk/');
26 define('SITE_PREFIX_LEN', 7);
27
28 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
29 {
30     $check_post = FALSE;
31     $header = array();
32     $get = array();
33     $post = array();
34     foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
35         // printf("LINE: [%s]\n", $line);
36         if ($check_post) {
37             if (!isset($header['The-Request'])) {
38                 return FALSE;
39             }
40             $req = explode(" ", $header['The-Request']);
41             $method = $req[0];
42
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]);
49                         continue;
50                     }
51                     $cookie[$nameval[0]] = urldecode($nameval[1]);
52                 }
53             }
54             // GET params management
55             $get_vars = explode('?', $req[1], 2);
56             $path =   $get_vars[0];
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]);
63                 }
64             }
65             // POST params management
66             if ($req[0] == 'POST') {
67                 if ($header['Content-Type'] != 'application/x-www-form-urlencoded' 
68                     || !isset($header['Content-Length'])) {
69                     return FALSE;
70                 }
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]);
76                 }
77                 printf("INFO: postlen: %d\n", $post_len);
78             }
79             break;
80         }
81         if ($line == "") {
82             $check_post = TRUE;
83             continue;
84         }
85         $split = explode(":", $line, 2);
86         $header[$split[0]] = $split[1];        
87     }
88     return $path;
89 }
90
91 function gpcs_var($name, $get, $post, $cookie)
92 {
93     if (isset($GLOBALS[$name])) 
94         return FALSE;
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]);
101
102     return FALSE;
103 }
104
105 function headers_render($header, $len)
106 {
107     $cookies = "";
108
109     if (isset($header['cookies'])) {
110         $cookies = $header['cookies']->render();
111         unset($header['cookies']);
112     }
113     if (isset($header['Location'])) {
114         $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
115     }
116     else {
117         $s = "HTTP/1.1 200 OK\r\n";
118
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);
127         }
128         if ($len >= 0) {
129             $s .= sprintf("Content-Length: %d\r\n", $len);
130         }
131         else {
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";
136             }
137             $s .= "Transfer-Encoding: chunked\r\n";
138         }
139         $s .= $cookies;
140     }
141     $s .= "\r\n";
142
143     return ($s);
144 }
145
146 /*
147  *  Caching system using ob php system to cache old style pages
148  *  to a var and than send it with more calm
149  */
150
151 function shutta()
152 {
153   log_rd2("SHUTTA [".connection_status()."] !");
154 }
155
156 register_shutdown_function('shutta');
157
158 /*
159  *  MAIN
160  */
161
162 function chunked_content($zls, $content)
163 {
164     if ($zls) {
165         $cont_comp = $zls->compress_chunk($content);
166     }
167     else {
168         $cont_comp = $content;
169     }
170     $cont_comp_l = mb_strlen($cont_comp, "ASCII");
171     printf("CHUNK: [%s]\n", $content);
172
173     return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
174 }
175
176 function chunked_fini()
177 {
178     return sprintf("0\r\n");
179 }
180
181 function get_encoding($header)
182 {
183     $enc = "plain";
184     if (isset($header['Accept-Encoding'])) {
185         $acc = explode(',', $header['Accept-Encoding']);
186
187         if (array_search('gzip', $acc) !== FALSE) {
188             $enc = 'gzip';
189         }
190         else if (array_search('deflate', $acc) !== FALSE) {
191             $enc = 'deflate';
192         }
193     }
194
195     return ($enc);
196 }
197
198 class Cookie {
199     var $attr;
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  ]]]]]] )
202     function Cookie()
203     {
204         $this->attr = array();
205     }
206
207     static function create($name)
208     {
209         $thiz = new Cookie();
210
211         $thiz->attr[$name] = "";
212
213         $argc = func_num_args();
214         for ($i = 1 ; $i < $argc ; $i++) {
215             $arg = func_get_arg($i);
216             switch ($i) {
217             case 1:
218                 $thiz->attr[$name] = urlencode($arg);
219                 break;
220             case 2:
221                 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
222                 break;
223             case 3:
224                 $thiz->attr['Path'] = $arg;
225                 break;
226             case 4:
227                 $thiz->attr['Domain'] = $arg;
228                 break;
229             case 5:
230                 if ($arg == TRUE) {
231                     $thiz->attr['Secure'] = NULL;
232                 }
233                 break;
234             case 6:
235                 if ($arg == TRUE) {
236                     $thiz->attr['HttpOnly'] = NULL;
237                 }
238                 break;
239             default:
240                 return FALSE;
241             }
242         }
243
244         return $thiz;
245     }
246
247     function render()
248     {
249         $r = "Set-Cookie: ";
250         $isfirst = TRUE;
251
252         foreach ($this->attr as $k => $v) {
253             if ($v == NULL) {
254                 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
255             }
256             else {
257                 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
258             }
259             $isfirst = FALSE;
260         }
261         $r .= "\r\n";
262
263         return $r;
264     }
265 }
266
267 class Cookies {
268     var $cookies;
269
270     function Cookies()
271     {
272         $this->cookies = array();
273     }
274
275     function add($name)
276     {
277         if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
278             return (FALSE);
279
280         array_push($this->cookies, $cookie);
281
282         return (TRUE);
283     }
284
285     function render()
286     {
287         $r = "";
288         foreach ($this->cookies as $cookie) {
289             $r .= $cookie->render();
290         }
291
292         return ($r);
293     }
294 }
295
296
297 class Sac_a_push {
298     static $fixed_fd = 2;
299     
300     var $file_socket;
301     var $unix_socket;
302     var $socks;
303     var $s2u;
304     var $pages_flush;
305
306     var $list;
307     var $in;
308
309     var $debug;
310     var $blocking_mode;
311
312     var $app;
313
314     var $curtime;
315
316     var $rndstr;
317     var $main_loop;
318
319     function Sac_a_push()
320     {
321     }
322
323     // Sac_a_push::create("/tmp/brisk.sock", 0, 0
324
325     static function create(&$app, $sockname, $debug, $blocking_mode)
326     {        
327         $thiz = new Sac_a_push();
328         
329         $thiz->app = $app;
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();
336
337         $thiz->blocking_mode = 0; // 0 for non-blocking
338
339         $thiz->rndstr = "";
340         for ($i = 0 ; $i < 4096 ; $i++) {
341             if (($i % 128) == 0)
342                 $thiz->rndstr .= " ";
343             else
344                 $thiz->rndstr .= chr(mt_rand(65, 90));
345         }
346         
347         if (file_exists($thiz->file_socket)) {
348             unlink($thiz->file_socket);
349         }
350     
351         $old_umask = umask(0);
352         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
353             return (FALSE);
354         }
355         umask($old_umask);
356         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
357
358         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
359             return(FALSE);
360         }
361
362         $thiz->main_loop = FALSE;
363
364         return ($thiz);
365     }
366
367     function socks_set($sock, $user)
368     {
369         $id = intval($sock);
370
371         $this->s2u[$id]   = $user;
372         $this->socks[$id] = $sock;
373     }
374
375     function socks_unset($sock)
376     {
377         $id = intval($sock);
378
379         unset($this->s2u[$id]);
380         unset($this->socks[$id]);
381     }
382
383     function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
384     {
385         $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
386
387         if ($pgflush->try_flush($this->curtime) == FALSE) {
388             // Add $pgflush to the pgflush array
389             $this->pgflush_add($pgflush);
390         }
391     }
392
393     function pgflush_add($pgflush)
394     {
395         array_push($this->pages_flush, $pgflush);
396     }
397
398     function garbage_manager($force)
399     {
400         $this->app->garbage_manager($force);
401
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);
406                 }
407                 unset($this->socks[intval($sock)]);
408                 unset($this->s2u[intval($sock)]);
409                 fclose($sock);
410                 printf("CLOSE ON GARBAGE MANAGER\n");
411             }
412         }
413     }
414
415     function run()
416     {
417         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST, $G_with_splash, $G_black_list;
418
419         if ($this->main_loop) {
420             return (FALSE);
421         }
422         
423         $this->main_loop = TRUE;
424         
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));
428             
429             /* Prepare the read array */
430             /* // when we manage it ... */
431             /* if ($shutdown)  */
432             /*     $read   = array_merge(array("$in" => $in), $socks); */
433             /* else */
434             $read   = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
435                                   $this->socks);
436             
437             if ($this->debug > 1) {
438                 printf("PRE_SELECT\n");
439                 print_r($read);
440             }
441             $write  = NULL;
442             $except = NULL;
443             $num_changed_sockets = stream_select($read, $write, $except, 0, 500000);
444         
445             if ($num_changed_sockets == 0) {
446                 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
447             } 
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) {
451                     print_r($read);
452                 }
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)) {
458                         continue;
459                     }
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");
464                             continue;
465                         }
466                         $stream_info = "";
467                         $method      = "";
468                         $get         = array();
469                         $post        = array();
470                         $cookie      = array();
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);
478                             print_r($header);
479                             printf("GET:\n");
480                             print_r($get);
481                             printf("POST:\n");
482                             print_r($post);
483                             printf("COOKIE:\n");
484                             print_r($cookie);
485                             $addr = stream_socket_get_name($new_socket, TRUE);
486                             $header_out = array();
487
488                             $subs = SITE_PREFIX."briskin5/";
489                             $subs_l = strlen($subs);
490                             $rret = FALSE;
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);
493                             }
494                             if ($rret == FALSE) { 
495                                 // FIXME: manage 404 !!!
496                                 printf("TODO: fix unknown page\n");
497                             }
498                             printf("number of sockets after %d\n", count($this->socks));
499                         }
500                         else {
501                             printf("WARNING: ancillary_getstream failed\n");
502                         }
503                     }
504                     else {
505                         $buf = fread($sock, 512);
506                         // if socket is closed
507                         if ($buf == FALSE || strlen($buf) == 0) {
508                             if ($buf == FALSE) {
509                                 printf("ERROR READING\n");
510                             }
511                             if ($sock === $this->list) {
512                                 printf("Arrivati %d bytes da list\n", strlen($buf));
513                                 exit(21);
514                             }
515                             else if ($sock === $this->in) {
516                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
517                                 exit(22);
518                             }
519                             else {
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);
523                                 }
524                                 unset($this->socks[intval($sock)]);
525                                 unset($this->s2u[intval($sock)]);
526                             }
527                             fclose($sock);
528                             printf("CLOSE ON READ\n");
529
530                             if ($this->debug > 1) {
531                                 printf("post unset\n");
532                                 print_r($this->socks);
533                             }
534                         }
535                         else {
536                             if ($this->debug > 1) {
537                                 print_r($read);
538                             }
539                             if ($sock === $this->list) {
540                                 printf("Arrivati %d bytes da list\n", strlen($buf));
541                             }
542                             else if ($sock === $this->in) {
543                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
544                                 $line = trim($buf);
545                                 if ($line == "reload") {
546                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
547                                 }
548                                 else if ($line == "shutdown") {
549                                     if ($this->app->dump_data()) {
550                                         exit(0);
551                                     }
552                                     else {
553                                         exit(1);
554                                     }
555                                 }
556                             }
557                             else {
558                                 $key = array_search("$sock", $this->socks);
559                                 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
560                             }
561                         }
562                     }
563                 }
564             }
565
566             $this->garbage_manager(FALSE);
567
568             /* manage unfinished pages */
569             foreach ($this->pages_flush as $k => $pgflush) {
570                 if ($pgflush->try_flush($this->curtime) == TRUE) {
571                     unset($this->pages_flush[$k]);
572                 }
573             }
574             
575             /*
576                $response:                        raw stream data not sent
577                $content:                         html consistent data (<script bla bla>)
578                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
579             */
580
581             /* manage open streaming */
582             foreach ($this->socks as $k => $sock) {
583                 if (isset($this->s2u[intval($sock)])) {
584                     $user = $this->s2u[intval($sock)];
585                     $response = $user->rd_cache_get();
586                     $do_ping = FALSE;
587                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
588                         $do_ping = TRUE;
589                     }
590                     else {
591                         $user->ping_req = FALSE;
592                     }
593
594                     if ($response == "") {
595                         $content = "";
596                         $user->stream_main($content, $get, $post, $cookie);
597                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
598                         if ($do_ping && $user->ping_req == FALSE) {
599                             $content .= $user->stream_keepalive(TRUE);
600                             $user->ping_req = TRUE;
601                         }
602                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
603                             $content = $user->stream_keepalive(FALSE);
604                         }
605                         if ($content != "") {
606                             $response = chunked_content($user->rd_zls_get(), $content);
607                         }
608                     }
609                     
610                     if ($response != "") {
611                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
612                         echo "SPIA: [".$response."]\n";
613                         $response_l = mb_strlen($response, "ASCII");
614                         $wret = @fwrite($sock, $response);
615                         if ($wret < $response_l) {
616                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
617                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
618                         }
619                         else {
620                             $user->rd_cache_set("");
621                         }
622                         fflush($sock);
623                         $user->rd_kalive_reset($this->curtime);
624                     }
625                     
626                     // close socket after a while to prevent client memory consumption
627                     if ($user->rd_endtime_is_expired($this->curtime)) {
628                         if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
629                             $this->s2u[intval($sock)]->rd_socket_set(NULL);
630                         }
631                         unset($this->socks[intval($sock)]);
632                         unset($this->s2u[intval($sock)]);
633                         fclose($sock);
634                         printf("CLOSE ON LOOP\n");
635                     }
636                 }
637             }  // foreach ($this->socks...
638             printf("\n");
639         }  // while (...
640     }  // function run(...
641 }
642
643 ?>