log_legal function usable without a valid user instance as parameter
[brisk.git] / web / Obj / sac-a-push.phh
1 <?php
2 /*
3  *  brisk - Obj/sac-a-push.phh
4  *
5  *  Copyright (C) 2012-2014 Matteo Nastasi
6  *                          mailto: nastasi@alternativeoutput.it
7  *                                  matteo.nastasi@milug.org
8  *                          web: http://www.alternativeoutput.it
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details. You should have received a
19  * copy of the GNU General Public License along with this program; if
20  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
21  * Suite 330, Boston, MA 02111-1307, USA.
22  *
23  */
24
25 define('SITE_PREFIX', "/brisk/");
26 define('SITE_PREFIX_LEN', 7);
27
28 define('DIRECT_ST_READ',  1);
29 define('DIRECT_ST_WRITE', 2);
30
31 declare(ticks = 1);
32
33 /* this list is created with bin/get_globals.sh */
34 $_globals_list = array(
35 'G_admin_mail', 'G_alarm_passwd', 'G_all_points', 'G_ban_list', 'G_base',
36 'G_black_list', 'G_brisk_version', 'G_btrace_pref_sub', 'G_cloud_smasher',
37 'G_crypt_key', 'G_dbasetype', 'G_dbauth', 'G_dbpfx', 'G_doc_path',
38 'G_proto', 'G_domain', 'G_donors_all', 'G_donors_cur', 'G_is_local', 'G_lang', 'G_lng',
39 'G_mail_seed', 'G_notguar_code', 'G_PG_cons', 'G_PG_cons_n', 'G_PG_vow',
40 'G_PG_vow_n', 'G_poll_entries', 'G_poll_name', 'G_poll_title',
41 'G_provider_proxy', 'G_proxy_white_list', 'G_room_about', 'G_room_help',
42 'G_room_passwdhowto', 'G_room_roadmap',
43 'G_selfreg_mask', 'G_selfreg_tout', 'G_shutdown', 'G_profile', 'G_sidebanner',
44 'G_sidebanner_idx', 'G_splash_content', 'G_splash_contents',
45 'G_splash_cont_idx', 'G_splash_h', 'G_splash_idx', 'G_splash_interval',
46 'G_splash_timeout', 'G_splash_w', 'G_topbanner', 'G_tos_dthard',
47 'G_tos_dtsoft', 'G_tos_fname', 'G_tos_idx', 'G_tos_vers', 'G_webbase');
48
49 function global_dump()
50 {
51     GLOBAL $G_alarm_passwd, $G_ban_list, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
52     GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
53     GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
54     GLOBAL $G_room_roadmap, $G_shutdown, $G_profile;
55     GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
56     GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
57     GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
58     GLOBAL $G_with_splash, $G_sidebanner, $G_sidebanner_idx;
59     GLOBAL $G_with_topbanner, $G_selfreg_tout, $G_selfreg_mask;
60
61     fprintf(STDERR, "G_alarm_passwd = [%s]\n", print_r($G_alarm_passwd, TRUE));
62     fprintf(STDERR, "G_ban_list = [%s]\n", print_r($G_ban_list, TRUE));
63     fprintf(STDERR, "G_black_list = [%s]\n", print_r($G_black_list, TRUE));
64     fprintf(STDERR, "G_btrace_pref_sub = [%s]\n", print_r($G_btrace_pref_sub, TRUE));
65     fprintf(STDERR, "G_dbauth = [%s]\n", print_r($G_dbauth, TRUE));
66     fprintf(STDERR, "G_dbpfx = [%s]\n", print_r($G_dbpfx, TRUE));
67     fprintf(STDERR, "G_donors_all = [%s]\n", print_r($G_donors_all, TRUE));
68     fprintf(STDERR, "G_donors_cur = [%s]\n", print_r($G_donors_cur, TRUE));
69     fprintf(STDERR, "G_is_local = [%s]\n", print_r($G_is_local, TRUE));
70     fprintf(STDERR, "G_lang = [%s]\n", print_r($G_lang, TRUE));
71     fprintf(STDERR, "G_poll_entries = [%s]\n", print_r($G_poll_entries, TRUE));
72     fprintf(STDERR, "G_poll_name = [%s]\n", print_r($G_poll_name, TRUE));
73     fprintf(STDERR, "G_poll_title = [%s]\n", print_r($G_poll_title, TRUE));
74     fprintf(STDERR, "G_proxy_white_list = [%s]\n", print_r($G_proxy_white_list, TRUE));
75     fprintf(STDERR, "G_room_roadmap = [%s]\n", print_r($G_room_roadmap, TRUE));
76     fprintf(STDERR, "G_shutdown = [%s]\n", print_r($G_shutdown, TRUE));
77     fprintf(STDERR, "G_profile = [%s]\n", print_r($G_profile, TRUE));
78     fprintf(STDERR, "G_splash_content = [%s]\n", print_r($G_splash_content, TRUE));
79     fprintf(STDERR, "G_splash_contents = [%s]\n", print_r($G_splash_contents, TRUE));
80     fprintf(STDERR, "G_splash_cont_idx = [%s]\n", print_r($G_splash_cont_idx, TRUE));
81     fprintf(STDERR, "G_splash_h = [%s]\n", print_r($G_splash_h, TRUE));
82     fprintf(STDERR, "G_splash_idx = [%s]\n", print_r($G_splash_idx, TRUE));
83     fprintf(STDERR, "G_splash_interval = [%s]\n", print_r($G_splash_interval, TRUE));
84     fprintf(STDERR, "G_splash_timeout = [%s]\n", print_r($G_splash_timeout, TRUE));
85     fprintf(STDERR, "G_splash_w = [%s]\n", print_r($G_splash_w, TRUE));
86     fprintf(STDERR, "G_topbanner = [%s]\n", print_r($G_topbanner, TRUE));
87     fprintf(STDERR, "G_with_donors = [%s]\n", print_r($G_with_donors, TRUE));
88     fprintf(STDERR, "G_with_poll = [%s]\n", print_r($G_with_poll, TRUE));
89     fprintf(STDERR, "G_sidebanner = [%s]\n", print_r($G_sidebanner, TRUE));
90     fprintf(STDERR, "G_sidebanner_idx = [%s]\n", print_r($G_sidebanner_idx, TRUE));
91     fprintf(STDERR, "G_with_splash = [%s]\n", print_r($G_with_splash, TRUE));
92     fprintf(STDERR, "G_with_topbanner = [%s]\n", print_r($G_with_topbanner, TRUE));
93     fprintf(STDERR, "G_selfreg_mask = [%x]\n", print_r($G_selfreg_mask, TRUE));
94
95     fprintf(STDERR, "G_selfreg_tout = [%s]\n", print_r($G_selfreg_tout, TRUE));
96
97 }
98
99 function pid_save()
100 {
101     $pid = getmypid();
102     $fname = LEGAL_PATH."/brisk.pid";
103
104     if (file_exists($fname)) {
105         log_crit("WARN: brisk.pid already exists");
106     }
107     file_put_contents($fname, sprintf("%d\n", $pid));
108 }
109
110 function pid_remove()
111 {
112     $fname = LEGAL_PATH."/brisk.pid";
113
114     if (file_exists($fname)) {
115         unlink($fname);
116     }
117 }
118
119 function post_manage(&$post, $line)
120 {
121     $a = explode('&', $line);
122     for ($i = 0 ; $i < count($a) ; $i++) {
123         $b = explode('=', $a[$i]);
124         if (isset($b[0])) {
125             if (isset($b[1])) {
126                 $post[$b[0]] = urldecode($b[1]);
127             }
128             else {
129                 $post[$b[0]] = "";
130             }
131         }
132     }
133 }
134
135 function spu_process_info($stream_info, &$method, &$header, &$get, &$post, &$cookie, &$rest, &$cont)
136 {
137     $check_post = FALSE;
138     $header = array();
139     $get = array();
140     $post = array();
141     $rest = 0;
142     foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
143         // printf("LINE: [%s]\n", $line);
144         if ($check_post) {
145             if (!isset($header['The-Request'])) {
146                 return FALSE;
147             }
148             $req = explode(" ", $header['The-Request']);
149             $method = $req[0];
150
151             if (isset($header['Cookie'])) {
152
153                 // LINE: [Cookie:sess=50e053a9511ef; CO_splashdate4=1356420646; CO_list=all; table_idx=7; table_token=510d494986925; lang=it; CO_bin5_pref_ring_endauct=false; CO_splashdate5=1358372822; CO_splashdate1=1363203374; CO_splashdate2=1363374826; __utma=43654517.209888411.1356605271.1356605271.1356605271.1; __utmz=43654517.1356605271.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)]
154
155                 $cookies = explode("; ", $header['Cookie']);
156                 for ($i = 0 ; $i < count($cookies) ; $i++) {
157                     $name = mb_strstr($cookies[$i], "=", TRUE, 'UTF-8');
158                     if ($name == FALSE) {
159                         if (mb_strlen($cookies[$i]) > 0) {
160                             $cookie[$cookies[$i]] = "";
161                         }
162                         else {
163                             printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
164                         }
165                         continue;
166                     }
167
168                     $value = mb_substr($cookies[$i], mb_strlen($name)+1, 10140, 'UTF-8');
169                     $cookie[$name] = urldecode($value);
170                 }
171             }
172             // GET params management
173             $get_vars = explode('?', $req[1], 2);
174             $path = $get_vars[0];
175             if (count($get_vars) > 1) {
176                 $a = explode('&', $get_vars[1]);
177                 // printf("A COUNT: [%s] %d\n", $a[0], count($a));
178                 for ($i = 0 ; $i < count($a) ; $i++) {
179                     $b = explode('=', $a[$i]);
180                     if ($b[0] == "")
181                         continue;
182                     $get[$b[0]] = urldecode($b[1]);
183                 }
184             }
185             // POST params management
186             if ($req[0] == 'POST') {
187                 $conttype_all = explode(";", $header['Content-Type']);
188                 $header['Content-Type'] = $conttype_all[0];
189                 // $path_all[1-] other things like charset and so on
190
191                 // if (content-type is wrong || content-length isn't set)
192                 //     return false
193
194                 if ($header['Content-Type'] != 'application/x-www-form-urlencoded'
195                     || !isset($header['Content-Length'])) {
196                     return FALSE;
197                 }
198                 $post_len = mb_strlen($line, "ASCII");
199                 // printf("INFO: postlen: %d\n", $post_len);
200                 $rest = (int)($header['Content-Length']) - $post_len;
201
202                 if ($rest == 0) {
203                     post_manage($post, $line);
204                 }
205                 else {
206                     $cont = $line;
207                 }
208             }
209             break;
210         }
211         if ($line == "") {
212             $check_post = TRUE;
213             continue;
214         }
215         $split = explode(":", $line, 2);
216         $hea_id = trim(mb_convert_case($split[0], MB_CASE_TITLE, 'UTF-8'));
217         $header[$hea_id] = $split[1];
218     }
219     return $path;
220 }
221
222 function gpcs_var($name, $get, $post, $cookie)
223 {
224     if (isset($GLOBALS[$name]))
225         return FALSE;
226     else if (isset($cookie[$name]))
227         return ($cookie[$name]);
228     else if (isset($post[$name]))
229         return ($post[$name]);
230     else if (isset($get[$name]))
231         return ($get[$name]);
232
233     return FALSE;
234 }
235
236 function headers_render($header, $len)
237 {
238     $cookies = "";
239
240     if (isset($header['cookies'])) {
241         $cookies = $header['cookies']->render();
242         unset($header['cookies']);
243     }
244     if (isset($header['Location'])) {
245         $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
246     }
247     else if (isset($header['HTTP-Response'])) {
248         $s = sprintf("HTTP/1.1 %s\r\n", $header['HTTP-Response']);
249         foreach($header as $key => $value) {
250             if (strtolower($key) == "http-response")
251                 continue;
252             $s .= sprintf("%s: %s\r\n", $key, $value);
253         }
254         if ($len >= 0) {
255             $s .= sprintf("Content-Length: %ld\r\n", $len);
256         }
257     }
258     else {
259         $s = "HTTP/1.1 200 OK\r\n";
260
261         if (!isset($header['Date']))
262             $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
263         if (!isset($header['Connection']))
264             $s .= "Connection: close\r\n";
265         if (!isset($header['Content-Type']))
266             $s .= "Content-Type: text/html\r\n";
267         foreach($header as $key => $value) {
268             $s .= sprintf("%s: %s\r\n", $key, $value);
269         }
270         if ($len >= 0) {
271             $s .= sprintf("Content-Length: %d\r\n", $len);
272         }
273         else {
274             $s .= "Cache-Control: no-cache, must-revalidate\r\n";
275             $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
276             if (!isset($header['Content-Encoding'])) {
277                 $s .= "Content-Encoding: chunked\r\n";
278             }
279             $s .= "Transfer-Encoding: chunked\r\n";
280         }
281         $s .= $cookies;
282     }
283     $s .= "\r\n";
284
285     return ($s);
286 }
287
288 /*
289  *  Caching system using ob php system to cache old style pages
290  *  to a var and than send it with more calm
291  */
292
293 function shutta()
294 {
295   log_rd2("SHUTTA [".connection_status()."] !");
296 }
297
298 register_shutdown_function('shutta');
299
300 /*
301  *  MAIN
302  */
303
304 function get_encoding($header)
305 {
306     $enc = "plain";
307     if (isset($header['Accept-Encoding'])) {
308         $acc = explode(',', $header['Accept-Encoding']);
309
310         if (array_search('gzip', $acc) !== FALSE) {
311             $enc = 'gzip';
312         }
313         else if (array_search('deflate', $acc) !== FALSE) {
314             $enc = 'deflate';
315         }
316     }
317
318     return ($enc);
319 }
320
321 class Cookie {
322     var $attr;
323     // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
324     // string $name  [, string $value  [, int $expire = 0  [, string $path  [, string $domain  [, bool $secure = false  [, bool $httponly = false  ]]]]]] )
325     function Cookie()
326     {
327         $this->attr = array();
328     }
329
330     static function create($name)
331     {
332         $thiz = new Cookie();
333
334         $thiz->attr[$name] = "";
335
336         $argc = func_num_args();
337         for ($i = 1 ; $i < $argc ; $i++) {
338             $arg = func_get_arg($i);
339             switch ($i) {
340             case 1:
341                 $thiz->attr[$name] = urlencode($arg);
342                 break;
343             case 2:
344                 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
345                 break;
346             case 3:
347                 $thiz->attr['Path'] = $arg;
348                 break;
349             case 4:
350                 $thiz->attr['Domain'] = $arg;
351                 break;
352             case 5:
353                 if ($arg == TRUE) {
354                     $thiz->attr['Secure'] = NULL;
355                 }
356                 break;
357             case 6:
358                 if ($arg == TRUE) {
359                     $thiz->attr['HttpOnly'] = NULL;
360                 }
361                 break;
362             default:
363                 return FALSE;
364             }
365         }
366
367         return $thiz;
368     }
369
370     function render()
371     {
372         $r = "Set-Cookie: ";
373         $isfirst = TRUE;
374
375         foreach ($this->attr as $k => $v) {
376             if ($v == NULL) {
377                 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
378             }
379             else {
380                 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
381             }
382             $isfirst = FALSE;
383         }
384         $r .= "\r\n";
385
386         return $r;
387     }
388 }
389
390 class Cookies {
391     var $cookies;
392
393     function Cookies()
394     {
395         $this->cookies = array();
396     }
397
398     function add($name)
399     {
400         if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
401             return (FALSE);
402
403         array_push($this->cookies, $cookie);
404
405         return (TRUE);
406     }
407
408     function render()
409     {
410         $r = "";
411         foreach ($this->cookies as $cookie) {
412             $r .= $cookie->render();
413         }
414
415         return ($r);
416     }
417 }
418
419
420 class Sac_a_push {
421     // maybe fixed_fd is unuseful
422     static $fixed_fd = 3;
423     static $cnt_master = NULL;
424     static $cnt_slave  = NULL;
425
426     var $provider_proxy; // list of provider/browser that offer proxy service
427
428     var $file_socket_pfx;
429     var $unix_socket_pfx;
430     var $direct_socket;   // socket where read direct commands
431     var $socks;
432     var $s2u;             // user associated with input socket
433     var $s2p;             // pending page associated with input socket
434     var $s2c;             // ws sockets in closing phase
435     var $pending_pages;
436     var $is_daemon;
437
438     var $list_web;
439     var $list_cmd;
440     var $in;
441
442     var $debug;
443     var $blocking_mode;
444
445     var $app;
446
447     var $curtime;
448
449     var $rndstr;
450     var $main_loop;
451
452     function Sac_a_push()
453     {
454     }
455
456     function sig_handler($sig)
457     {
458         switch ($sig) {
459         case SIGINT:
460             exit(1);
461             break;
462         case SIGTERM:
463             if (static::$cnt_master != NULL) {
464                     fwrite(static::$cnt_master, "\nshutdown\n");
465                     fflush(static::$cnt_master);
466             }
467             else {
468                 exit(1);
469             }
470             break;
471         case SIGHUP:
472             if (static::$cnt_master != NULL) {
473                 fwrite(static::$cnt_master, "\nreload\n");
474                 fflush(static::$cnt_master);
475             }
476             break;
477         }
478     }
479
480     static function create(&$app, $sockname_pfx, $debug, $blocking_mode, $provider_proxy, $argv)
481     {
482         $thiz = new Sac_a_push();
483
484         $thiz->app = $app;
485
486         $thiz->provider_proxy = ProviderProxy::create();
487
488         $thiz->file_socket_pfx = $sockname_pfx;
489         $thiz->unix_socket_pfx = "unix://$sockname_pfx";
490         $thiz->direct_socket = "unix://${sockname_pfx}_admin.sock";
491         $thiz->debug = $debug;
492         $thiz->list_web = array();
493         $thiz->socks = array();
494         $thiz->s2u  = array();
495         $thiz->s2p  = array();
496         $thiz->s2c  = array();
497         $thiz->pending_pages = array();
498         $thiz->is_daemon = FALSE;
499
500         if (array_search("-d", $argv) !== FALSE || array_search("--daemon", $argv) !== FALSE) {
501             $thiz->is_daemon = TRUE;
502         }
503
504         // create a couple of sockets for control management
505         if (($sockpair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM,
506                                             STREAM_IPPROTO_IP)) == FALSE) {
507             return FALSE;
508         }
509         static::$cnt_master = $sockpair[0];
510         static::$cnt_slave  = $sockpair[1];
511
512         pcntl_signal(SIGTERM, array("Sac_a_push", "sig_handler"));
513         pcntl_signal(SIGINT, array("Sac_a_push", "sig_handler"));
514         pcntl_signal(SIGHUP, array("Sac_a_push", "sig_handler"));
515
516         $thiz->blocking_mode = 0; // 0 for non-blocking
517
518         $thiz->rndstr = "";
519         for ($i = 0 ; $i < 4096 ; $i++) {
520             if (($i % 128) == 0)
521                 $thiz->rndstr .= " ";
522             else
523                 $thiz->rndstr .= chr(mt_rand(65, 90));
524         }
525
526         for ($i = 0 ; $i < USOCK_POOL_N ; $i++) {
527             $file_socket = $thiz->file_socket_pfx . sprintf("%d.sock", $i);
528             if (file_exists($file_socket)) {
529                 unlink($file_socket);
530             }
531         }
532         $file_socket_admin = $thiz->file_socket_pfx . "_admin.sock";
533         if (file_exists($file_socket_admin)) {
534             unlink($file_socket_admin);
535         }
536
537         $old_umask = umask(0);
538         for ($i = 0 ; $i < USOCK_POOL_N ; $i++) {
539             $unix_socket = sprintf("%s%d.sock", $thiz->unix_socket_pfx, $i);
540             if (($list_sock = stream_socket_server($unix_socket, $err, $errs)) === FALSE) {
541                 return (FALSE);
542             }
543             array_push($thiz->list_web, $list_sock);
544         }
545         if (($thiz->list_cmd = stream_socket_server($thiz->direct_socket, $err, $errs)) === FALSE) {
546             return (FALSE);
547         }
548         umask($old_umask);
549         for ($i = 0 ; $i < USOCK_POOL_N ; $i++) {
550             stream_set_blocking($thiz->list_web[$i], $thiz->blocking_mode); # Set the stream to non-blocking
551         }
552         stream_set_blocking($thiz->list_cmd, $thiz->blocking_mode); # Set the stream to non-blocking
553
554         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
555             return(FALSE);
556         }
557
558         $thiz->main_loop = FALSE;
559         $thiz->reload(TRUE, $provider_proxy);
560
561         return ($thiz);
562     }
563
564     function socks_set($sock, $user, $pendpage, $postclose = NULL)
565     {
566         $id = intval($sock);
567
568         $this->socks[$id] = $sock;
569         if ($user != NULL)
570             $this->s2u[$id] = $user;
571         if ($pendpage != NULL)
572             $this->s2p[$id] = $pendpage;
573         if ($postclose != NULL)
574             $this->s2c[$id] = $postclose;
575     }
576
577     function socks_unset($sock)
578     {
579         $id = intval($sock);
580
581         if (isset($this->s2u[$id]))
582             unset($this->s2u[$id]);
583         if (isset($this->s2p[$id]))
584             unset($this->s2p[$id]);
585         if (isset($this->s2c[$id]))
586             unset($this->s2c[$id]);
587         unset($this->socks[$id]);
588     }
589
590     function pendpage_try_addcont(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
591     {
592         $pendpage = PendingPage::pendingpage_continue( $new_socket, $this->curtime, $tout, $method,
593                                                            $header,           $get, $post, $cookie,
594                                                              $path,          $addr, $rest, $cont);
595
596         $pendpage->try_flush($this->curtime);
597         // Add $pendpage to the pendpage array (in any case)
598         // fprintf(STDERR, "IMPORTANT: Pendadd: %d\n", $pendpage->status);
599         $this->pendpage_add($pendpage);
600     }
601
602     function pendpage_try_addflush(&$new_socket, $tout, $enc, $header_out, $content)
603     {
604         $pendpage = PendingPage::pendingpage_flushing($new_socket, $this->curtime, $tout, $enc, $header_out, $content);
605
606         if ($pendpage->try_flush($this->curtime) == FALSE) {
607             // Add $pendpage to the pendpage array
608             $this->pendpage_add($pendpage);
609         }
610     }
611
612     function pendpage_add($pendpage)
613     {
614         array_push($this->pending_pages, $pendpage);
615         $this->socks_set($pendpage->socket_get(), NULL, $pendpage);
616     }
617
618     function pendpage_rem($pendpage)
619     {
620         $sock = $pendpage->socket_get();
621         if (($key = array_search($pendpage, $this->pending_pages)) !== FALSE) {
622             unset($this->pending_pages[$key]);
623         }
624         else {
625             fprintf(STDERR, "WARNING: pendpage not found\n");
626         }
627         $this->socks_unset($sock);
628         fprintf(STDERR, "PP_REM: %d\n", intval($sock));
629     }
630
631
632     function pendpage_try_addwait(&$new_socket, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont)
633     {
634         $pendpage = PendingPage::pendingpage_waiting($new_socket, $this->curtime, $tout, $method, $header, $get, $post, $cookie, $path, $addr, $rest, $cont);
635         /*
636         if ($pendpage->try_flush($this->curtime) == FALSE) {
637             // Add $pendpage to the pendpage array
638             */
639         $this->pendpage_add($pendpage);
640         /*
641         }
642         */
643     }
644
645     function garbage_manager($force)
646     {
647         $this->app->garbage_manager($force);
648
649         foreach ($this->socks as $k => $sock) {
650             $id = intval($sock);
651             if (isset($this->s2c[$id])) {
652                 $postclose = $this->s2c[$id];
653                 if ($postclose->read('', $this->curtime) == 0) {
654                     fclose($sock);
655                     $this->socks_unset($sock);
656                 }
657             }
658             else if (isset($this->s2u[$id])) {
659                 $user = $this->s2u[$id];
660                 if ($user->the_end) {
661                     if (($user->rd_toflush == FALSE && $user->rd_step == $user->step)
662                         || $user->rd_endtime_is_expired($this->curtime)) {
663                         if ($user->rd_socket_get() != NULL) {
664                             $user->rd_socket_set(NULL);
665                         }
666                         unset($this->socks[$id]);
667                         unset($this->s2u[$id]);
668                         fclose($sock);
669                         // printf("CLOSE ON GARBAGE MANAGER\n");
670                     }
671                 }
672             }
673         }
674         $this->app->users_cleanup();
675     }
676
677     function check_globals()
678     {
679         GLOBAL $_globals_list;
680         foreach ($_globals_list as $g) {
681             if (!array_search($g, $GLOBALS) || !isset($GLOBALS[$g])) {
682                 error_log(sprintf("Global [%s] not declared", $g));
683                 return FALSE;
684             }
685         }
686         return TRUE;
687     }
688
689     function run()
690     {
691         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
692
693         GLOBAL $G_alarm_passwd, $G_ban_list, $G_black_list, $G_cloud_smasher, $G_provider_proxy;
694         GLOBAL $G_btrace_pref_sub, $G_dbauth;
695         GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
696         GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
697         GLOBAL $G_room_roadmap, $G_shutdown, $G_profile;
698         GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
699         GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
700         GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
701         GLOBAL $G_with_splash, $G_sidebanner, $G_sidebanner_idx;
702         GLOBAL $G_with_topbanner;
703         GLOBAL $G_tos_vers, $G_tos_fname, $G_tos_dtsoft, $G_tos_dthard, $G_tos_idx, $G_doc_path;
704
705         if (!$this->check_globals()) {
706             fprintf(STDERR, "Take a look to the phplog file, GLOBALS missing!\n");
707             sleep(10);
708         }
709
710         if ($this->main_loop) {
711             return (FALSE);
712         }
713
714         $this->main_loop = TRUE;
715
716         $list_web_arr = array();
717         for ($i = 0 ; $i < USOCK_POOL_N ; $i++) {
718             $list_web_arr[intval($this->list_web[$i])] = $this->list_web[$i];
719         }
720
721         log_legal(time(), '127.0.0.1', FALSE, 'MAIN', 'LOG:START');
722
723         $lastime = 0;
724         $dump_users = TRUE;
725         $sock_shard_cur = -1;
726
727         $mtime_start = microtime(TRUE);
728         $mtsum_idle = 0.0;
729         $mtsum_read = 0.0;
730         $mtsum_garb = 0.0;
731         $mtsum_unfi = 0.0;
732         $mtsum_mana = 0.0;
733
734         while ($this->main_loop) {
735             $mtime_begin = microtime(TRUE);
736             $sock_shard_cur = ($sock_shard_cur + 1) % SOCK_SHARD_N;
737             $this->app->sess_cur_set(FALSE);
738             $this->curtime = time();
739             if ($lastime != ($this->curtime >> 2)) {
740                 if ($G_profile == TRUE) {
741                     $mtime_finish = microtime(TRUE);
742                     $mtime_diff = ($mtime_finish - $mtime_start);
743                     $mtime_idle = 100.0 * $mtsum_idle / $mtime_diff;
744                     $mtime_read = 100.0 * $mtsum_read / $mtime_diff;
745                     $mtime_garb = 100.0 * $mtsum_garb / $mtime_diff;
746                     $mtime_unfi = 100.0 * $mtsum_unfi / $mtime_diff;
747                     $mtime_mana = 100.0 * $mtsum_mana / $mtime_diff;
748
749                     log_legal(time(), '127.0.0.1', FALSE, 'MAIN',
750                     sprintf('LOG:PROF: tot(%.3f) idle: %.2f  read: %.2f  garb: %.2f  unfi: %.2f  mana: %.2f',
751                     $mtime_diff, $mtime_idle, $mtime_read, $mtime_garb, $mtime_unfi, $mtime_mana
752                     ));
753                     $mtsum_idle = 0.0;
754                     $mtsum_read = 0.0;
755                     $mtsum_garb = 0.0;
756                     $mtsum_unfi = 0.0;
757                     $mtsum_mana = 0.0;
758                     $mtime_start = $mtime_finish;
759                 }
760                 fprintf(STDERR, "\nIN LOOP: Current opened: %d  pending_pages: %d\n", count($this->socks), count($this->pending_pages));
761             }
762
763             /* Prepare the read array */
764             /* // when we manage it ... */
765             /* if ($shutdown)  */
766             /*     $read   = array_merge(array("$in" => $in), $socks); */
767             /* else */
768             $pre_read = array_merge($list_web_arr, array(
769                 intval($this->list_cmd) => $this->list_cmd,
770                 intval(static::$cnt_slave) => static::$cnt_slave),
771             $this->socks);
772             if ($this->is_daemon == FALSE) {
773                 $read = array_merge($pre_read, array(intval($this->in) => $this->in));
774             }
775             else {
776                 $read = $pre_read;
777             }
778
779             if ($this->debug > 1) {
780                 printf("PRE_SELECT\n");
781                 print_r($read);
782             }
783             $write  = NULL;
784             $except = NULL;
785             $num_changed_sockets = @stream_select($read, $write, $except, 0, 500000);
786
787             if ($G_profile) {
788                 $mtime_idle = microtime(TRUE);
789                 $mtsum_idle += $mtime_idle - $mtime_begin;
790             }
791             if ($num_changed_sockets == 0) {
792                 // printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
793                 ;
794             }
795             else if ($num_changed_sockets > 0) {
796                 if ($lastime != ($this->curtime >> 2)) {
797                     printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
798                 }
799                 if ($this->debug > 1) {
800                     print_r($read);
801                 }
802                 /* At least at one of the sockets something interesting happened */
803                 foreach ($read as $i => $sock) {
804                     $id = intval($sock);
805                     $manage_page = FALSE;
806                     /* is_resource check is required because there is the possibility that
807                        during new request an old connection is closed */
808                     if (!is_resource($sock)) {
809                         continue;
810                     }
811                     $list_web_idx = array_search($sock, $this->list_web, TRUE);
812                     if ($list_web_idx !== FALSE) {
813                         $list_web_usock = $this->list_web[$list_web_idx];
814                         // printf("NUOVA CONNEX\n");
815                         if (($new_unix = stream_socket_accept($list_web_usock)) == FALSE) {
816                             printf("SOCKET_ACCEPT FAILED\n");
817                             continue;
818                         }
819                         $stream_info = "";
820                         $method      = "";
821                         $get         = array();
822                         $post        = array();
823                         $cookie      = array();
824                         $rest        = 0;
825                         $cont        = "";
826                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
827                             // printf("NEW_SOCKET: %d\n", intval($new_socket));
828                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
829                             // error_log(sprintf("RECEIVED HEADER:\n%s", $stream_info));
830                             if (($path = spu_process_info($stream_info, $method, $header,
831                                                           $get, $post, $cookie, $rest, $cont))
832                                 == FALSE) {
833                                 fprintf(STDERR, "TODO: fix wrong header management\n");
834                             }
835
836                             // We try to get real IP from header (passed by proxy) and then fallback to direct connection IP
837                             // error_log(sprintf("addr: [%s]", $addr));
838                             // error_log(sprintf("X-Real-Ip: [%s]", array_key_exists('X-Real-Ip', $header) ? $header['X-Real-Ip'] : "Not exists"));
839                             if (array_key_exists('X-Real-Ip', $header)) {
840                                 $addr = $header['X-Real-Ip'];
841                             }
842                             else {
843                                 $addr = addrtoipv4(stream_socket_get_name($new_socket, TRUE));
844                             }
845
846                             // FOR TEST $header['X-Forwarded-For'] = '154.155.22.33';
847                             $addr = $this->pproxy_realip($header, $addr);
848
849                             // printf("PATH: [%s] [%s]\n", $path, print_r($header, TRUE));
850                             if ($method == "POST" && $rest > 0) {
851                                 if (isset($header['Expect']) && $header['Expect'] == '100-continue') {
852                                     // fprintf(STDERR, "\nPOSTA DE CHE\n\n");
853                                     $this->pendpage_try_addcont($new_socket, 20,
854                                                                 $method, $header, $get, $post, $cookie,
855                                                                 $path, $addr, $rest, $cont);
856                                 }
857                                 else {
858                                     $this->pendpage_try_addwait($new_socket, 20,
859                                                                 $method, $header, $get, $post, $cookie,
860                                                                 $path, $addr, $rest, $cont);
861                                 }
862                             }
863                             else {
864                                 $manage_page = TRUE;
865                             }
866
867                             // printf("number of sockets after %d\n", count($this->socks));
868                         }
869                         else {
870                             printf("WARNING: ancillary_getstream failed\n");
871                         }
872                     }
873                     else if ($sock === $this->list_cmd) {
874                         // printf("NUOVA DIRECT CONNEX\n");
875                         if (($new_unix = stream_socket_accept($this->list_cmd)) == FALSE) {
876                             printf("SOCKET_ACCEPT FAILED\n");
877                             continue;
878                         }
879                         stream_set_blocking($new_unix, $this->blocking_mode);
880                         $this->direct_mgmt($new_unix);
881                     } // not socket_list nor socket_list_cmd
882                     else if ($id % SOCK_SHARD_N == $sock_shard_cur) {  // already opened socket
883                         $buf = fread($sock, 4096);
884                         // if socket is closed
885                         if ($buf == FALSE || mb_strlen($buf, "ASCII") == 0 || feof($sock)) {
886                             $postclose = NULL;
887                             // close socket case
888                             if ($buf == FALSE) {
889                                 // printf("INFO: read return false\n");
890                                 ;
891                             }
892                             if (array_search($sock, $this->list_web, TRUE) !== FALSE) {
893                                 // printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
894                                 return(21);
895                             }
896                             else if ($sock === $this->list_cmd) {
897                                 // printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
898                                 return(23);
899                             }
900                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
901                                 // printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
902                                 return(22);
903                             }
904                             else {
905                                 unset($this->socks[$id]);
906                                 if (isset($this->s2u[$id])) {
907                                     // $user_a[$s2u[$id]]->disable();
908                                     if ($this->s2u[$id]->rd_socket_get() != NULL) {
909                                         // try to send close frame (for websocket)
910                                         $clo = $this->s2u[$id]->stream_close();
911                                         $postclose = $user->stream_postclose_get($sock, $this->curtime);
912                                         $clo_l = mb_strlen($clo, "ASCII");
913                                         @fwrite($sock, $clo, $clo_l);
914                                         $this->s2u[$id]->rd_socket_set(NULL);
915                                     }
916                                     unset($this->s2u[$id]);
917                                 }
918                             }
919                             if ($postclose != NULL) {
920                                 // print("POSTCLOSE found!");
921                                 $this->socks_set($sock, NULL, NULL, $postclose);
922                             }
923                             else {
924                                 fclose($sock);
925                             }
926                             // printf("CLOSE ON READ\n");
927
928                             if ($this->debug > 1) {
929                                 printf("post unset\n");
930                                 print_r($this->socks);
931                             }
932                         }  // if ($buf == FALSE || mb_strlen($buf, "ASCII") == 0) {
933                         else { // data on the socket
934                             if ($this->debug > 1) {
935                                 print_r($read);
936                             }
937                             if (array_search($sock, $this->list_web, TRUE) !== FALSE) {
938                                 // printf("Arrivati %d bytes da list\n", mb_strlen($buf, "ASCII"));
939                                 ;
940                             }
941                             else if ($sock === $this->list_cmd) {
942                                 // printf("Arrivati %d bytes da list_cmd\n", mb_strlen($buf, "ASCII"));
943                                 ;
944                             }
945                             else if ($sock === $this->in || $sock === static::$cnt_slave) {
946                                 // printf("Arrivati %d bytes da stdin\n", mb_strlen($buf, "ASCII"));
947                                 $line = trim($buf);
948                                 if ($line == "reload") {
949                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
950                                     $this->reload(FALSE, $G_provider_proxy);
951                                     $this->app->reload(FALSE, $G_ban_list, $G_black_list,
952                                                        $G_cloud_smasher);
953                                     if (!$this->check_globals()) {
954                                         fprintf(STDERR, "Take a look to the phplog file, GLOBALS missing!\n");
955                                         sleep(10);
956                                     }
957                                     global_dump();
958                                 }
959                                 else if ($line == "dump") {
960                                     $dump_users = TRUE;
961                                 }
962                                 else if ($line == "shutdown" || $line == "sd") {
963                                     if ($this->app->dump_data()) {
964                                         return(0);
965                                     }
966                                     else {
967                                         return(1);
968                                     }
969                                 }
970                             }
971                             else {  // data arrived from not special socket
972                                 $key = array_search("$sock", $this->socks);
973                                 // fprintf(STDERR, "Arrivati %d bytes dalla socket n. %d\n", mb_strlen($buf, "ASCII"), $key);
974
975                                 if (isset($this->s2u[$id])) {
976                                     //
977                                     //  TODO:
978                                     //     fix $addr
979                                     //     fix $this->pendpage_try_addflush below (probably not required)
980                                     //
981                                     $addr = "127.0.0.1";
982                                     $user = $this->s2u[$id];
983
984                                     // fprintf(STDERR, 'POST USER');
985                                     if ($user && $user->rd_transp && strpos($user->rd_transp->type, "websocket") !== FALSE) {
986                                         $clie_cmd = $user->rd_transp->unchunk($buf, $sock);
987                                         $clie_cmd = json_decode($clie_cmd, TRUE);
988                                         // fprintf(STDERR, "HERE WE ARE INCOMING DATA [%s]\n", print_r($clie_cmd, TRUE));
989
990                                         $wr_addr = substr(parse_url($clie_cmd["target"])["path"], strlen(SITE_PREFIX));
991                                         if ($wr_addr == "index_wr.php") {
992                                             ob_start();
993                                             // complete: index_wr_main($this->app, $addr, $get, $post, $cookie);
994                                             index_wr_main($this->app, $addr, $clie_cmd, NULL, NULL);
995                                             $content = ob_get_contents();
996                                             ob_end_clean();
997                                         }
998                                         else if ($wr_addr == "briskin5/index_wr.php") {
999                                             $table_idx = $clie_cmd['table_idx'];
1000                                             $table_token = $clie_cmd['table_token'];
1001
1002                                             if (($bri = $this->app->match_get($table_idx, $table_token)) != FALSE) {
1003                                                 ob_start();
1004                                                 bin5_index_wr_main($bri, $addr, $clie_cmd, NULL, NULL);
1005                                                 $content = ob_get_contents();
1006                                                 ob_end_clean();
1007                                             }
1008                                         }
1009                                         else {
1010                                             fprintf(STDERR, "Unknown page [%s]\n", $wr_addr);
1011                                         }
1012                                         /*
1013                                           briskin5/index_wr.php
1014
1015                                           if (isset($table_idx) && isset($table_token)) {
1016                                           if (($bri = $s_a_p->app->match_get($table_idx, $table_token)) != FALSE) {
1017                                           ob_start();
1018                                           bin5_index_wr_main($bri, $addr, $get, $post, $cookie);
1019                                           $content = ob_get_contents();
1020                                           ob_end_clean();
1021                                           }
1022                                           else {
1023                                           $content = "Bin5 Load data error";
1024                                           }
1025                                           }
1026                                           else {
1027                                           $content = "Bin5 Load data error";
1028                                           }
1029                                           $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
1030                                         */
1031                                     }
1032                                 }
1033                                 else {
1034                                     fprintf(STDERR, "User associated with ID: %s not found\n", $id);
1035                                 }
1036
1037                                 if (isset($this->s2p[$id])) {
1038                                     $this->s2p[$id]->rest -= mb_strlen($buf, "ASCII");
1039                                     $this->s2p[$id]->cont .= $buf;
1040                                     if ($this->s2p[$id]->rest <= 0) {
1041                                         $header = $new_socket = $path = $addr = $get = $cookie = 0;
1042                                         $post = array();
1043
1044                                         $this->s2p[$id]->context_get($header, $new_socket, $path, $addr, $get, $post, $cookie);
1045                                         $this->pendpage_rem($this->s2p[$id]);
1046                                         fprintf(STDERR, "SOCKET RUN: %s\n", $new_socket);
1047
1048                                         $manage_page = TRUE;
1049                                     }
1050                                 }
1051
1052                                 // postclose case
1053                                 if (isset($this->s2c[$id])) {
1054                                     $postclose = $this->s2c[$id];
1055                                     // printf("POSTCLOSE: found pc in s2c list\n");
1056                                     if ($postclose->read($buf, $this->curtime) == 0) {
1057                                         printf("POSTCLOSE: received end opcode, close\n");
1058                                         fclose($sock);
1059                                         $this->socks_unset($sock);
1060                                     }
1061                                 }
1062                             }
1063                         }
1064                     }
1065
1066                     if ($manage_page == TRUE) {
1067                         /*
1068                         printf("M: %s\nHEADER:\n", $method);
1069                         print_r($header);
1070                         printf("GET:\n");
1071                         print_r($get);
1072                         printf("POST:\n");
1073                         print_r($post);
1074                         printf("COOKIE:\n");
1075                         print_r($cookie);
1076                         */
1077
1078                         $header_out = array();
1079                         // TODO: MOVE DOWN request_mgr to factorize new_sockets and POST closed
1080                         $rret = FALSE;
1081                         if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
1082                             $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
1083                         }
1084                         if ($rret == FALSE) {
1085                             // FIXME: manage 404 !!!
1086                             printf("TODO: fix unknown page: %s\n", $path);
1087                             fclose($new_socket);
1088                         }
1089                     }
1090                 }
1091             }
1092             if ($G_profile) {
1093                 $mtime_read = microtime(TRUE);
1094                 $mtsum_read += $mtime_read - $mtime_idle;
1095             }
1096
1097             $this->garbage_manager(FALSE);
1098
1099             if ($G_profile) {
1100                 $mtime_garb = microtime(TRUE);
1101                 $mtsum_garb += $mtime_garb - $mtime_read;
1102             }
1103
1104             /* manage unfinished pages */
1105             foreach ($this->pending_pages as $k => $pendpage) {
1106                 // TODO: try_flush if exists in the class
1107                 if ($pendpage->try_flush($this->curtime) == TRUE) {
1108                     unset($this->pending_pages[$k]);
1109                 }
1110             }
1111
1112             if ($G_profile) {
1113                 $mtime_unfi = microtime(TRUE);
1114                 $mtsum_unfi += $mtime_unfi - $mtime_garb;
1115             }
1116
1117             /*
1118                $response:                        raw stream data not sent
1119                $content:                         html consistent data (<script bla bla>)
1120                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
1121             */
1122
1123             /* manage open streaming */
1124             foreach ($this->socks as $k => $sock) {
1125                 $id = intval($sock);
1126                 if (isset($this->s2u[$id])) {
1127                     $user = $this->s2u[$id];
1128
1129                     if ($user->rd_toflush) {
1130                         if (fflush($sock) == FALSE)
1131                             continue;
1132                         else
1133                             $user->rd_toflush = FALSE;
1134                     }
1135                     $response = $user->rd_cache_get();
1136                     $do_ping = FALSE;
1137                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
1138                         $do_ping = TRUE;
1139                     }
1140                     else {
1141                         $user->ping_req = FALSE;
1142                     }
1143
1144                     if ($response == "") {
1145                         $content = "";
1146                         $user->stream_main($content, $get, $post, $cookie);
1147                         if ($dump_users) {
1148                            printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
1149                         }
1150                         if ($do_ping && $user->ping_req == FALSE) {
1151                             $content .= $user->stream_keepalive(TRUE);
1152                             $user->ping_req = TRUE;
1153                         }
1154                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
1155                             $content = $user->stream_keepalive(FALSE);
1156                         }
1157                         if ($content != "") {
1158                             $response = $user->chunked_content($content);
1159                         }
1160                     }
1161
1162                     if ($response != "") {
1163                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
1164                         // echo "SPIA: [".$response."]\n";
1165                         $response_l = mb_strlen($response, "ASCII");
1166                         $wret = @fwrite($sock, $response, $response_l);
1167                         if ($wret < $response_l) {
1168                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
1169                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
1170                         }
1171                         else {
1172                             $user->rd_cache_set("");
1173                         }
1174                         if (fflush($sock) == FALSE) {
1175                             $user->rd_toflush = TRUE;
1176                             continue;
1177                         }
1178                         $user->rd_kalive_reset($this->curtime);
1179                     }
1180
1181                     // close socket after a while to prevent client memory consumption
1182                     if ($user->rd_endtime_is_expired($this->curtime)) {
1183                         $postclose = $user->stream_postclose_get($sock, $this->curtime);
1184                         if ($user->rd_socket_get() != NULL) {
1185                             $user->rd_socket_set(NULL);
1186                         }
1187                         unset($this->socks[$id]);
1188                         unset($this->s2u[$id]);
1189                         $clo = $user->stream_close();
1190                         $clo_l = mb_strlen($clo, "ASCII");
1191                         @fwrite($sock, $clo, $clo_l);
1192                         if ($postclose) {
1193                             $this->socks_set($sock, NULL, NULL, $postclose);
1194                         }
1195                         else {
1196                             fclose($sock);
1197                         }
1198                         // printf("CLOSE ON LOOP\n");
1199                     }
1200                 }  // if (isset($this->s2u[$id]...
1201             }  // foreach ($this->socks...
1202             if ($G_profile) {
1203                 $mtime_mana = microtime(TRUE);
1204                 $mtsum_mana += $mtime_mana - $mtime_unfi;
1205             }
1206             $dump_users = FALSE;
1207             printf("#");
1208             if (defined('CURL_DE_SAC_VERS')) {
1209                 $this->app->cds->process();
1210             }
1211             $lastime = ($this->curtime >> 2);
1212         }  // while (...
1213     }  // function run(...
1214
1215     function pproxy_realip(&$header, $ip_str)
1216     {
1217         return ($this->provider_proxy->realip($header, $ip_str));
1218     }
1219
1220     function reload($is_first, $prov_proxy)
1221     {
1222         fprintf(STDERR, "SAP RELOAD STUFF (%d)\n", count($prov_proxy));
1223
1224         $this->provider_proxy->update($prov_proxy);
1225     }
1226
1227     function direct_command($cmdstr)
1228     {
1229         GLOBAL $G_alarm_passwd;
1230
1231         $cmd = cmd_deserialize($cmdstr);
1232
1233         if (!isset($cmd['cmd'])) {
1234             return cmd_return(500, 'no cmd found');
1235         }
1236         // "cmd" => "userauth", "sess" => 'xxxxxxxxxxx', 'private' => 'it_must_be_correct',
1237         //           'the_end' => 'true' );
1238         // cmd=userauth&sess=52d796ac08c47&private=yourpasswd192.168.122.152d796ac08c47&the_end=true
1239         if ($cmd['cmd'] == 'userauth') {
1240             if (!isset($cmd['sess']) || !isset($cmd['private'])) {
1241                 return cmd_return(401, 'malformed cmd');
1242             }
1243             $idx = -1;
1244             if (($user = $this->app->get_user($cmd['sess'], $idx)) == FALSE)
1245                 return cmd_return(402, 'user not found');
1246
1247             if (($user->flags & USER_FLAG_TY_ADMIN) == 0x00)
1248                 return cmd_return(403, 'permission denied');
1249
1250             if (md5($G_alarm_passwd.$user->ip.$user->sess) != $cmd['private'])
1251                 return cmd_return(404, 'authentication failed ['.$cmd['private'].']['.$G_alarm_passwd.$user->ip.$user->sess.']');
1252
1253             return cmd_return(200, 'success');
1254         }
1255
1256         return cmd_return(501, 'no cmd found');
1257     }
1258
1259     function direct_mgmt($socket)
1260     {
1261         printf("DIRECT: begin\n");
1262         $st = DIRECT_ST_READ;
1263         $cmd_all = "";
1264         $endtime = $this->curtime + 3;
1265
1266         while(time() <= $endtime) {
1267             printf("DIRECT: init loop %d\n", $st);
1268             if ($st == DIRECT_ST_READ) {
1269                 $buf = fread($socket, 4096);
1270                 if ($buf == FALSE && feof($socket)) {
1271                     break;
1272                 }
1273                 else if ($buf != FALSE && strlen($buf) > 0) {
1274                     $cmd_all .= $buf;
1275
1276                     if (substr(trim($cmd_all), -13) == "&the_end=true") {
1277                         $output_arr = $this->direct_command($cmd_all);
1278                         $output = cmd_serialize($output_arr);
1279                         $output_cur = 0;
1280                         $output_len = mb_strlen($output, "ASCII");
1281                         $st = DIRECT_ST_WRITE;
1282                         continue;
1283                     }
1284                 }
1285             }
1286             else if ($st == DIRECT_ST_WRITE)  {
1287                 $ret = fwrite($socket, $output, $output_len);
1288                 if ($ret === FALSE) {
1289                     if (feof($socket)) {
1290                         break;
1291                     }
1292                 }
1293                 else if ($ret > 0 && $ret < $output_len) {
1294                     $output = substr($output, -($output_len - $ret));
1295                     $output_len -= $ret;
1296                     continue;
1297                 }
1298                 else if ($ret == $output_len) {
1299                     fclose($socket);
1300                     return TRUE;
1301                 }
1302             }
1303             // probably not needed
1304             // usleep(10000);
1305         }
1306
1307         fclose($socket);
1308         return FALSE;
1309     }
1310 } // class Sac_a_push
1311 ?>