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