PageFlush added, log_legal without remote address
[brisk.git] / web / spush / brisk-spush.php
1 #!/usr/bin/php
2 <?php
3 /*
4  *  brisk - spush/brisk-spush.php
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  * TODO
25  *
26  *   - partial write for normal page management
27  *   - log legal address fix
28  *   - from room to table
29  *   - from table to room
30  *   - fwrite other issues
31  *   - manage and test cross forwarder between table and room
32  *   - setcookie (for tables only)
33  *   - keepalive management
34  *   - chunked
35  *
36  *   DONE/FROZEN - problema con getpeer (HOSTADDR)
37  *
38  *   DONE - index_rd_ifra: last_clean issue
39  *   DONE - fwrite failed error management (select, buffer where store unsent data, and fwrite check and retry)
40  *   ABRT - index_wr.php::reload - reload is js-only function
41  *   DONE - bug: after restart index_rd.php receive from prev clients a lot of req
42  *   DONE - index_wr.php::chat
43  *   DONE - index_wr.php::exit
44  *   DONE - index_rd.php porting
45  *   DONE - generic var management from internet
46  *   DONE - index.php auth part
47  */
48
49 $G_base = "../";
50
51 require_once("./sac-a-push.phh");
52 require_once("./brisk-spush.phh");
53 require_once($G_base."Obj/brisk.phh");
54 require_once($G_base."Obj/auth.phh");
55 // require_once("../Obj/proxyscan.phh");
56 require_once($G_base."index.php");
57 require_once($G_base."index_wr.php");
58 require_once($G_base."index_rd_ifra.php");
59 require_once($G_base."briskin5/Obj/briskin5.phh");
60
61 define('SITE_PREFIX', '/brisk/');
62
63 function headers_render($header)
64 {
65     
66     $s = "";
67     $s .= "HTTP/1.1 200 OK\r\n";
68     if (!isset($header['Date']))
69         $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
70     if (!isset($header['Connection']))
71         $s .= "Connection: close\r\n";
72     if (!isset($header['Content-Type']))
73         $s .= "Content-Type: text/html\r\n";
74     foreach($header as $key => $value) {
75         $s .= sprintf("%s: %s\r\n", $key, $value);
76     }
77     $s .= "Mop: was/here\r\n";
78     $s .= "\r\n";
79
80     return ($s);
81 }
82
83 /*
84  *  Caching system using ob php system to cache old style pages
85  *  to a var and than send it with more calm
86  */
87 $G_headers = "";
88
89 function shutta()
90 {
91   log_rd2("SHUTTA [".connection_status()."] !");
92 }
93
94 register_shutdown_function('shutta');
95
96 /*
97  *  MAIN
98  */
99 $shutdown = FALSE;
100
101 function main()
102 {
103     GLOBAL $G_headers;
104     GLOBAL $shutdown;
105     $main_loop = TRUE;
106
107     /*
108      *  INIT
109      */
110
111     $FILE_SOCKET = "/tmp/brisk.sock";
112     $UNIX_SOCKET = "unix://$FILE_SOCKET";
113     $debug = 0;
114     $fixed_fd = 2;
115     $socks = array();
116
117     $blocking_mode = 0; // 0 for non-blocking
118
119     if (($room = Room::create()) == FALSE) {
120         log_crit("load_data failed");
121         return FALSE;
122     }
123
124     $s2u  = array();
125     $pages_flush = array();
126
127     $rndstr = "";
128     for ($i = 0 ; $i < 4096 ; $i++) {
129         $rndstr .= chr(mt_rand(65, 90));
130     }
131
132     if (file_exists($FILE_SOCKET)) {
133         unlink($FILE_SOCKET);
134     }
135     
136     $old_umask = umask(0);
137     if (($list = stream_socket_server($UNIX_SOCKET, $err, $errs)) === FALSE) {
138         exit(11);
139     }
140     umask($old_umask);
141
142     if (($in = fopen("php://stdin", "r")) === FALSE) {
143         exit(11);
144     }
145
146     stream_set_blocking($list, $blocking_mode); # Set the stream to non-blocking
147
148     while ($main_loop) {
149         $curtime = time();
150         printf("IN LOOP: Current opened: %d  pages_flush: %d\n", count($socks), count($pages_flush));
151
152         /* Prepare the read array */
153         if ($shutdown) 
154             $read   = array_merge(array("$in" => $in), $socks);
155         else
156             $read   = array_merge(array("$list" => $list, "$in" => $in), $socks);
157
158         if ($debug > 1) {
159             printf("PRE_SELECT\n");
160             print_r($read);
161         }
162         $write  = NULL;
163         $except = NULL;
164         $num_changed_sockets = stream_select($read, $write, $except, 0, 250000);
165         
166         if ($num_changed_sockets === FALSE) {
167             printf("No data in 5 secs");
168         } 
169         else if ($num_changed_sockets > 0) {
170             printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
171             if ($debug > 1) {
172                 print_r($read);
173             }
174             /* At least at one of the sockets something interesting happened */
175             foreach ($read as $i => $sock) {
176                 if ($sock === $list) {
177                     printf("NUOVA CONNEX\n");
178                     $new_unix = stream_socket_accept($list);
179                     $stream_info = "";
180                     $method      = "";
181                     $get         = array();
182                     $post        = array();
183                     $cookie      = array();
184                     if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
185                         stream_set_blocking($new_socket, $blocking_mode); // Set the stream to non-blocking
186                         printf("RECEIVED HEADER:\n%s", $stream_info);
187                         $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
188                         printf("PATH: [%s]\n", $path);
189                         printf("M: %s\nHEADER:\n", $method);
190                         print_r($header);
191                         printf("GET:\n");
192                         print_r($get);
193                         printf("POST:\n");
194                         print_r($post);
195                         printf("COOKIE:\n");
196                         print_r($cookie);
197
198                         $addr = stream_socket_get_name($new_socket, TRUE);
199
200                         switch ($path) {
201                         case SITE_PREFIX:
202                         case SITE_PREFIX."index.php":
203                             $header_out = array();
204                             ob_start();
205                             index_main($room, $header_out, $addr, $get, $post, $cookie);
206                             $content = ob_get_contents();
207                             ob_end_clean();
208
209                             $pgflush = new PageFlush($new_socket, $curtime, 20, $header_out, $content);
210
211                             if ($pgflush->try_flush($curtime) == FALSE) {
212                                 // Add $pgflush to the pgflush array
213                                 array_push($pages_flush, $pgflush);
214                             }
215
216                             break;
217                         case SITE_PREFIX."index_wr.php":
218                             $header_out = array();
219                             $addr = "";
220                             // $ret = socket_getpeername($new_socket, $addr);
221                             printf("RET: %s\n", $addr);
222                             // exit(123);
223                             ob_start();
224                             index_wr_main($room, $addr, $get, $post, $cookie);
225                             $content = ob_get_contents();
226                             ob_end_clean();
227                             
228                             // printf("OUT: [%s]\n", $G_content);
229                             fwrite($new_socket, headers_render($header_out).$content);
230                             fclose($new_socket);
231                             break;
232                         case SITE_PREFIX."index_rd_ifra.php":
233                             do {
234                                 $header_out = array();
235                                 if (!isset($cookie['sess'])
236                                     || (($user = $room->get_user($cookie['sess'], $idx)) == FALSE)) {
237                                     $body = index_rd_ifra_fini(TRUE);
238                                     fwrite($new_socket, headers_render($header_out).$body);
239                                     fflush($new_socket);
240                                     fclose($new_socket);
241                                     break;
242                                 }
243                                 // close a previous opened index_read_ifra socket, if exists
244                                 if (($prev = $user->rd_socket_get()) != NULL) {
245                                     unset($s2u[intval($user->rd_socket_get())]);
246                                     unset($socks[intval($user->rd_socket_get())]);
247                                     fclose($user->rd_socket_get());
248                                     printf("CLOSE AND OPEN AGAIN ON IFRA2\n");
249                                     $user->rd_socket_set(NULL);
250                                 }
251
252                                 $body = "";
253                                 index_rd_ifra_init($room, $user, $header_out, $body, $get, $post, $cookie);
254                                 fwrite($new_socket, headers_render($header_out).$body);
255                                 fflush($new_socket);
256
257                                 $s2u[intval($new_socket)] = $idx;
258                                 $socks[intval($new_socket)] = $new_socket;                                
259                                 $user->rd_socket_set($new_socket);
260                             } while (FALSE);
261
262                             break;
263                         }
264                     }
265                     else {
266                         printf("WARNING: ancillary_getstream failed\n");
267                     }
268                 }
269                 else {
270                     if (($buf = fread($sock, 512)) === FALSE) {
271                         printf("error read\n");
272                         exit(123);
273                     }
274                     else if (strlen($buf) === 0) {
275                         if ($sock === $list) {
276                             printf("Arrivati %d bytes da list\n", strlen($buf));
277                         }
278                         else if ($sock === $in) {
279                             printf("Arrivati %d bytes da stdin\n", strlen($buf));
280                         }
281                         else {
282                             // $user_a[$s2u[intval($sock)]]->disable();
283                             if ($room->user[$s2u[intval($sock)]]->rd_socket_get() != NULL) {
284                                 $room->user[$s2u[intval($sock)]]->rd_socket_set(NULL);
285                             }
286                             unset($socks[intval($sock)]);
287                             unset($s2u[intval($sock)]);
288                             fclose($sock);
289                             printf("CLOSE ON READ\n");
290                         }
291                         if ($debug > 1) {
292                             printf("post unset\n");
293                             print_r($socks);
294                         }
295                     }
296                     else {
297                         if ($debug > 1) {
298                             print_r($read);
299                         }
300                         if ($sock === $list) {
301                             printf("Arrivati %d bytes da list\n", strlen($buf));
302                         }
303                         else if ($sock === $in) {
304                             printf("Arrivati %d bytes da stdin\n", strlen($buf));
305                         }
306                         else {
307                             $key = array_search("$sock", $socks);
308                             printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
309                         }
310                     }
311                 }
312             }
313         }
314
315
316         foreach ($pages_flush as $k => $pgflush) {
317             if ($pgflush->try_flush($curtime) == TRUE) {
318                 unset($pages_flush[$k]);
319             }
320         }
321
322         foreach ($socks as $k => $sock) {
323             if (isset($s2u[intval($sock)])) {
324                 $user = $room->user[$s2u[intval($sock)]];
325                 $body = $user->rd_cache_get();
326                 if ($body == "")
327                     index_rd_ifra_main($room, $user, $body);
328
329                 if ($body == "" && $user->rd_kalive_is_expired($curtime)) {
330                     $body = index_rd_ifra_keepalive($user);
331                 }
332
333                 if ($body != "") {
334                     echo "SPIA: [".substr($body, 0, 60)."...]\n";
335                     $body_l = mb_strlen($body, "ASCII");
336                     $ret = @fwrite($sock, $body);
337                     if ($ret < $body_l) {
338                         printf("TROUBLE WITH FWRITE: %d\n", $ret);
339                         $user->rd_cache_set(mb_substr($body, $ret, $body_l - $ret, "ASCII"));
340                     }
341                     else {
342                         $user->rd_cache_set("");
343                     }
344                     fflush($sock);
345                     $user->rd_kalive_reset($curtime);
346                 }
347
348                 // close socket after a while to prevent client memory consumption
349                 if ($user->rd_endtime_is_expired($curtime)) {
350                     // $user_a[$s2u[intval($sock)]]->disable();
351                     if ($room->user[$s2u[intval($sock)]]->rd_socket_get() != NULL) {
352                         $room->user[$s2u[intval($sock)]]->rd_socket_set(NULL);
353                     }
354                     unset($socks[intval($sock)]);
355                     unset($s2u[intval($sock)]);
356                     fclose($sock);
357                     printf("CLOSE ON LOOP\n");
358                 }
359             }
360         }
361     }
362     
363     exit(0);
364 }
365
366 main();
367 ?>