commented old cold removed
[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, 1); // 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                         printf("RECEIVED HEADER:\n%s", $stream_info);
176                         $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
177                         printf("PATH: [%s]\n", $path);
178                         printf("M: %s\nHEADER:\n", $method);
179                         print_r($header);
180                         printf("GET:\n");
181                         print_r($get);
182                         printf("POST:\n");
183                         print_r($post);
184                         printf("COOKIE:\n");
185                         print_r($cookie);
186
187                         $addr = stream_socket_get_name($new_socket, TRUE);
188
189                         switch ($path) {
190                         case SITE_PREFIX:
191                         case SITE_PREFIX."index.php":
192                             $header_out = array();
193                             ob_start();
194                             index_main($room, $header_out, $addr, $get, $post, $cookie);
195                             $content = ob_get_contents();
196                             ob_end_clean();
197                             // printf("OUT: [%s]\n", $G_content);
198                             fwrite($new_socket, headers_render($header_out).$content);
199                             fclose($new_socket);
200                             break;
201                         case SITE_PREFIX."index_wr.php":
202                             $header_out = array();
203                             $addr = "";
204                             // $ret = socket_getpeername($new_socket, $addr);
205                             printf("RET: %s\n", $addr);
206                             // exit(123);
207                             ob_start();
208                             index_wr_main($room, $addr, $get, $post, $cookie);
209                             $content = ob_get_contents();
210                             ob_end_clean();
211                             
212                             // printf("OUT: [%s]\n", $G_content);
213                             fwrite($new_socket, headers_render($header_out).$content);
214                             fclose($new_socket);
215                             break;
216                         case SITE_PREFIX."index_rd_ifra.php":
217                             do {
218                                 if (!isset($cookie['sess'])) {
219                                     fclose($new_socket);
220                                     break;
221                                 }
222                                 if (($user = $room->get_user($cookie['sess'], $idx)) == FALSE) {
223                                     fclose($new_socket);
224                                     break;
225                                 }
226                                 if (($prev = $user->rd_socket_get()) != NULL) {
227                                     unset($s2u[intval($user->rd_socket_get())]);
228                                     unset($socks[intval($user->rd_socket_get())]);
229                                     fclose($user->rd_socket_get());
230                                     $user->rd_socket_set(NULL);
231                                 }
232
233                                 $header_out = array();
234                                 $body = "";
235                                 index_rd_ifra_init($room, $user, $header_out, $body, $get, $post, $cookie);
236                                 stream_set_blocking($new_socket, $blocking_mode); // Set the stream to non-blocking
237                                 fwrite($new_socket, headers_render($header_out).$body);
238                                 fflush($new_socket);
239
240                                 $s2u[intval($new_socket)] = $idx;
241                                 $socks[intval($new_socket)] = $new_socket;                                
242                                 $user->rd_socket_set($new_socket);
243                             } while (FALSE);
244
245                             break;
246                         }
247                     }
248                     else {
249                         printf("WARNING: ancillary_getstream failed\n");
250                     }
251                 }
252                 else {
253                     if (($buf = fread($sock, 512)) === FALSE) {
254                         printf("error read\n");
255                         exit(123);
256                     }
257                     else if (strlen($buf) === 0) {
258                         if ($sock === $list) {
259                             printf("Arrivati %d bytes da list\n", strlen($buf));
260                         }
261                         else if ($sock === $in) {
262                             printf("Arrivati %d bytes da stdin\n", strlen($buf));
263                         }
264                         else {
265                             // $user_a[$s2u[intval($sock)]]->disable();
266                             if ($room->user[$s2u[intval($sock)]]->rd_socket_get() != NULL) {
267                                 $room->user[$s2u[intval($sock)]]->rd_socket_set(NULL);
268                             }
269                             unset($socks[intval($sock)]);
270                             unset($s2u[intval($sock)]);
271                             fclose($sock);
272                         }
273                         if ($debug > 1) {
274                             printf("post unset\n");
275                             print_r($socks);
276                         }
277                     }
278                     else {
279                         if ($debug > 1) {
280                             print_r($read);
281                         }
282                         if ($sock === $list) {
283                             printf("Arrivati %d bytes da list\n", strlen($buf));
284                         }
285                         else if ($sock === $in) {
286                             printf("Arrivati %d bytes da stdin\n", strlen($buf));
287                         }
288                         else {
289                             $key = array_search("$sock", $socks);
290                             printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
291                         }
292                     }
293                 }
294             }
295         }
296
297
298
299
300         foreach ($socks as $k => $sock) {
301             if (isset($s2u[intval($sock)])) {
302                 $body = "";
303                 
304
305                 $body = "";
306                 $user = $room->user[$s2u[intval($sock)]];
307                 index_rd_ifra_main($room, $user, $body);
308                 if ($body == "" && $user->rd_tout_is_expired($curtime)) {
309                     $body = index_rd_ifra_keepalive($user);
310                 }
311
312                 if ($body != "") {
313                     echo "SPIA: [".substr($body, 0, 60)."...]\n";
314                     fwrite($sock, $body);
315                     fflush($sock);
316                     $user->rd_tout_reset($curtime);
317                 }
318
319                 // close socket after a while to prevent client memory consumption
320                 if ($user->rd_endtime_is_expired($curtime)) {
321                     // $user_a[$s2u[intval($sock)]]->disable();
322                     if ($room->user[$s2u[intval($sock)]]->rd_socket_get() != NULL) {
323                         $room->user[$s2u[intval($sock)]]->rd_socket_set(NULL);
324                     }
325                     unset($socks[intval($sock)]);
326                     unset($s2u[intval($sock)]);
327                     fclose($sock);
328                 }
329             }
330         }
331     }
332     
333     exit(0);
334 }
335
336 main();
337 ?>