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