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