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