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