]> icculus.org git repositories - divverent/nexuiz.git/blob - Docs/server/rcon.pl
4f4b284349ea8092fbd323e28234f9519793860e
[divverent/nexuiz.git] / Docs / server / rcon.pl
1 #!/usr/bin/perl
2
3 # Copyright (c) 2008 Rudolf "divVerent" Polzer
4
5 # Permission is hereby granted, free of charge, to any person
6 # obtaining a copy of this software and associated documentation
7 # files (the "Software"), to deal in the Software without
8 # restriction, including without limitation the rights to use,
9 # copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the
11 # Software is furnished to do so, subject to the following
12 # conditions:
13
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
16
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19 # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 # OTHER DEALINGS IN THE SOFTWARE.
25
26 # parts copied from rcon2irc
27 # MISC STRING UTILITY ROUTINES to convert between DarkPlaces and IRC conventions
28
29 # convert mIRC color codes to DP color codes
30 our @color_irc2dp_table = (7, 0, 4, 2, 1, 1, 6, 1, 3, 2, 5, 5, 4, 6, 7, 7);
31 our @color_dp2irc_table = (-1, 4, 9, 8, 12, 11, 13, -1, -1, -1); # not accurate, but legible
32 our @color_dp2ansi_table = ("m", "1;31m", "1;32m", "1;33m", "1;34m", "1;36m", "1;35m", "m", "1m", "1m"); # not accurate, but legible
33 our %color_team2dp_table = (5 => 1, 14 => 4, 13 => 3, 10 => 6);
34 our %color_team2irc_table = (5 => 4, 14 => 12, 13 => 8, 10 => 13);
35 sub color_irc2dp($)
36 {
37         my ($message) = @_;
38         $message =~ s/\^/^^/g;
39         my $color = 7;
40         $message =~ s{\003(\d\d?)(?:,(\d?\d?))?|(\017)}{
41                 # $1 is FG, $2 is BG, but let's ignore BG
42                 my $oldcolor = $color;
43                 if($3)
44                 {
45                         $color = 7;
46                 }
47                 else
48                 {
49                         $color = $color_irc2dp_table[$1];
50                         $color = $oldcolor if not defined $color;
51                 }
52                 ($color == $oldcolor) ? '' : '^' . $color;
53         }esg;
54         $message =~ s{[\000-\037]}{}gs; # kill bold etc. for now
55         return $message;
56 }
57
58 our @text_qfont_table = ( # ripped from DP console.c qfont_table
59     "\0", '#',  '#',  '#',  '#',  '.',  '#',  '#',
60     '#',  9,    10,   '#',  ' ',  13,   '.',  '.',
61     '[',  ']',  '0',  '1',  '2',  '3',  '4',  '5',
62     '6',  '7',  '8',  '9',  '.',  '<',  '=',  '>',
63     ' ',  '!',  '"',  '#',  '$',  '%',  '&',  '\'',
64     '(',  ')',  '*',  '+',  ',',  '-',  '.',  '/',
65     '0',  '1',  '2',  '3',  '4',  '5',  '6',  '7',
66     '8',  '9',  ':',  ';',  '<',  '=',  '>',  '?',
67     '@',  'A',  'B',  'C',  'D',  'E',  'F',  'G',
68     'H',  'I',  'J',  'K',  'L',  'M',  'N',  'O',
69     'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',
70     'X',  'Y',  'Z',  '[',  '\\', ']',  '^',  '_',
71     '`',  'a',  'b',  'c',  'd',  'e',  'f',  'g',
72     'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o',
73     'p',  'q',  'r',  's',  't',  'u',  'v',  'w',
74     'x',  'y',  'z',  '{',  '|',  '}',  '~',  '<',
75     '<',  '=',  '>',  '#',  '#',  '.',  '#',  '#',
76     '#',  '#',  ' ',  '#',  ' ',  '>',  '.',  '.',
77     '[',  ']',  '0',  '1',  '2',  '3',  '4',  '5',
78     '6',  '7',  '8',  '9',  '.',  '<',  '=',  '>',
79     ' ',  '!',  '"',  '#',  '$',  '%',  '&',  '\'',
80     '(',  ')',  '*',  '+',  ',',  '-',  '.',  '/',
81     '0',  '1',  '2',  '3',  '4',  '5',  '6',  '7',
82     '8',  '9',  ':',  ';',  '<',  '=',  '>',  '?',
83     '@',  'A',  'B',  'C',  'D',  'E',  'F',  'G',
84     'H',  'I',  'J',  'K',  'L',  'M',  'N',  'O',
85     'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',
86     'X',  'Y',  'Z',  '[',  '\\', ']',  '^',  '_',
87     '`',  'a',  'b',  'c',  'd',  'e',  'f',  'g',
88     'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o',
89     'p',  'q',  'r',  's',  't',  'u',  'v',  'w',
90     'x',  'y',  'z',  '{',  '|',  '}',  '~',  '<'
91 );
92 sub text_dp2ascii($)
93 {
94         my ($message) = @_;
95         $message = join '', map { $text_qfont_table[ord $_] } split //, $message;
96 }
97
98 sub color_dp_transform(&$)
99 {
100         my ($block, $message) = @_;
101
102         $message =~ s{(?:(\^\^)|\^x([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])|\^([0-9])|(.))(?=([0-9,]?))}{
103                 defined $1 ? $block->(char => '^', $7) :
104                 defined $2 ? $block->(rgb => [hex $2, hex $3, hex $4], $7) :
105                 defined $5 ? $block->(color => $5, $7) :
106                 defined $6 ? $block->(char => $6, $7) :
107                         die "Invalid match";
108         }esg;
109
110         return $message;
111 }
112
113 sub color_dp2none($)
114 {
115         my ($message) = @_;
116
117         return color_dp_transform
118         {
119                 my ($type, $data, $next) = @_;
120                 print "$type $data\n";
121                 $type eq 'char'
122                         ? $text_qfont_table[ord $data]
123                         : "";
124         }
125         $message;
126 }
127
128 sub color_rgb2basic($)
129 {
130         my ($data) = @_;
131         my ($r, $g, $b) = @$data;
132         my $min = [sort ($r, $g, $b)]->[0];
133         my $max = [sort ($r, $g, $b)]->[-1];
134
135         my $v = $max / 15;
136         my $s = ($max == $min) ? 0 : 1 - $min/$max;
137
138         if($s < 0.2)
139         {
140                 return 0 if $v < 0.5;
141                 return 7;
142         }
143
144         my $h;
145         if($max == $min)
146         {
147                 $h = 0;
148         }
149         elsif($max == $r)
150         {
151                 $h = (60 * ($g - $b) / ($max - $min)) % 360;
152         }
153         elsif($max == $g)
154         {
155                 $h = (60 * ($b - $r) / ($max - $min)) + 120;
156         }
157         elsif($max == $b)
158         {
159                 $h = (60 * ($r - $g) / ($max - $min)) + 240;
160         }
161
162         return 1 if $h < 36;
163         return 3 if $h < 80;
164         return 2 if $h < 150;
165         return 5 if $h < 200;
166         return 4 if $h < 270;
167         return 6 if $h < 330;
168         return 1;
169 }
170
171 sub color_dp_rgb2basic($)
172 {
173         my ($message) = @_;
174         return color_dp_transform
175         {
176                 my ($type, $data, $next) = @_;
177                 print "$type $data\n";
178                 $type eq 'char'  ? ($data eq '^' ? '^^' : $data) :
179                 $type eq 'color' ? "^$data" :
180                 $type eq 'rgb'   ? "^" . color_rgb2basic $data :
181                         die "Invalid type";
182         }
183         $message;
184 }
185
186 sub color_dp2irc($)
187 {
188         my ($message) = @_;
189         my $color = -1;
190         return color_dp_transform
191         {
192                 my ($type, $data, $next) = @_;
193
194                 if($type eq 'rgb')
195                 {
196                         $type = 'color';
197                         $data = color_rgb2basic $data;
198                 }
199
200                 $type eq 'char'  ? $text_qfont_table[ord $data] :
201                 $type eq 'color' ? do {
202                         my $oldcolor = $color;
203                         $color = $color_dp2irc_table[$data];
204
205                         $color == $oldcolor ? '' :
206                         $color < 0          ? "\017" :
207                         $next eq ','        ? "\003$color\002\002" :
208                                               sprintf "\003%02d", $color;
209                 } :
210                         die "Invalid type";
211         }
212         $message;
213 }
214
215 sub color_dp2ansi($)
216 {
217         my ($message) = @_;
218         my $color = -1;
219         return color_dp_transform
220         {
221                 my ($type, $data, $next) = @_;
222
223                 if($type eq 'rgb')
224                 {
225                         $type = 'color';
226                         $data = color_rgb2basic $data;
227                 }
228
229                 $type eq 'char'  ? $text_qfont_table[ord $data] :
230                 $type eq 'color' ? do {
231                         my $oldcolor = $color;
232                         $color = $color_dp2ansi_table[$data];
233
234                         $color eq $oldcolor ? '' :
235                                               "\033[${color}"
236                 } :
237                         die "Invalid type";
238         }
239         $message;
240 }
241
242 sub color_dpfix($)
243 {
244         my ($message) = @_;
245         # if the message ends with an odd number of ^, kill one
246         chop $message if $message =~ /(?:^|[^\^])\^(\^\^)*$/;
247         return $message;
248 }
249
250
251
252
253 # Interfaces:
254 #   Connection:
255 #     $conn->sockname() returns a connection type specific representation
256 #       string of the local address, or undef if not applicable.
257 #     $conn->send("string") sends something over the connection.
258 #     $conn->recv() receives a string from the connection, or returns "" if no
259 #       data is available.
260 #     $conn->fds() returns all file descriptors used by the connection, so one
261 #       can use select() on them.
262 #   Channel:
263 #     Usually wraps around a connection and implements a command based
264 #     structure over it. It usually is constructed using new
265 #     ChannelType($connection, someparameters...)
266 #     @cmds = $chan->join_commands(@cmds) joins multiple commands to a single
267 #       command string if the protocol supports it, or does nothing and leaves
268 #       @cmds unchanged if the protocol does not support that usage (this is
269 #       meant to save send() invocations).
270 #     $chan->send($command, $nothrottle) sends a command over the channel. If
271 #       $nothrottle is sent, the command must not be left out even if the channel
272 #       is saturated (for example, because of IRC's flood control mechanism).
273 #     $chan->quote($str) returns a string in a quoted form so it can safely be
274 #       inserted as a substring into a command, or returns $str as is if not
275 #       applicable. It is assumed that the result of the quote method is used
276 #       as part of a quoted string, if the protocol supports that.
277 #     $chan->recv() returns a list of received commands from the channel, or
278 #       the empty list if none are available.
279 #     $conn->fds() returns all file descriptors used by the channel's
280 #       connections, so one can use select() on them.
281
282
283
284
285
286
287
288 # Socket connection.
289 # Represents a connection over a socket.
290 # Mainly used to wrap a channel around it for, in this case, line based or rcon-like operation.
291 package Connection::Socket;
292 use strict;
293 use warnings;
294 use IO::Socket::INET;
295 use IO::Handle;
296
297 # Constructor:
298 #   my $conn = new Connection::Socket(tcp => "localaddress" => "remoteaddress" => 6667);
299 # If the remote address does not contain a port number, the numeric port is
300 # used (it serves as a default port).
301 sub new($$)
302 {
303         my ($class, $proto, $local, $remote, $defaultport) = @_;
304         my $sock = IO::Socket::INET->new(
305                 Proto => $proto,
306                 (length($local) ? (LocalAddr => $local) : ()),
307                 PeerAddr => $remote,
308                 PeerPort => $defaultport
309         ) or die "socket $proto/$local/$remote: $!";
310         $sock->blocking(0);
311         my $you = {
312                 # Mortal fool! Release me from this wretched tomb! I must be set free
313                 # or I will haunt you forever! I will hide your keys beneath the
314                 # cushions of your upholstered furniture... and NEVERMORE will you be
315                 # able to find socks that match!
316                 sock => $sock,
317                 # My demonic powers have made me OMNIPOTENT! Bwahahahahahahaha!
318         };
319         return
320                 bless $you, 'Connection::Socket';
321 }
322
323 # $sock->sockname() returns the local address of the socket.
324 sub sockname($)
325 {
326         my ($self) = @_;
327         my ($port, $addr) = sockaddr_in $self->{sock}->sockname();
328         return "@{[inet_ntoa $addr]}:$port";
329 }
330
331 # $sock->send($data) sends some data over the socket; on success, 1 is returned.
332 sub send($$)
333 {
334         my ($self, $data) = @_;
335         return 1
336                 if not length $data;
337         if(not eval { $self->{sock}->send($data); })
338         {
339                 warn "$@";
340                 return 0;
341         }
342         return 1;
343 }
344
345 # $sock->recv() receives as much as possible from the socket (or at most 32k). Returns "" if no data is available.
346 sub recv($)
347 {
348         my ($self) = @_;
349         my $data = "";
350         if(defined $self->{sock}->recv($data, 32768, 0))
351         {
352                 return $data;
353         }
354         elsif($!{EAGAIN})
355         {
356                 return "";
357         }
358         else
359         {
360                 return undef;
361         }
362 }
363
364 # $sock->fds() returns the socket file descriptor.
365 sub fds($)
366 {
367         my ($self) = @_;
368         return fileno $self->{sock};
369 }
370
371
372
373
374
375
376
377 # QW rcon protocol channel.
378 # Wraps around a UDP based Connection and sends commands as rcon commands as
379 # well as receives rcon replies. The quote and join_commands methods are using
380 # DarkPlaces engine specific rcon protocol extensions.
381 package Channel::QW;
382 use strict;
383 use warnings;
384
385 # Constructor:
386 #   my $chan = new Channel::QW($connection, "password");
387 sub new($$)
388 {
389         my ($class, $conn, $password) = @_;
390         my $you = {
391                 connector => $conn,
392                 password => $password,
393                 recvbuf => "",
394         };
395         return
396                 bless $you, 'Channel::QW';
397 }
398
399 # Note: multiple commands in one rcon packet is a DarkPlaces extension.
400 sub join_commands($@)
401 {
402         my ($self, @data) = @_;
403         return join "\0", @data;
404 }
405
406 sub send($$$)
407 {
408         my ($self, $line, $nothrottle) = @_;
409         return $self->{connector}->send("\377\377\377\377rcon $self->{password} $line");
410 }
411
412 # Note: backslash and quotation mark escaping is a DarkPlaces extension.
413 sub quote($$)
414 {
415         my ($self, $data) = @_;
416         $data =~ s/[\000-\037]//g;
417         $data =~ s/([\\"])/\\$1/g;
418         $data =~ s/\$/\$\$/g;
419         return $data;
420 }
421
422 sub recv($)
423 {
424         my ($self) = @_;
425         for(;;)
426         {
427                 my $s = $self->{connector}->recv();
428                 die "read error\n"
429                         if not defined $s;
430                 length $s
431                         or last;
432                 next
433                         if $s !~ /^\377\377\377\377n(.*)$/s;
434                 $self->{recvbuf} .= $1;
435         }
436         my @out = ();
437         while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
438         {
439                 push @out, $1;
440         }
441         return @out;
442 }
443
444 sub fds($)
445 {
446         my ($self) = @_;
447         return $self->{connector}->fds();
448 }
449
450
451
452
453
454
455
456 package main;
457 use strict;
458 use warnings;
459 use IO::Select;
460 use Time::HiRes;
461
462 sub default($$)
463 {
464         my ($default, $value) = @_;
465         return $value if defined $value;
466         return $default;
467 }
468
469 my $server   = default '',    $ENV{rcon_address};
470 my $password = default '',    $ENV{rcon_password};
471 my $timeout  = default '5',   $ENV{rcon_timeout};
472 my $timeouti = default '0.2', $ENV{rcon_timeout_inter};
473 my $colors   = default '0',   $ENV{rcon_colorcodes_raw};
474
475 if(!length $server)
476 {
477         print STDERR "Usage: rcon_address=SERVERIP:PORT rcon_password=PASSWORD $0 rconcommands...\n";
478         print STDERR "Optional: rcon_timeout=... (default: 5)\n";
479         print STDERR "          rcon_timeout_inter=... (default: 0.2)\n";
480         print STDERR "          rcon_colorcodes_raw=1 (to disable color codes translation)\n";
481         exit 0;
482 }
483
484 my $connection = Connection::Socket->new("udp", "", $server, 26000);
485 my $rcon = Channel::QW->new($connection, $password);
486
487 if(!$rcon->send($rcon->join_commands(@ARGV)))
488 {
489         die "send: $!";
490 }
491
492 if($timeout > 0)
493 {
494         my $sel = IO::Select->new($rcon->fds());
495         my $endtime_max = Time::HiRes::time() + $timeout;
496         my $endtime = $endtime_max;
497
498         while((my $dt = $endtime - Time::HiRes::time()) > 0)
499         {
500                 if($sel->can_read($dt))
501                 {
502                         for($rcon->recv())
503                         {
504                                 $_ = (color_dp2ansi $_) . "\033[m" unless $colors;
505                                 print "$_\n"
506                         }
507                         $endtime = Time::HiRes::time() + $timeouti;
508                         $endtime = $endtime_max
509                                 if $endtime > $endtime_max;
510                 }
511         }
512 }
513 exit 0;