e283fe3a2f28717d885c753b533810495ac77e7a
[oweals/minetest.git] / util / master / master.cgi
1 #!/usr/bin/perl
2
3 =info
4 install:
5  cpan JSON JSON::XS
6  touch list_full list
7  chmod a+rw list_full list log.log
8
9 freebsd:
10  www/fcgiwrap www/nginx
11
12 rc.conf.local:
13 nginx_enable="YES"
14 fcgiwrap_enable="YES"
15 fcgiwrap_user="www"
16
17 nginx:
18
19         location / {
20             index  index.html;
21             add_header Access-Control-Allow-Origin *;
22         }
23         location /announce {
24             fastcgi_pass   unix:/var/run/fcgiwrap/fcgiwrap.sock;
25             fastcgi_param  SCRIPT_FILENAME $document_root/master.cgi;
26             include        fastcgi_params;
27         }
28
29
30 apache .htaccess:
31  AddHandler cgi-script .cgi
32  DirectoryIndex index.html
33  Options +ExecCGI +FollowSymLinks
34  Order allow,deny
35  <FilesMatch (\.(html?|cgi|fcgi|css|js|gif|png|jpe?g|ico)|(^)|\w+)$>
36   Allow from all
37  </FilesMatch>
38  Deny from all
39  <ifModule mod_headers.c>
40      Header set Access-Control-Allow-Origin: *
41  </ifModule>
42
43
44
45 =cut
46
47 use strict;
48 no strict qw(refs);
49 use warnings "NONFATAL" => "all";
50 no warnings qw(uninitialized);
51 use utf8;
52 use Socket;
53 BEGIN {
54     if ($Socket::VERSION ge '2.008') {
55         eval qq{use Socket qw(getaddrinfo getnameinfo NI_NUMERICHOST NIx_NOSERV)}; # >5.16
56     } else {
57         eval qq{use Socket6 qw(getaddrinfo getnameinfo NI_NUMERICHOST NIx_NOSERV)}; # <5.16
58     }
59 };
60 use Time::HiRes qw(time sleep);
61 use IO::Socket::IP;
62 use JSON;
63 use Net::Ping;
64 #use Data::Dumper;
65 our $root_path;
66 ($ENV{'SCRIPT_FILENAME'} || $0) =~ m|^(.+)[/\\].+?$|;    #v0w
67 $root_path = $1 . '/' if $1;
68 $root_path =~ s|\\|/|g;
69
70 our %config = (
71     #debug        => 1,
72     list_full    => $root_path . 'list_full',
73     list_pub     => $root_path . 'list',
74     log          => $root_path . 'log.log',
75     time_purge   => 86400 * 30,
76     time_alive   => 650,
77     source_check => 1,
78     ping_timeout => 3,
79     ping         => 1,
80     mineping     => 1,
81     pingable     => 1,
82     trusted      => [qw( 176.9.122.10 )],       #masterserver self ip - if server on same ip with masterserver doesnt announced
83     #blacklist => [], # [qw(2.3.4.5 4.5.6.7 8.9.0.1), '1.2.3.4', qr/^10\.20\.30\./, ], # list, or quoted, ips, or regex
84 );
85 do($root_path . 'config.pl');
86 our $ping = Net::Ping->new("udp", $config{ping_timeout});
87 $ping->hires();
88
89 sub get_params_one(@) {
90     local %_ = %{ref $_[0] eq 'HASH' ? shift : {}};
91     for (@_) {
92         tr/+/ /, s/%([a-f\d]{2})/pack 'H*', $1/gei for my ($k, $v) = /^([^=]+=?)=(.+)$/ ? ($1, $2) : (/^([^=]*)=?$/, /^-/);
93         $_{$k} = $v;
94     }
95     wantarray ? %_ : \%_;
96 }
97
98 sub get_params(;$$) {    #v7
99     my ($string, $delim) = @_;
100     $delim ||= '&';
101     read(STDIN, local $_ = '', $ENV{'CONTENT_LENGTH'}) if !$string and $ENV{'CONTENT_LENGTH'};
102     local %_ =
103       $string
104       ? get_params_one split $delim, $string
105       : (get_params_one(@ARGV), map { get_params_one split $delim, $_ } split(/;\s*/, $ENV{'HTTP_COOKIE'}), $ENV{'QUERY_STRING'}, $_);
106     wantarray ? %_ : \%_;
107 }
108
109 sub get_params_utf8(;$$) {
110     local $_ = &get_params;
111     utf8::decode $_ for %$_;
112     wantarray ? %$_ : $_;
113 }
114
115 sub file_rewrite(;$@) {
116     local $_ = shift;
117     return unless open my $fh, '>', $_;
118     print $fh @_;
119 }
120
121 sub printlog(;@) {
122     #local $_ = shift;
123     return unless open my $fh, '>>', $config{log};
124     print $fh (join ' ', @_), "\n";
125 }
126
127 sub file_read ($) {
128     open my $f, '<', $_[0] or return;
129     local $/ = undef;
130     my $ret = <$f>;
131     close $f;
132     return \$ret;
133 }
134
135 sub read_json {
136     my $ret = {};
137     eval { $ret = JSON->new->utf8->relaxed(1)->decode(${ref $_[0] ? $_[0] : file_read($_[0]) or \''} || '{}'); };    #'mc
138     printlog "json error [$@] on [", ${ref $_[0] ? $_[0] : \$_[0]}, "]" if $@;
139     $ret;
140 }
141
142 sub printu (@) {
143     for (@_) {
144         print($_), next unless utf8::is_utf8($_);
145         my $s = $_;
146         utf8::encode($s);
147         print($s);
148     }
149 }
150
151 sub float {
152     return ($_[0] < 8 and $_[0] - int($_[0]))
153       ? sprintf('%.' . ($_[0] < 1 ? 3 : ($_[0] < 3 ? 2 : 1)) . 'f', $_[0])
154       : int($_[0]);
155
156 }
157
158 sub mineping ($$) {
159     my ($addr, $port) = @_;
160     printlog "mineping($addr, $port)" if $config{debug};
161     my $data;
162     my $time = time;
163     eval {
164         my $socket = IO::Socket::IP->new(
165             'PeerAddr' => $addr,
166             'PeerPort' => $port,
167             'Proto'    => 'udp',
168             'Timeout'  => $config{ping_timeout},
169         );
170         $socket->send("\x4f\x45\x74\x03\x00\x00\x00\x01");
171         local $SIG{ALRM} = sub { die "alarm time out"; };
172         alarm $config{ping_timeout};
173         $socket->recv($data, POSIX::BUFSIZ) or die "recv: $!";
174         alarm 0;
175         1;    # return value from eval on normalcy
176     } or return 0;
177     return 0 unless length $data;
178     $time = float(time - $time);
179     printlog "recvd: ", length $data, " [$time]" if $config{debug};
180     return $time;
181 }
182
183 sub request (;$) {
184     my ($r) = @_;
185     $r ||= \%ENV;
186     my $param = get_params_utf8;
187     my $after = sub {
188         if ($param->{json}) {
189             my $j = {};
190             eval { $j = JSON->new->decode($param->{json}) || {} };
191             $param->{$_} = $j->{$_} for keys %$j;
192             delete $param->{json};
193         }
194         if (%$param) {
195             s/^false$// for values %$param;
196             $param->{ip} = $r->{REMOTE_ADDR};
197             $param->{ip} =~ s/^::ffff://;
198             for (@{$config{blacklist}}) {
199                 return if $param->{ip} ~~ $_;
200             }
201             $param->{address} ||= $param->{ip};
202             if ($config{source_check}) {
203                 (my $err, local @_) = getaddrinfo($param->{address});
204                 my $addrs = [ map{(getnameinfo($_->{addr}, NI_NUMERICHOST, NIx_NOSERV))[1]} @_];
205                 if (!($param->{ip} ~~ $addrs) and !($param->{ip} ~~ $config{trusted})) {
206                     printlog("bad address (", @$addrs, ")[$param->{address}] ne [$param->{ip}] [$err]") if $config{debug};
207                     return;
208                 }
209             }
210             $param->{port} ||= 30000;
211             $param->{key} = "$param->{ip}:$param->{port}";
212             $param->{off} = time if $param->{action} ~~ 'delete';
213             if ($config{ping} and $param->{action} ne 'delete') {
214                 if ($config{mineping}) {
215                     $param->{ping} = mineping($param->{ip}, $param->{port});
216                 } else {
217                     $ping->port_number($param->{port});
218                     $ping->service_check(0);
219                     my ($pingret, $duration, $ip) = $ping->ping($param->{address});
220                     if ($ip ne $param->{ip} and !($param->{ip} ~~ $config{trusted})) {
221                         printlog "strange ping ip [$ip] != [$param->{ip}]" if $config{debug};
222                         return if $config{source_check} and !($param->{ip} ~~ $config{trusted});
223                     }
224                     $param->{ping} = $duration if $pingret;
225                     printlog " PING t=$config{ping_timeout}, $param->{address}:$param->{port} = ( $pingret, $duration, $ip )" if $config{debug};
226                 }
227             }
228             my $list = read_json($config{list_full}) || {};
229             printlog "readed[$config{list_full}] list size=", scalar @{$list->{list}};
230             my $listk = {map { $_->{key} => $_ } @{$list->{list}}};
231             my $old = $listk->{$param->{key}};
232             $param->{time} = $old->{time} if $param->{off};
233             $param->{time} ||= int time;
234             $param->{start} = $param->{action} ~~ 'start' ? $param->{time} : $old->{start} || $param->{time};
235             delete $param->{start} if $param->{off};
236             $param->{first} ||= $old->{first} || $old->{time} || $param->{time};
237             $param->{clients_top} = $old->{clients_top} if $old->{clients_top} > $param->{clients};
238             $param->{clients_top} ||= $param->{clients} || 0;
239             $param->{mods} ||= $old->{mods};
240             delete $param->{action};
241             $listk->{$param->{key}} = $param;
242             #printlog Dumper $param;
243             $list->{list} = [grep { $_->{time} > time - $config{time_purge} } values %$listk];
244             file_rewrite($config{list_full}, JSON->new->encode($list));
245             printlog "writed[$config{list_full}] list size=", scalar @{$list->{list}} if $config{debug};
246             $list->{list} = [
247                 sort { $b->{clients} <=> $a->{clients} || $a->{start} <=> $b->{start} }
248                   grep { $_->{time} > time - $config{time_alive} and !$_->{off} and (!$config{ping} or !$config{pingable} or $_->{ping}) }
249                   @{$list->{list}}
250             ];
251             file_rewrite($config{list_pub}, JSON->new->encode($list));
252             printlog "writed[$config{list_pub}] list size=", scalar @{$list->{list}} if $config{debug};
253         }
254     };
255     return [200, ["Content-type", "application/json"], [JSON->new->encode({})]], $after;
256 }
257
258 sub request_cgi {
259     my ($p, $after) = request(@_);
260     shift @$p;
261     printu join "\n", map { join ': ', @$_ } shift @$p;
262     printu "\n\n";
263     printu join '', map { join '', @$_ } @$p;
264     if (fork) {
265         unless ($config{debug}) {
266             close STDOUT;
267             close STDERR;
268         }
269     } else {
270         $after->() if ref $after ~~ 'CODE';
271     }
272 }
273 request_cgi() unless caller;