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