]> icculus.org git repositories - divverent/nexuiz.git/blob - Docs/server/rcon.pl
add rcon client Perl script; slight bugfix to rcon2irc (namely, handling of the ...
[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
27 # parts copied from rcon2irc
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 = (14, 4, 9, 8, 12, 11, 13, 14, 15, 15); # 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_dp2none($)
99 {
100         my ($message) = @_;
101         my $color = -1;
102         $message =~ s{\^(.)(?=([0-9,]?))}{
103                 my $c = $1;
104                 $c eq '^' ? '^' :
105                 $c =~ /^[0-9]$/ ? '' : "^$c";
106         }esg;
107         return text_dp2ascii $message;
108 }
109
110 sub color_dp2irc($)
111 {
112         my ($message) = @_;
113         my $color = -1;
114         $message =~ s{\^(.)(?=([0-9,]?))}{
115                 my $c = $1;
116                 my $f = $2;
117                 $c eq '^' ? '^' :
118                 $c =~ /^[0-9]$/ ? do {
119                         my $oldcolor = $color;
120                         $c = 0 if $c >= 7; # map 0, 7, 8, 9 to default (no bright white or such stuff)
121                         $color = $color_dp2irc_table[$c];
122                         ($color == $oldcolor) ? '' :
123                         $c == 0 ? "\017" :
124                         $f eq ',' ? "\003$color\002\002" :
125                         $f ne ''  ? sprintf "\003%02d", $color : "\003$color";
126                 } : "^$c";
127         }esg;
128         return text_dp2ascii $message;
129 }
130
131 sub color_dp2ansi($)
132 {
133         my ($message) = @_;
134         my $color = -1;
135         $message =~ s{\^(.)}{
136                 my $c = $1;
137                 $c eq '^' ? '^' :
138                 $c =~ /^[0-9]$/ ? do {
139                         my $oldcolor = $color;
140                         $color = $color_dp2ansi_table[$c];
141                         ($color == $oldcolor) ? '' :
142                         "\000[${color}" # "
143                 } : "^$c";
144         }esg;
145         $message = text_dp2ascii $message;
146         $message =~ s/\000/\033/g;
147         return $message;
148 }
149
150 sub color_dpfix($)
151 {
152         my ($message) = @_;
153         # if the message ends with an odd number of ^, kill one
154         chop $message if $message =~ /(?:^|[^\^])\^(\^\^)*$/;
155         return $message;
156 }
157
158
159
160 # Interfaces:
161 #   Connection:
162 #     $conn->sockname() returns a connection type specific representation
163 #       string of the local address, or undef if not applicable.
164 #     $conn->send("string") sends something over the connection.
165 #     $conn->recv() receives a string from the connection, or returns "" if no
166 #       data is available.
167 #     $conn->fds() returns all file descriptors used by the connection, so one
168 #       can use select() on them.
169 #   Channel:
170 #     Usually wraps around a connection and implements a command based
171 #     structure over it. It usually is constructed using new
172 #     ChannelType($connection, someparameters...)
173 #     @cmds = $chan->join_commands(@cmds) joins multiple commands to a single
174 #       command string if the protocol supports it, or does nothing and leaves
175 #       @cmds unchanged if the protocol does not support that usage (this is
176 #       meant to save send() invocations).
177 #     $chan->send($command, $nothrottle) sends a command over the channel. If
178 #       $nothrottle is sent, the command must not be left out even if the channel
179 #       is saturated (for example, because of IRC's flood control mechanism).
180 #     $chan->quote($str) returns a string in a quoted form so it can safely be
181 #       inserted as a substring into a command, or returns $str as is if not
182 #       applicable. It is assumed that the result of the quote method is used
183 #       as part of a quoted string, if the protocol supports that.
184 #     $chan->recv() returns a list of received commands from the channel, or
185 #       the empty list if none are available.
186 #     $conn->fds() returns all file descriptors used by the channel's
187 #       connections, so one can use select() on them.
188
189
190
191
192
193
194
195 # Socket connection.
196 # Represents a connection over a socket.
197 # Mainly used to wrap a channel around it for, in this case, line based or rcon-like operation.
198 package Connection::Socket;
199 use strict;
200 use warnings;
201 use IO::Socket::INET;
202 use IO::Handle;
203
204 # Constructor:
205 #   my $conn = new Connection::Socket(tcp => "localaddress" => "remoteaddress" => 6667);
206 # If the remote address does not contain a port number, the numeric port is
207 # used (it serves as a default port).
208 sub new($$)
209 {
210         my ($class, $proto, $local, $remote, $defaultport) = @_;
211         my $sock = IO::Socket::INET->new(
212                 Proto => $proto,
213                 (length($local) ? (LocalAddr => $local) : ()),
214                 PeerAddr => $remote,
215                 PeerPort => $defaultport
216         ) or die "socket $proto/$local/$remote: $!";
217         $sock->blocking(0);
218         my $you = {
219                 # Mortal fool! Release me from this wretched tomb! I must be set free
220                 # or I will haunt you forever! I will hide your keys beneath the
221                 # cushions of your upholstered furniture... and NEVERMORE will you be
222                 # able to find socks that match!
223                 sock => $sock,
224                 # My demonic powers have made me OMNIPOTENT! Bwahahahahahahaha!
225         };
226         return
227                 bless $you, 'Connection::Socket';
228 }
229
230 # $sock->sockname() returns the local address of the socket.
231 sub sockname($)
232 {
233         my ($self) = @_;
234         my ($port, $addr) = sockaddr_in $self->{sock}->sockname();
235         return "@{[inet_ntoa $addr]}:$port";
236 }
237
238 # $sock->send($data) sends some data over the socket; on success, 1 is returned.
239 sub send($$)
240 {
241         my ($self, $data) = @_;
242         return 1
243                 if not length $data;
244         if(not eval { $self->{sock}->send($data); })
245         {
246                 warn "$@";
247                 return 0;
248         }
249         return 1;
250 }
251
252 # $sock->recv() receives as much as possible from the socket (or at most 32k). Returns "" if no data is available.
253 sub recv($)
254 {
255         my ($self) = @_;
256         my $data = "";
257         $self->{sock}->recv($data, 32768, 0);
258         return $data;
259 }
260
261 # $sock->fds() returns the socket file descriptor.
262 sub fds($)
263 {
264         my ($self) = @_;
265         return fileno $self->{sock};
266 }
267
268
269
270
271
272
273
274 # QW rcon protocol channel.
275 # Wraps around a UDP based Connection and sends commands as rcon commands as
276 # well as receives rcon replies. The quote and join_commands methods are using
277 # DarkPlaces engine specific rcon protocol extensions.
278 package Channel::QW;
279 use strict;
280 use warnings;
281
282 # Constructor:
283 #   my $chan = new Channel::QW($connection, "password");
284 sub new($$)
285 {
286         my ($class, $conn, $password) = @_;
287         my $you = {
288                 connector => $conn,
289                 password => $password,
290                 recvbuf => "",
291         };
292         return
293                 bless $you, 'Channel::QW';
294 }
295
296 # Note: multiple commands in one rcon packet is a DarkPlaces extension.
297 sub join_commands($@)
298 {
299         my ($self, @data) = @_;
300         return join "\0", @data;
301 }
302
303 sub send($$$)
304 {
305         my ($self, $line, $nothrottle) = @_;
306         return $self->{connector}->send("\377\377\377\377rcon $self->{password} $line");
307 }
308
309 # Note: backslash and quotation mark escaping is a DarkPlaces extension.
310 sub quote($$)
311 {
312         my ($self, $data) = @_;
313         $data =~ s/[\000-\037]//g;
314         $data =~ s/([\\"])/\\$1/g;
315         $data =~ s/\$/\$\$/g;
316         return $data;
317 }
318
319 sub recv($)
320 {
321         my ($self) = @_;
322         for(;;)
323         {
324                 length(my $s = $self->{connector}->recv())
325                         or last;
326                 next
327                         if $s !~ /^\377\377\377\377n(.*)$/s;
328                 $self->{recvbuf} .= $1;
329         }
330         my @out = ();
331         while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
332         {
333                 push @out, $1;
334         }
335         return @out;
336 }
337
338 sub fds($)
339 {
340         my ($self) = @_;
341         return $self->{connector}->fds();
342 }
343
344
345
346
347
348
349
350 package main;
351 use strict;
352 use warnings;
353 use IO::Select;
354
355 sub default($$)
356 {
357         my ($default, $value) = @_;
358         return $value if defined $value;
359         return $default;
360 }
361
362 my $server   = default '',  $ENV{rcon_address};
363 my $password = default '',  $ENV{rcon_password};
364 my $timeout  = default '5', $ENV{rcon_timeout};
365 my $colors   = default '0', $ENV{rcon_colorcodes_raw};
366
367 if(!length $server)
368 {
369         print STDERR "Usage: rcon_address=SERVERIP:PORT rcon_password=PASSWORD $0 rconcommands...\n";
370         print STDERR "Optional: rcon_timeout=... (default: 5)\n";
371         print STDERR "          rcon_colorcodes_raw=1 (to disable color codes translation)\n";
372         exit 0;
373 }
374
375 my $connection = Connection::Socket->new("udp", "", $server, 26000);
376 my $rcon = Channel::QW->new($connection, $password);
377
378 if(!$rcon->send($rcon->join_commands(@ARGV)))
379 {
380         die "send: $!";
381 }
382
383 if($timeout)
384 {
385         my $sel = IO::Select->new($rcon->fds());
386         if($sel->can_read($timeout))
387         {
388                 for($rcon->recv())
389                 {
390                         $_ = color_dp2ansi $_;
391                         print "$_\033[m\n"
392                 }
393         }
394 }