fix bug for already closed readed socket
[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                 /* is_resource check is required because there is the possibility that
177                    during new request an old connection is closed */
178                 if (!is_resource($sock)) {
179                     continue;
180                 }
181                 if ($sock === $list) {
182                     printf("NUOVA CONNEX\n");
183                     $new_unix = stream_socket_accept($list);
184                     $stream_info = "";
185                     $method      = "";
186                     $get         = array();
187                     $post        = array();
188                     $cookie      = array();
189                     if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
190                         stream_set_blocking($new_socket, $blocking_mode); // Set the stream to non-blocking
191                         printf("RECEIVED HEADER:\n%s", $stream_info);
192                         $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
193                         printf("PATH: [%s]\n", $path);
194                         printf("M: %s\nHEADER:\n", $method);
195                         print_r($header);
196                         printf("GET:\n");
197                         print_r($get);
198                         printf("POST:\n");
199                         print_r($post);
200                         printf("COOKIE:\n");
201                         print_r($cookie);
202
203                         $addr = stream_socket_get_name($new_socket, TRUE);
204
205                         switch ($path) {
206                         case SITE_PREFIX:
207                         case SITE_PREFIX."index.php":
208                             $header_out = array();
209                             ob_start();
210                             index_main($room, $header_out, $addr, $get, $post, $cookie);
211                             $content = ob_get_contents();
212                             ob_end_clean();
213
214                             $pgflush = new PageFlush($new_socket, $curtime, 20, $header_out, $content);
215
216                             if ($pgflush->try_flush($curtime) == FALSE) {
217                                 // Add $pgflush to the pgflush array
218                                 array_push($pages_flush, $pgflush);
219                             }
220
221                             break;
222                         case SITE_PREFIX."index_wr.php":
223                             $header_out = array();
224                             $addr = "";
225                             // $ret = socket_getpeername($new_socket, $addr);
226                             printf("RET: %s\n", $addr);
227                             // exit(123);
228                             ob_start();
229                             index_wr_main($room, $addr, $get, $post, $cookie);
230                             $content = ob_get_contents();
231                             ob_end_clean();
232                             
233                             // printf("OUT: [%s]\n", $G_content);
234                             fwrite($new_socket, headers_render($header_out).$content);
235                             fclose($new_socket);
236                             break;
237                         case SITE_PREFIX."index_rd_ifra.php":
238                             do {
239                                 $header_out = array();
240                                 if (!isset($cookie['sess'])
241                                     || (($user = $room->get_user($cookie['sess'], $idx)) == FALSE)) {
242                                     $body = index_rd_ifra_fini(TRUE);
243                                     fwrite($new_socket, headers_render($header_out).$body);
244                                     fflush($new_socket);
245                                     fclose($new_socket);
246                                     break;
247                                 }
248                                 // close a previous opened index_read_ifra socket, if exists
249                                 if (($prev = $user->rd_socket_get()) != NULL) {
250                                     unset($s2u[intval($user->rd_socket_get())]);
251                                     unset($socks[intval($user->rd_socket_get())]);
252                                     fclose($user->rd_socket_get());
253                                     printf("CLOSE AND OPEN AGAIN ON IFRA2\n");
254                                     $user->rd_socket_set(NULL);
255                                 }
256
257                                 $body = "";
258                                 index_rd_ifra_init($room, $user, $header_out, $body, $get, $post, $cookie);
259                                 fwrite($new_socket, headers_render($header_out).$body);
260                                 fflush($new_socket);
261
262                                 $s2u[intval($new_socket)] = $idx;
263                                 $socks[intval($new_socket)] = $new_socket;                                
264                                 $user->rd_socket_set($new_socket);
265                             } while (FALSE);
266
267                             break;
268                         }
269                     }
270                     else {
271                         printf("WARNING: ancillary_getstream failed\n");
272                     }
273                 }
274                 else {
275                     if (($buf = fread($sock, 512)) === FALSE) {
276                         printf("error read\n");
277                         exit(123);
278                     }
279                     else if (strlen($buf) === 0) {
280                         if ($sock === $list) {
281                             printf("Arrivati %d bytes da list\n", strlen($buf));
282                         }
283                         else if ($sock === $in) {
284                             printf("Arrivati %d bytes da stdin\n", strlen($buf));
285                         }
286                         else {
287                             // $user_a[$s2u[intval($sock)]]->disable();
288                             if ($room->user[$s2u[intval($sock)]]->rd_socket_get() != NULL) {
289                                 $room->user[$s2u[intval($sock)]]->rd_socket_set(NULL);
290                             }
291                             unset($socks[intval($sock)]);
292                             unset($s2u[intval($sock)]);
293                             fclose($sock);
294                             printf("CLOSE ON READ\n");
295                         }
296                         if ($debug > 1) {
297                             printf("post unset\n");
298                             print_r($socks);
299                         }
300                     }
301                     else {
302                         if ($debug > 1) {
303                             print_r($read);
304                         }
305                         if ($sock === $list) {
306                             printf("Arrivati %d bytes da list\n", strlen($buf));
307                         }
308                         else if ($sock === $in) {
309                             printf("Arrivati %d bytes da stdin\n", strlen($buf));
310                         }
311                         else {
312                             $key = array_search("$sock", $socks);
313                             printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
314                         }
315                     }
316                 }
317             }
318         }
319
320
321         foreach ($pages_flush as $k => $pgflush) {
322             if ($pgflush->try_flush($curtime) == TRUE) {
323                 unset($pages_flush[$k]);
324             }
325         }
326
327         foreach ($socks as $k => $sock) {
328             if (isset($s2u[intval($sock)])) {
329                 $user = $room->user[$s2u[intval($sock)]];
330                 $body = $user->rd_cache_get();
331                 if ($body == "")
332                     index_rd_ifra_main($room, $user, $body);
333
334                 if ($body == "" && $user->rd_kalive_is_expired($curtime)) {
335                     $body = index_rd_ifra_keepalive($user);
336                 }
337
338                 if ($body != "") {
339                     echo "SPIA: [".substr($body, 0, 60)."...]\n";
340                     $body_l = mb_strlen($body, "ASCII");
341                     $ret = @fwrite($sock, $body);
342                     if ($ret < $body_l) {
343                         printf("TROUBLE WITH FWRITE: %d\n", $ret);
344                         $user->rd_cache_set(mb_substr($body, $ret, $body_l - $ret, "ASCII"));
345                     }
346                     else {
347                         $user->rd_cache_set("");
348                     }
349                     fflush($sock);
350                     $user->rd_kalive_reset($curtime);
351                 }
352
353                 // close socket after a while to prevent client memory consumption
354                 if ($user->rd_endtime_is_expired($curtime)) {
355                     // $user_a[$s2u[intval($sock)]]->disable();
356                     if ($room->user[$s2u[intval($sock)]]->rd_socket_get() != NULL) {
357                         $room->user[$s2u[intval($sock)]]->rd_socket_set(NULL);
358                     }
359                     unset($socks[intval($sock)]);
360                     unset($s2u[intval($sock)]);
361                     fclose($sock);
362                     printf("CLOSE ON LOOP\n");
363                 }
364             }
365         }
366     }
367     
368     exit(0);
369 }
370
371 main();
372 ?>