3 # Copyright (c) 2008 Rudolf "divVerent" Polzer
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
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
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.
26 # parts copied from rcon2irc
27 # MISC STRING UTILITY ROUTINES to convert between DarkPlaces and IRC conventions
29 # convert mIRC color codes to DP color codes
30 our $color_utf8_enable = 1;
31 our @color_irc2dp_table = (7, 0, 4, 2, 1, 1, 6, 1, 3, 2, 5, 5, 4, 6, 7, 7);
32 our @color_dp2irc_table = (-1, 4, 9, 8, 12, 11, 13, -1, -1, -1); # not accurate, but legible
33 our @color_dp2ansi_table = ("m", "1;31m", "1;32m", "1;33m", "1;34m", "1;36m", "1;35m", "m", "1m", "1m"); # not accurate, but legible
34 our %color_team2dp_table = (5 => 1, 14 => 4, 13 => 3, 10 => 6);
35 our %color_team2irc_table = (5 => 4, 14 => 12, 13 => 8, 10 => 13);
39 $message =~ s/\^/^^/g;
41 $message =~ s{\003(\d\d?)(?:,(\d?\d?))?|(\017)}{
42 # $1 is FG, $2 is BG, but let's ignore BG
43 my $oldcolor = $color;
50 $color = $color_irc2dp_table[$1];
51 $color = $oldcolor if not defined $color;
53 ($color == $oldcolor) ? '' : '^' . $color;
55 $message =~ s{[\000-\037]}{}gs; # kill bold etc. for now
59 our @text_qfont_table = ( # ripped from DP console.c qfont_table
60 '', '#', '#', '#', '#', '.', '#', '#',
61 '#', 9, 10, '#', ' ', 13, '.', '.',
62 '[', ']', '0', '1', '2', '3', '4', '5',
63 '6', '7', '8', '9', '.', '<', '=', '>',
64 ' ', '!', '"', '#', '$', '%', '&', '\'',
65 '(', ')', '*', '+', ',', '-', '.', '/',
66 '0', '1', '2', '3', '4', '5', '6', '7',
67 '8', '9', ':', ';', '<', '=', '>', '?',
68 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
69 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
70 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
71 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
72 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
73 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
74 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
75 'x', 'y', 'z', '{', '|', '}', '~', '<',
76 '<', '=', '>', '#', '#', '.', '#', '#',
77 '#', '#', ' ', '#', ' ', '>', '.', '.',
78 '[', ']', '0', '1', '2', '3', '4', '5',
79 '6', '7', '8', '9', '.', '<', '=', '>',
80 ' ', '!', '"', '#', '$', '%', '&', '\'',
81 '(', ')', '*', '+', ',', '-', '.', '/',
82 '0', '1', '2', '3', '4', '5', '6', '7',
83 '8', '9', ':', ';', '<', '=', '>', '?',
84 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
85 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
86 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
87 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
88 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
89 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
90 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
91 'x', 'y', 'z', '{', '|', '}', '~', '<'
93 sub text_qfont_table($)
97 if($color_utf8_enable)
99 return (($o & 0xFF00) == 0xE000) ? $text_qfont_table[$o & 0xFF] : $char;
103 return $text_qfont_table[$o];
109 $message = join '', map { text_qfont_table $_ } split //, $message;
112 sub color_dp_transform(&$)
114 my ($block, $message) = @_;
115 $message =~ s{(?:(\^\^)|\^x([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])|\^([0-9])|(.))(?=([0-9,]?))}{
116 defined $1 ? $block->(char => '^', $7) :
117 defined $2 ? $block->(rgb => [hex $2, hex $3, hex $4], $7) :
118 defined $5 ? $block->(color => $5, $7) :
119 defined $6 ? $block->(char => $6, $7) :
130 return color_dp_transform
132 my ($type, $data, $next) = @_;
134 ? text_qfont_table $data
140 sub color_rgb2basic($)
143 my ($R, $G, $B) = @$data;
144 my $min = [sort { $a <=> $b } ($R, $G, $B)]->[0];
145 my $max = [sort { $a <=> $b } ($R, $G, $B)]->[-1];
148 my $s = ($max == $min) ? 0 : 1 - $min/$max;
152 return 0 if $v < 0.5;
163 $h = (60 * ($G - $B) / ($max - $min)) % 360;
167 $h = (60 * ($B - $R) / ($max - $min)) + 120;
171 $h = (60 * ($R - $G) / ($max - $min)) + 240;
176 return 2 if $h < 150;
177 return 5 if $h < 200;
178 return 4 if $h < 270;
179 return 6 if $h < 330;
183 sub color_dp_rgb2basic($)
186 return color_dp_transform
188 my ($type, $data, $next) = @_;
189 $type eq 'char' ? ($data eq '^' ? '^^' : $data) :
190 $type eq 'color' ? "^$data" :
191 $type eq 'rgb' ? "^" . color_rgb2basic $data :
201 return color_dp_transform
203 my ($type, $data, $next) = @_;
208 $data = color_rgb2basic $data;
211 $type eq 'char' ? text_qfont_table $data :
212 $type eq 'color' ? do {
213 my $oldcolor = $color;
214 $color = $color_dp2irc_table[$data];
216 $color == $oldcolor ? '' :
217 $color < 0 ? "\017" :
218 (index '0123456789,', $next) >= 0 ? "\003$color\002\002" :
230 return color_dp_transform
232 my ($type, $data, $next) = @_;
237 $data = color_rgb2basic $data;
240 $type eq 'char' ? text_qfont_table $data :
241 $type eq 'color' ? do {
242 my $oldcolor = $color;
243 $color = $color_dp2ansi_table[$data];
245 $color eq $oldcolor ? '' :
256 # if the message ends with an odd number of ^, kill one
257 chop $message if $message =~ /(?:^|[^\^])\^(\^\^)*$/;
266 # $conn->sockname() returns a connection type specific representation
267 # string of the local address, or undef if not applicable.
268 # $conn->send("string") sends something over the connection.
269 # $conn->recv() receives a string from the connection, or returns "" if no
271 # $conn->fds() returns all file descriptors used by the connection, so one
272 # can use select() on them.
274 # Usually wraps around a connection and implements a command based
275 # structure over it. It usually is constructed using new
276 # ChannelType($connection, someparameters...)
277 # @cmds = $chan->join_commands(@cmds) joins multiple commands to a single
278 # command string if the protocol supports it, or does nothing and leaves
279 # @cmds unchanged if the protocol does not support that usage (this is
280 # meant to save send() invocations).
281 # $chan->send($command, $nothrottle) sends a command over the channel. If
282 # $nothrottle is sent, the command must not be left out even if the channel
283 # is saturated (for example, because of IRC's flood control mechanism).
284 # $chan->quote($str) returns a string in a quoted form so it can safely be
285 # inserted as a substring into a command, or returns $str as is if not
286 # applicable. It is assumed that the result of the quote method is used
287 # as part of a quoted string, if the protocol supports that.
288 # $chan->recv() returns a list of received commands from the channel, or
289 # the empty list if none are available.
290 # $conn->fds() returns all file descriptors used by the channel's
291 # connections, so one can use select() on them.
300 # Represents a connection over a socket.
301 # Mainly used to wrap a channel around it for, in this case, line based or rcon-like operation.
302 package Connection::Socket;
305 use IO::Socket::INET;
309 # my $conn = new Connection::Socket(tcp => "localaddress" => "remoteaddress" => 6667);
310 # If the remote address does not contain a port number, the numeric port is
311 # used (it serves as a default port).
314 my ($class, $proto, $local, $remote, $defaultport) = @_;
315 my $sock = IO::Socket::INET->new(
317 (length($local) ? (LocalAddr => $local) : ()),
319 PeerPort => $defaultport
320 ) or die "socket $proto/$local/$remote/$defaultport: $!";
324 # Mortal fool! Release me from this wretched tomb! I must be set free
325 # or I will haunt you forever! I will hide your keys beneath the
326 # cushions of your upholstered furniture... and NEVERMORE will you be
327 # able to find socks that match!
329 # My demonic powers have made me OMNIPOTENT! Bwahahahahahahaha!
332 bless $you, 'Connection::Socket';
335 # $sock->sockname() returns the local address of the socket.
339 my ($port, $addr) = sockaddr_in $self->{sock}->sockname();
340 return "@{[inet_ntoa $addr]}:$port";
343 # $sock->send($data) sends some data over the socket; on success, 1 is returned.
346 my ($self, $data) = @_;
349 if(not eval { $self->{sock}->send($data); })
357 # $sock->recv() receives as much as possible from the socket (or at most 32k). Returns "" if no data is available.
362 if(defined $self->{sock}->recv($data, 32768, 0))
376 # $sock->fds() returns the socket file descriptor.
380 return fileno $self->{sock};
389 # QW rcon protocol channel.
390 # Wraps around a UDP based Connection and sends commands as rcon commands as
391 # well as receives rcon replies. The quote and join_commands methods are using
392 # DarkPlaces engine specific rcon protocol extensions.
400 # my $chan = new Channel::QW($connection, "password");
403 my ($class, $conn, $password, $secure, $timeout) = @_;
406 password => $password,
412 bless $you, 'Channel::QW';
415 # Note: multiple commands in one rcon packet is a DarkPlaces extension.
416 sub join_commands($@)
418 my ($self, @data) = @_;
419 return join "\0", @data;
424 my ($self, $line, $nothrottle) = @_;
426 if $color_utf8_enable;
427 if($self->{secure} > 1)
429 $self->{connector}->send("\377\377\377\377getchallenge");
430 my $c = $self->recvchallenge();
431 return 0 if not defined $c;
432 my $key = Digest::HMAC::hmac("$c $line", $self->{password}, \&Digest::MD4::md4);
433 return $self->{connector}->send("\377\377\377\377srcon HMAC-MD4 CHALLENGE $key $c $line");
435 elsif($self->{secure})
437 my $t = sprintf "%ld.%06d", time(), int rand 1000000;
438 my $key = Digest::HMAC::hmac("$t $line", $self->{password}, \&Digest::MD4::md4);
439 return $self->{connector}->send("\377\377\377\377srcon HMAC-MD4 TIME $key $t $line");
443 return $self->{connector}->send("\377\377\377\377rcon $self->{password} $line");
447 # Note: backslash and quotation mark escaping is a DarkPlaces extension.
450 my ($self, $data) = @_;
451 $data =~ s/[\000-\037]//g;
452 $data =~ s/([\\"])/\\$1/g;
453 $data =~ s/\$/\$\$/g;
461 my $sel = IO::Select->new($self->fds());
462 my $endtime_max = Time::HiRes::time() + $self->{timeout};
463 my $endtime = $endtime_max;
465 while((my $dt = $endtime - Time::HiRes::time()) > 0)
467 if($sel->can_read($dt))
471 my $s = $self->{connector}->recv();
476 if($s =~ /^\377\377\377\377challenge (.*?)(?:$|\0)/s)
481 if $s !~ /^\377\377\377\377n(.*)$/s;
482 $self->{recvbuf} .= $1;
494 my $s = $self->{connector}->recv();
500 if $s !~ /^\377\377\377\377n(.*)$/s;
501 $self->{recvbuf} .= $1;
504 while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
508 if $color_utf8_enable;
517 return $self->{connector}->fds();
534 my ($default, $value) = @_;
535 return $value if defined $value;
539 my $server = default '', $ENV{rcon_address};
540 my $password = default '', $ENV{rcon_password};
541 my $secure = default '1', $ENV{rcon_secure};
542 my $timeout = default '5', $ENV{rcon_timeout};
543 my $timeouti = default '0.2', $ENV{rcon_timeout_inter};
544 my $timeoutc = default $timeout, $ENV{rcon_timeout_challenge};
545 my $colors = default '0', $ENV{rcon_colorcodes_raw};
546 my $utf8 = default '1', $ENV{rcon_utf8_enable};
550 print STDERR "Usage: rcon_address=SERVERIP:PORT rcon_password=PASSWORD $0 rconcommands...\n";
551 print STDERR "Optional: rcon_timeout=... (default: 5)\n";
552 print STDERR " rcon_timeout_inter=... (default: 0.2)\n";
553 print STDERR " rcon_timeout_challenge=... (default: 5)\n";
554 print STDERR " rcon_colorcodes_raw=1 (to disable color codes translation)\n";
555 print STDERR " rcon_secure=0 (to allow connecting to older servers not supporting secure rcon)\n";
556 print STDERR " rcon_utf8_enable=0 (to enable/disable engine UTF8 mode)\n";
560 $color_utf8_enable = $utf8;
562 if($color_utf8_enable)
564 binmode STDOUT, ':utf8';
565 binmode STDERR, ':utf8';
568 my $connection = Connection::Socket->new("udp", "", $server, 26000);
569 my $rcon = Channel::QW->new($connection, $password, $secure, $timeoutc);
571 if(!$rcon->send($rcon->join_commands(@ARGV)))
578 my $sel = IO::Select->new($rcon->fds());
579 my $endtime_max = Time::HiRes::time() + $timeout;
580 my $endtime = $endtime_max;
582 while((my $dt = $endtime - Time::HiRes::time()) > 0)
584 if($sel->can_read($dt))
588 $_ = (color_dp2ansi $_) . "\033[m" unless $colors;
591 $endtime = Time::HiRes::time() + $timeouti;
592 $endtime = $endtime_max
593 if $endtime > $endtime_max;