htmlfile transport type added
[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     $cookies = "";
109
110     if (isset($header['cookies'])) {
111         $cookies = $header['cookies']->render();
112         unset($header['cookies']);
113     }
114     if (isset($header['Location'])) {
115         $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
116     }
117     else {
118         $s = "HTTP/1.1 200 OK\r\n";
119
120         if (!isset($header['Date']))
121             $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
122         if (!isset($header['Connection']))
123             $s .= "Connection: close\r\n";
124         if (!isset($header['Content-Type']))
125             $s .= "Content-Type: text/html\r\n";
126         foreach($header as $key => $value) {
127             $s .= sprintf("%s: %s\r\n", $key, $value);
128         }
129         if ($len >= 0) {
130             $s .= sprintf("Content-Length: %d\r\n", $len);
131         }
132         else {
133             $s .= "Cache-Control: no-cache, must-revalidate\r\n";
134             $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
135             if (!isset($header['Content-Encoding'])) {
136                 $s .= "Content-Encoding: chunked\r\n";
137             }
138             $s .= "Transfer-Encoding: chunked\r\n";
139         }
140         $s .= $cookies;
141     }
142     $s .= "\r\n";
143
144     return ($s);
145 }
146
147 /*
148  *  Caching system using ob php system to cache old style pages
149  *  to a var and than send it with more calm
150  */
151
152 function shutta()
153 {
154   log_rd2("SHUTTA [".connection_status()."] !");
155 }
156
157 register_shutdown_function('shutta');
158
159 /*
160  *  MAIN
161  */
162
163 function chunked_content($zls, $content)
164 {
165     if ($zls) {
166         $cont_comp = $zls->compress_chunk($content);
167     }
168     else {
169         $cont_comp = $content;
170     }
171     $cont_comp_l = mb_strlen($cont_comp, "ASCII");
172     printf("CHUNK: [%s]\n", $content);
173
174     return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
175 }
176
177 function chunked_fini()
178 {
179     return sprintf("0\r\n");
180 }
181
182 function get_encoding($header)
183 {
184     $enc = "plain";
185     if (isset($header['Accept-Encoding'])) {
186         $acc = explode(',', $header['Accept-Encoding']);
187
188         if (array_search('gzip', $acc) !== FALSE) {
189             $enc = 'gzip';
190         }
191         else if (array_search('deflate', $acc) !== FALSE) {
192             $enc = 'deflate';
193         }
194     }
195
196     return ($enc);
197 }
198
199 class Cookie {
200     var $attr;
201     // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
202     // string $name  [, string $value  [, int $expire = 0  [, string $path  [, string $domain  [, bool $secure = false  [, bool $httponly = false  ]]]]]] )
203     function Cookie()
204     {
205         $this->attr = array();
206     }
207
208     static function create($name)
209     {
210         $thiz = new Cookie();
211
212         $thiz->attr[$name] = "";
213
214         $argc = func_num_args();
215         for ($i = 1 ; $i < $argc ; $i++) {
216             $arg = func_get_arg($i);
217             switch ($i) {
218             case 1:
219                 $thiz->attr[$name] = urlencode($arg);
220                 break;
221             case 2:
222                 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
223                 break;
224             case 3:
225                 $thiz->attr['Path'] = $arg;
226                 break;
227             case 4:
228                 $thiz->attr['Domain'] = $arg;
229                 break;
230             case 5:
231                 if ($arg == TRUE) {
232                     $thiz->attr['Secure'] = NULL;
233                 }
234                 break;
235             case 6:
236                 if ($arg == TRUE) {
237                     $thiz->attr['HttpOnly'] = NULL;
238                 }
239                 break;
240             default:
241                 return FALSE;
242             }
243         }
244
245         return $thiz;
246     }
247
248     function render()
249     {
250         $r = "Set-Cookie: ";
251         $isfirst = TRUE;
252
253         foreach ($this->attr as $k => $v) {
254             if ($v == NULL) {
255                 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
256             }
257             else {
258                 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
259             }
260             $isfirst = FALSE;
261         }
262         $r .= "\r\n";
263
264         return $r;
265     }
266 }
267
268 class Cookies {
269     var $cookies;
270
271     function Cookies()
272     {
273         $this->cookies = array();
274     }
275
276     function add($name)
277     {
278         if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
279             return (FALSE);
280
281         array_push($this->cookies, $cookie);
282
283         return (TRUE);
284     }
285
286     function render()
287     {
288         $r = "";
289         foreach ($this->cookies as $cookie) {
290             $r .= $cookie->render();
291         }
292
293         return ($r);
294     }
295 }
296
297
298 class Sac_a_push {
299     static $fixed_fd = 2;
300     
301     var $file_socket;
302     var $unix_socket;
303     var $socks;
304     var $s2u;
305     var $pages_flush;
306
307     var $list;
308     var $in;
309
310     var $debug;
311     var $blocking_mode;
312
313     var $app;
314     var $bin5;
315
316     var $curtime;
317
318     var $rndstr;
319     var $main_loop;
320
321     function Sac_a_push()
322     {
323     }
324
325     // Sac_a_push::create("/tmp/brisk.sock", 0, 0
326
327     static function create(&$app, $sockname, $debug, $blocking_mode)
328     {        
329         $thiz = new Sac_a_push();
330         
331         $thiz->app = $app;
332         $thiz->file_socket = $sockname;
333         $thiz->unix_socket = "unix://$sockname";
334         $thiz->debug = $debug;
335         $thiz->socks = array();
336         $thiz->s2u  = array();
337         $thiz->pages_flush = array();
338
339         $thiz->blocking_mode = 0; // 0 for non-blocking
340
341         $thiz->rndstr = "";
342         for ($i = 0 ; $i < 4096 ; $i++) {
343             if (($i % 128) == 0)
344                 $thiz->rndstr .= "\n";
345             else
346                 $thiz->rndstr .= chr(mt_rand(65, 90));
347         }
348         
349         if (file_exists($thiz->file_socket)) {
350             unlink($thiz->file_socket);
351         }
352     
353         $old_umask = umask(0);
354         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
355             return (FALSE);
356         }
357         umask($old_umask);
358         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
359
360         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
361             return(FALSE);
362         }
363
364         $thiz->main_loop = FALSE;
365
366         return ($thiz);
367     }
368
369     function socks_set($sock, $user)
370     {
371         $id = intval($sock);
372
373         $this->s2u[$id]   = $user;
374         $this->socks[$id] = $sock;
375     }
376
377     function socks_unset($sock)
378     {
379         $id = intval($sock);
380
381         unset($this->s2u[$id]);
382         unset($this->socks[$id]);
383     }
384
385     function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
386     {
387         $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
388
389         if ($pgflush->try_flush($this->curtime) == FALSE) {
390             // Add $pgflush to the pgflush array
391             $this->pgflush_add($pgflush);
392         }
393     }
394
395     function pgflush_add($pgflush)
396     {
397         array_push($this->pages_flush, $pgflush);
398     }
399
400     function garbage_manager($force)
401     {
402         $this->app->garbage_manager($force);
403
404         foreach ($this->socks as $k => $sock) {
405             if ($this->s2u[intval($sock)]->sess == '') {
406                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
407                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
408                 }
409                 unset($this->socks[intval($sock)]);
410                 unset($this->s2u[intval($sock)]);
411                 fclose($sock);
412                 printf("CLOSE ON GARBAGE MANAGER\n");
413             }
414         }
415     }
416
417     function run()
418     {
419         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST, $G_with_splash;
420
421         if ($this->main_loop) {
422             return (FALSE);
423         }
424         
425         $this->main_loop = TRUE;
426         
427         while ($this->main_loop) {
428             $this->curtime = time();
429             printf("IN LOOP: Current opened: %d  pages_flush: %d - ", count($this->socks), count($this->pages_flush));
430             
431             /* Prepare the read array */
432             /* // when we manage it ... */
433             /* if ($shutdown)  */
434             /*     $read   = array_merge(array("$in" => $in), $socks); */
435             /* else */
436             $read   = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
437                                   $this->socks);
438             
439             if ($this->debug > 1) {
440                 printf("PRE_SELECT\n");
441                 print_r($read);
442             }
443             $write  = NULL;
444             $except = NULL;
445             $num_changed_sockets = stream_select($read, $write, $except, 0, 500000);
446         
447             if ($num_changed_sockets == 0) {
448                 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
449             } 
450             else if ($num_changed_sockets > 0) {
451                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
452                 if ($this->debug > 1) {
453                     print_r($read);
454                 }
455                 /* At least at one of the sockets something interesting happened */
456                 foreach ($read as $i => $sock) {
457                     /* is_resource check is required because there is the possibility that
458                        during new request an old connection is closed */
459                     if (!is_resource($sock)) {
460                         continue;
461                     }
462                     if ($sock === $this->list) {
463                         printf("NUOVA CONNEX\n");
464                         if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
465                             printf("SOCKET_ACCEPT FAILED\n");
466                             continue;
467                         }
468                         $stream_info = "";
469                         $method      = "";
470                         $get         = array();
471                         $post        = array();
472                         $cookie      = array();
473                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
474                             printf("NEW_SOCKET: %d\n", intval($new_socket));
475                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
476                             printf("RECEIVED HEADER:\n%s", $stream_info);
477                             $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
478                             printf("PATH: [%s]\n", $path);
479                             printf("M: %s\nHEADER:\n", $method);
480                             print_r($header);
481                             printf("GET:\n");
482                             print_r($get);
483                             printf("POST:\n");
484                             print_r($post);
485                             printf("COOKIE:\n");
486                             print_r($cookie);
487                             $addr = stream_socket_get_name($new_socket, TRUE);
488                             $header_out = array();
489
490                             $subs = SITE_PREFIX."briskin5/";
491                             $subs_l = strlen($subs);
492                             $rret = FALSE;
493                             if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
494                                 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
495                             }
496                             if ($rret == FALSE) { 
497                                 // FIXME: manage 404 !!!
498                                 printf("TODO: fix unknown page\n");
499                             }
500                             printf("number of sockets after %d\n", count($this->socks));
501                         }
502                         else {
503                             printf("WARNING: ancillary_getstream failed\n");
504                         }
505                     }
506                     else {
507                         $buf = fread($sock, 512);
508                         // if socket is closed
509                         if ($buf == FALSE || strlen($buf) == 0) {
510                             if ($buf == FALSE) {
511                                 printf("ERROR READING\n");
512                             }
513                             if ($sock === $this->list) {
514                                 printf("Arrivati %d bytes da list\n", strlen($buf));
515                                 exit(21);
516                             }
517                             else if ($sock === $this->in) {
518                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
519                                 exit(22);
520                             }
521                             else {
522                                 // $user_a[$s2u[intval($sock)]]->disable();
523                                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
524                                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
525                                 }
526                                 unset($this->socks[intval($sock)]);
527                                 unset($this->s2u[intval($sock)]);
528                             }
529                             fclose($sock);
530                             printf("CLOSE ON READ\n");
531
532                             if ($this->debug > 1) {
533                                 printf("post unset\n");
534                                 print_r($this->socks);
535                             }
536                         }
537                         else {
538                             if ($this->debug > 1) {
539                                 print_r($read);
540                             }
541                             if ($sock === $this->list) {
542                                 printf("Arrivati %d bytes da list\n", strlen($buf));
543                             }
544                             else if ($sock === $this->in) {
545                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
546                                 $line = trim($buf);
547                                 if ($line == "reload") {
548                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
549                                 }
550                             }
551                             else {
552                                 $key = array_search("$sock", $this->socks);
553                                 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
554                             }
555                         }
556                     }
557                 }
558             }
559
560             $this->garbage_manager(FALSE);
561
562             /* manage unfinished pages */
563             foreach ($this->pages_flush as $k => $pgflush) {
564                 if ($pgflush->try_flush($this->curtime) == TRUE) {
565                     unset($this->pages_flush[$k]);
566                 }
567             }
568             
569             /*
570                $response:                        raw stream data not sent
571                $content:                         html consistent data (<script bla bla>)
572                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
573             */
574
575             /* manage open streaming */
576             foreach ($this->socks as $k => $sock) {
577                 if (isset($this->s2u[intval($sock)])) {
578                     $user = $this->s2u[intval($sock)];
579                     $response = $user->rd_cache_get();
580                     $do_ping = FALSE;
581                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
582                         $do_ping = TRUE;
583                     }
584                     else {
585                         $user->ping_req = FALSE;
586                     }
587
588                     if ($response == "") {
589                         $content = "";
590                         $user->stream_main($content, $get, $post, $cookie);
591                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
592                         if ($do_ping && $user->ping_req == FALSE) {
593                             $content .= $user->stream_keepalive(TRUE);
594                             $user->ping_req = TRUE;
595                         }
596                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
597                             $content = $user->stream_keepalive(FALSE);
598                         }
599                         if ($content != "") {
600                             $response = chunked_content($user->rd_zls_get(), $content);
601                         }
602                     }
603                     
604                     if ($response != "") {
605                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
606                         echo "SPIA: [".$response."]\n";
607                         $response_l = mb_strlen($response, "ASCII");
608                         $wret = @fwrite($sock, $response);
609                         if ($wret < $response_l) {
610                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
611                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
612                         }
613                         else {
614                             $user->rd_cache_set("");
615                         }
616                         fflush($sock);
617                         $user->rd_kalive_reset($this->curtime);
618                     }
619                     
620                     // close socket after a while to prevent client memory consumption
621                     if ($user->rd_endtime_is_expired($this->curtime)) {
622                         if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
623                             $this->s2u[intval($sock)]->rd_socket_set(NULL);
624                         }
625                         unset($this->socks[intval($sock)]);
626                         unset($this->s2u[intval($sock)]);
627                         fclose($sock);
628                         printf("CLOSE ON LOOP\n");
629                     }
630                 }
631             }  // foreach ($this->socks...
632             printf("\n");
633         }  // while (...
634     }  // function run(...
635 }
636
637 ?>