3 our $VERSION = '0.4.2 svn $Revision$';
5 # Copyright (c) 2008 Rudolf "divVerent" Polzer
7 # Permission is hereby granted, free of charge, to any person
8 # obtaining a copy of this software and associated documentation
9 # files (the "Software"), to deal in the Software without
10 # restriction, including without limitation the rights to use,
11 # copy, modify, merge, publish, distribute, sublicense, and/or sell
12 # copies of the Software, and to permit persons to whom the
13 # Software is furnished to do so, subject to the following
16 # The above copyright notice and this permission notice shall be
17 # included in all copies or substantial portions of the Software.
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
21 # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
23 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
26 # OTHER DEALINGS IN THE SOFTWARE.
30 # $conn->sockname() returns a connection type specific representation
31 # string of the local address, or undef if not applicable.
32 # $conn->send("string") sends something over the connection.
33 # $conn->recv() receives a string from the connection, or returns "" if no
35 # $conn->fds() returns all file descriptors used by the connection, so one
36 # can use select() on them.
38 # Usually wraps around a connection and implements a command based
39 # structure over it. It usually is constructed using new
40 # ChannelType($connection, someparameters...)
41 # @cmds = $chan->join_commands(@cmds) joins multiple commands to a single
42 # command string if the protocol supports it, or does nothing and leaves
43 # @cmds unchanged if the protocol does not support that usage (this is
44 # meant to save send() invocations).
45 # $chan->send($command, $nothrottle) sends a command over the channel. If
46 # $nothrottle is sent, the command must not be left out even if the channel
47 # is saturated (for example, because of IRC's flood control mechanism).
48 # $chan->quote($str) returns a string in a quoted form so it can safely be
49 # inserted as a substring into a command, or returns $str as is if not
50 # applicable. It is assumed that the result of the quote method is used
51 # as part of a quoted string, if the protocol supports that.
52 # $chan->recv() returns a list of received commands from the channel, or
53 # the empty list if none are available.
54 # $conn->fds() returns all file descriptors used by the channel's
55 # connections, so one can use select() on them.
64 # Represents a connection over a socket.
65 # Mainly used to wrap a channel around it for, in this case, line based or rcon-like operation.
66 package Connection::Socket;
73 # my $conn = new Connection::Socket(tcp => "localaddress" => "remoteaddress" => 6667);
74 # If the remote address does not contain a port number, the numeric port is
75 # used (it serves as a default port).
78 my ($class, $proto, $local, $remote, $defaultport) = @_;
79 my $sock = IO::Socket::INET->new(
81 (length($local) ? (LocalAddr => $local) : ()),
83 PeerPort => $defaultport
84 ) or die "socket $proto/$local/$remote: $!";
87 # Mortal fool! Release me from this wretched tomb! I must be set free
88 # or I will haunt you forever! I will hide your keys beneath the
89 # cushions of your upholstered furniture... and NEVERMORE will you be
90 # able to find socks that match!
92 # My demonic powers have made me OMNIPOTENT! Bwahahahahahahaha!
95 bless $you, 'Connection::Socket';
98 # $sock->sockname() returns the local address of the socket.
102 my ($port, $addr) = sockaddr_in $self->{sock}->sockname();
103 return "@{[inet_ntoa $addr]}:$port";
106 # $sock->send($data) sends some data over the socket; on success, 1 is returned.
109 my ($self, $data) = @_;
112 if(not eval { $self->{sock}->send($data); })
120 # $sock->recv() receives as much as possible from the socket (or at most 32k). Returns "" if no data is available.
125 if(defined $self->{sock}->recv($data, 32768, 0))
139 # $sock->fds() returns the socket file descriptor.
143 return fileno $self->{sock};
152 # Line-based buffered connectionless FIFO channel.
153 # Whatever is sent to it using send() is echoed back when using recv().
154 package Channel::FIFO;
159 # my $chan = new Channel::FIFO();
167 bless $you, 'Channel::FIFO';
170 sub join_commands($@)
172 my ($self, @data) = @_;
178 my ($self, $line, $nothrottle) = @_;
179 push @{$self->{buffer}}, $line;
184 my ($self, $data) = @_;
191 my $r = $self->{buffer};
192 $self->{buffer} = [];
208 # QW rcon protocol channel.
209 # Wraps around a UDP based Connection and sends commands as rcon commands as
210 # well as receives rcon replies. The quote and join_commands methods are using
211 # DarkPlaces engine specific rcon protocol extensions.
217 # my $chan = new Channel::QW($connection, "password");
220 my ($class, $conn, $password) = @_;
223 password => $password,
227 bless $you, 'Channel::QW';
230 # Note: multiple commands in one rcon packet is a DarkPlaces extension.
231 sub join_commands($@)
233 my ($self, @data) = @_;
234 return join "\0", @data;
239 my ($self, $line, $nothrottle) = @_;
240 return $self->{connector}->send("\377\377\377\377rcon $self->{password} $line");
243 # Note: backslash and quotation mark escaping is a DarkPlaces extension.
246 my ($self, $data) = @_;
247 $data =~ s/[\000-\037]//g;
248 $data =~ s/([\\"])/\\$1/g;
249 $data =~ s/\$/\$\$/g;
258 my $s = $self->{connector}->recv();
264 if $s !~ /^\377\377\377\377n(.*)$/s;
265 $self->{recvbuf} .= $1;
268 while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
278 return $self->{connector}->fds();
287 # Line based protocol channel.
288 # Wraps around a TCP based Connection and sends commands as text lines
289 # (separated by CRLF). When reading responses from the Connection, any type of
290 # line ending is accepted.
291 # A flood control mechanism is implemented.
292 package Channel::Line;
295 use Time::HiRes qw/time/;
298 # my $chan = new Channel::Line($connection);
301 my ($class, $conn) = @_;
311 bless $you, 'Channel::Line';
314 sub join_commands($@)
316 my ($self, @data) = @_;
320 # Sets new flood control parameters:
321 # $chan->throttle(maximum lines per second, maximum burst length allowed to
322 # exceed the lines per second limit);
323 # RFC 1459 describes these parameters to be 0.5 and 5 for the IRC protocol.
324 # If the $nothrottle flag is set while sending, the line is sent anyway even
325 # if flooding would take place.
328 my ($self, $linepersec, $maxlines) = @_;
329 $self->{linepersec} = $linepersec;
330 $self->{maxlines} = $maxlines;
331 $self->{capacity} = $maxlines;
336 my ($self, $line, $nothrottle) = @_;
338 if(defined $self->{capacity})
340 $self->{capacity} += ($t - $self->{lastsend}) * $self->{linepersec};
341 $self->{lastsend} = $t;
342 $self->{capacity} = $self->{maxlines}
343 if $self->{capacity} > $self->{maxlines};
347 if $self->{capacity} < 0;
349 $self->{capacity} -= 1;
352 return $self->{connector}->send("$line\r\n");
357 my ($self, $data) = @_;
358 $data =~ s/\r\n?/\n/g;
368 my $s = $self->{connector}->recv();
373 $self->{recvbuf} .= $s;
376 while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
386 return $self->{connector}->fds();
394 # main program... a gateway between IRC and DarkPlaces servers
401 use Time::HiRes qw/time/;
403 our @handlers = (); # list of [channel, expression, sub to handle result]
404 our @tasks = (); # list of [time, sub]
408 playernick_0 => "(console)",
414 irc_channel => undef,
415 irc_ping_delay => 120,
418 irc_nickserv_password => "",
419 irc_nickserv_identify => 'PRIVMSG NickServ :IDENTIFY %2$s',
420 irc_nickserv_ghost => 'PRIVMSG NickServ :GHOST %1$s %2$s',
421 irc_nickserv_ghost_attempts => 3,
423 irc_quakenet_authname => "",
424 irc_quakenet_password => "",
425 irc_quakenet_getchallenge => 'PRIVMSG Q@CServe.quakenet.org :CHALLENGE',
426 irc_quakenet_challengeauth => 'PRIVMSG Q@CServe.quakenet.org :CHALLENGEAUTH',
427 irc_quakenet_challengeprefix => ':Q!TheQBot@CServe.quakenet.org NOTICE [^:]+ :CHALLENGE',
431 dp_password => undef,
432 dp_status_delay => 30,
433 dp_server_from_wan => "",
436 irc_admin_password => "",
437 irc_admin_timeout => 3600,
444 # MISC STRING UTILITY ROUTINES to convert between DarkPlaces and IRC conventions
446 # convert mIRC color codes to DP color codes
447 our @color_irc2dp_table = (7, 0, 4, 2, 1, 1, 6, 1, 3, 2, 5, 5, 4, 6, 7, 7);
448 our @color_dp2irc_table = (14, 4, 9, 8, 12, 11, 13, 14, 15, 15); # not accurate, but legible
449 our @color_dp2ansi_table = ("m", "1;31m", "1;32m", "1;33m", "1;34m", "1;36m", "1;35m", "m", "1m", "1m"); # not accurate, but legible
450 our %color_team2dp_table = (5 => 1, 14 => 4, 13 => 3, 10 => 6);
451 our %color_team2irc_table = (5 => 4, 14 => 12, 13 => 8, 10 => 13);
455 $message =~ s/\^/^^/g;
457 $message =~ s{\003(\d\d?)(?:,(\d?\d?))?|(\017)}{
458 # $1 is FG, $2 is BG, but let's ignore BG
459 my $oldcolor = $color;
466 $color = $color_irc2dp_table[$1];
467 $color = $oldcolor if not defined $color;
469 ($color == $oldcolor) ? '' : '^' . $color;
471 $message =~ s{[\000-\037]}{}gs; # kill bold etc. for now
475 our @text_qfont_table = ( # ripped from DP console.c qfont_table
476 "\0", '#', '#', '#', '#', '.', '#', '#',
477 '#', 9, 10, '#', ' ', 13, '.', '.',
478 '[', ']', '0', '1', '2', '3', '4', '5',
479 '6', '7', '8', '9', '.', '<', '=', '>',
480 ' ', '!', '"', '#', '$', '%', '&', '\'',
481 '(', ')', '*', '+', ',', '-', '.', '/',
482 '0', '1', '2', '3', '4', '5', '6', '7',
483 '8', '9', ':', ';', '<', '=', '>', '?',
484 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
485 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
486 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
487 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
488 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
489 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
490 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
491 'x', 'y', 'z', '{', '|', '}', '~', '<',
492 '<', '=', '>', '#', '#', '.', '#', '#',
493 '#', '#', ' ', '#', ' ', '>', '.', '.',
494 '[', ']', '0', '1', '2', '3', '4', '5',
495 '6', '7', '8', '9', '.', '<', '=', '>',
496 ' ', '!', '"', '#', '$', '%', '&', '\'',
497 '(', ')', '*', '+', ',', '-', '.', '/',
498 '0', '1', '2', '3', '4', '5', '6', '7',
499 '8', '9', ':', ';', '<', '=', '>', '?',
500 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
501 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
502 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
503 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
504 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
505 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
506 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
507 'x', 'y', 'z', '{', '|', '}', '~', '<'
512 $message = join '', map { $text_qfont_table[ord $_] } split //, $message;
519 $message =~ s{\^(.)(?=([0-9,]?))}{
522 $c =~ /^[0-9]$/ ? '' : "^$c";
524 return text_dp2ascii $message;
531 $message =~ s{\^(.)(?=([0-9,]?))}{
535 $c =~ /^[0-9]$/ ? do {
536 my $oldcolor = $color;
537 $c = 0 if $c >= 7; # map 0, 7, 8, 9 to default (no bright white or such stuff)
538 $color = $color_dp2irc_table[$c];
539 ($color == $oldcolor) ? '' :
541 $f eq ',' ? "\0003$color\0002\0002" :
542 $f ne '' ? sprintf "\0003%02d", $color : "\0003$color";
545 $message = text_dp2ascii $message;
546 $message =~ s/\0001/\017/g;
547 $message =~ s/\0002/\002/g;
548 $message =~ s/\0003/\003/g;
556 $message =~ s{\^(.)}{
559 $c =~ /^[0-9]$/ ? do {
560 my $oldcolor = $color;
561 $color = $color_dp2ansi_table[$c];
562 ($color eq $oldcolor) ? '' :
566 $message = text_dp2ascii $message;
567 $message =~ s/\000/\033/g;
574 # if the message ends with an odd number of ^, kill one
575 chop $message if $message =~ /(?:^|[^\^])\^(\^\^)*$/;
581 # Nexuiz specific parsing of some server messages
583 sub nex_is_teamplay($)
586 return $map =~ /^(?:kh|ctf|tdm|dom)_/;
589 sub nex_slotsstring()
592 if(defined $store{slots_max})
594 my $slots = $store{slots_max} - $store{slots_active};
595 my $slots_s = ($slots == 1) ? '' : 's';
596 $slotsstr = " ($slots free slot$slots_s)";
597 my $s = $config{dp_server_from_wan} || $config{dp_server};
598 $slotsstr .= "; join now: \002nexuiz +connect $s"
599 if $slots >= 1 and not $store{lms_blocked};
606 # Do we have a config file? If yes, read and parse it (syntax: key = value
607 # pairs, separated by newlines), if not, complain.
608 die "Usage: $0 configfile\n"
611 open my $fh, "<", $ARGV[0]
612 or die "open $ARGV[0]: $!";
617 /^(.*?)\s+=(?:\s+(.*))?$/ or next;
618 warn "Undefined config item: $1"
619 unless exists $config{$1};
620 $config{$1} = defined $2 ? $2 : "";
623 my @missing = grep { !defined $config{$_} } keys %config;
624 die "The following config items are missing: @missing"
629 # Create a channel for error messages and other internal status messages...
631 $channels{system} = new Channel::FIFO();
633 # for example, quit messages caused by signals (if SIGTERM or SIGINT is first
634 # received, try to shut down cleanly, and if such a signal is received a second
638 exit 1 if $quitting++;
639 $channels{system}->send("quit SIGINT");
642 exit 1 if $quitting++;
643 $channels{system}->send("quit SIGTERM");
648 # Create the two channels to gateway between...
650 $channels{irc} = new Channel::Line(new Connection::Socket(tcp => $config{irc_local} => $config{irc_server} => 6667));
651 $channels{dp} = new Channel::QW(my $dpsock = new Connection::Socket(udp => $config{dp_listen} => $config{dp_server} => 26000), $config{dp_password});
652 $config{dp_listen} = $dpsock->sockname();
653 print "Listening on $config{dp_listen}\n";
655 $channels{irc}->throttle(0.5, 5);
658 # Utility routine to write to a channel by name, also outputting what's been written and some status
662 my $nothrottle = shift;
663 my $chan = $channels{$chanstr};
666 print "UNDEFINED: $chanstr, ignoring message\n";
669 @_ = $chan->join_commands(@_);
672 my $result = $chan->send($_, $nothrottle);
675 print " $chanstr << $_\n";
679 print "FLOOD: $chanstr << $_\n";
683 print "ERROR: $chanstr << $_\n";
684 $channels{system}->send("error $chanstr", 0);
691 # Schedule a task for later execution by the main loop; usage: schedule sub {
692 # task... }, $time; When a scheduled task is run, a reference to the task's own
693 # sub is passed as first argument; that way, the task is able to re-schedule
694 # itself so it gets periodically executed.
697 my ($sub, $time) = @_;
698 push @tasks, [time() + $time, $sub];
701 # On IRC error, delete some data store variables of the connection, and
702 # reconnect to the IRC server soon (but only if someone is actually playing)
705 # prevent multiple instances of this timer
706 return if $store{irc_error_active};
707 $store{irc_error_active} = 1;
709 delete $channels{irc};
712 if(!defined $store{slots_full})
714 # DP is not running, then delay IRC reconnecting
715 #use Data::Dumper; print Dumper \$timer;
716 schedule $timer => 1;;
718 # this will keep irc_error_active
720 $channels{irc} = new Channel::Line(new Connection::Socket(tcp => "" => $config{irc_server}));
721 delete $store{$_} for grep { /^irc_/ } keys %store;
722 $store{irc_nick} = "";
725 out dp => 0, 'sv_cmd bans', 'status 1', 'log_dest_udp';
726 $store{status_waiting} = -1;
728 # this will clear irc_error_active
733 # IRC joining (if this is called as response to a nick name collision, $is433 is set);
734 # among other stuff, it performs NickServ or Quakenet authentication. This is to be called
735 # until the channel has been joined for every message that may be "interesting" (basically,
736 # IRC 001 hello messages, 443 nick collision messages and some notices by services).
742 if $store{irc_joined_channel};
744 #use Data::Dumper; print Dumper \%store;
748 if(length $store{irc_nick})
750 # we already have another nick, but couldn't change to the new one
751 # try ghosting and then get the nick again
752 if(length $config{irc_nickserv_password})
754 if(++$store{irc_nickserv_ghost_attempts} <= $config{irc_nickserv_ghost_attempts})
756 $store{irc_nick_requested} = $config{irc_nick};
757 out irc => 1, sprintf($config{irc_nickserv_ghost}, $config{irc_nick}, $config{irc_nickserv_password});
759 out irc => 1, "NICK $config{irc_nick}";
761 return; # we'll get here again for the NICK success message, or for a 433 failure
763 # otherwise, we failed to ghost and will continue with the wrong
764 # nick... also, no need to try to identify here
766 # otherwise, we can't handle this and will continue with our wrong nick
770 # we failed to get an initial nickname
771 # change ours a bit and try again
772 if(length $store{irc_nick_requested} < 9)
774 $store{irc_nick_requested} .= '_';
778 substr $store{irc_nick_requested}, int(rand length $store{irc_nick_requested}), 1, chr(97 + int rand 26);
780 out irc => 1, "NICK $store{irc_nick_requested}";
781 return; # when it fails, we'll get here again, and when it succeeds, we will continue
785 # we got a 001 or a NICK message, so $store{irc_nick} has been updated
786 if(length $config{irc_nickserv_password})
788 if($store{irc_nick} eq $config{irc_nick})
791 out irc => 1, sprintf($config{irc_nickserv_identify}, $config{irc_nick}, $config{irc_nickserv_password});
796 if(++$store{irc_nickserv_ghost_attempts} <= $config{irc_nickserv_ghost_attempts})
798 $store{irc_nick_requested} = $config{irc_nick};
799 out irc => 1, sprintf($config{irc_nickserv_ghost}, $config{irc_nick}, $config{irc_nickserv_password});
801 out irc => 1, "NICK $config{irc_nick}";
803 return; # we'll get here again for the NICK success message, or for a 433 failure
805 # otherwise, we failed to ghost and will continue with the wrong
806 # nick... also, no need to try to identify here
810 # we are on Quakenet. Try to authenticate.
811 if(length $config{irc_quakenet_password} and length $config{irc_quakenet_authname})
813 if(defined $store{irc_quakenet_challenge})
815 if($store{irc_quakenet_challenge} =~ /^MD5 (.*)/)
817 out irc => 1, "$config{irc_quakenet_challengeauth} $config{irc_quakenet_authname} " . Digest::MD5::md5_hex("$config{irc_quakenet_password} $1");
822 out irc => 1, $config{irc_quakenet_getchallenge};
824 # we get here again when Q asks us
828 # if we get here, we are on IRC
829 $store{irc_joined_channel} = 1;
831 out irc => 1, "JOIN $config{irc_channel}";
836 my $RE_FAIL = qr/$ $/;
837 my $RE_SUCCEED = qr//;
840 return $_[0] ? $RE_FAIL : $RE_SUCCEED;
844 # List of all handlers on the various sockets. Additional handlers can be added by a plugin.
846 # detect a server restart and set it up again
847 [ dp => q{ *(?:Warning: Could not expand \$|Unknown command ")(?:rcon2irc_[a-z0-9_]*)[" ]*} => sub {
849 'alias rcon2irc_eval "$*"',
851 'sv_logscores_console 0',
852 'sv_logscores_bots 1',
854 'sv_eventlog_console 1',
855 'alias rcon2irc_say_as "set say_as_restorenick \"$sv_adminnick\"; sv_adminnick \"$1^3\"; say \"^7$2\"; rcon2irc_say_as_restore"',
856 'alias rcon2irc_say_as_restore "set sv_adminnick \"$say_as_restorenick\""',
857 'alias rcon2irc_quit "echo \"quitting rcon2irc $1: log_dest_udp is $log_dest_udp\""'; # note: \\\\\\" ->perl \\\" ->console \"
861 # detect missing entry in log_dest_udp and fix it
862 [ dp => q{"log_dest_udp" is "([^"]*)" \["[^"]*"\]} => sub {
864 my @dests = split ' ', $dest;
865 return 0 if grep { $_ eq $config{dp_listen} } @dests;
866 out dp => 0, 'log_dest_udp "' . join(" ", @dests, $config{dp_listen}) . '"';
870 # retrieve list of banned hosts
871 [ dp => q{#(\d+): (\S+) is still banned for (\S+) seconds} => sub {
872 return 0 unless $store{status_waiting} < 0;
873 my ($id, $ip, $time) = @_;
874 $store{bans_new} = [] if $id == 0;
875 $store{bans_new}[$id] = { ip => $ip, 'time' => $time };
879 # retrieve hostname from status replies
880 [ dp => q{host: (.*)} => sub {
881 return 0 unless $store{status_waiting} < 0;
883 $store{dp_hostname} = $name;
884 $store{bans} = $store{bans_new};
888 # retrieve version from status replies
889 [ dp => q{version: (.*)} => sub {
890 return 0 unless $store{status_waiting} < 0;
892 $store{dp_version} = $version;
896 # retrieve player names
897 [ dp => q{players: (\d+) active \((\d+) max\)} => sub {
898 return 0 unless $store{status_waiting} < 0;
899 my ($active, $max) = @_;
900 my $full = ($active >= $max);
901 $store{slots_max} = $max;
902 $store{slots_active} = $active;
903 $store{status_waiting} = $active;
904 $store{playerslots_active_new} = [];
905 if($full != ($store{slots_full} || 0))
907 $store{slots_full} = $full;
909 if $store{lms_blocked};
912 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION is full!\001";
916 my $slotsstr = nex_slotsstring();
917 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION can be joined again$slotsstr!\001";
923 # retrieve player names
924 [ dp => q{\^\d(\S+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(-?\d+)\s+\#(\d+)\s+\^\d(.*)} => sub {
925 return 0 unless $store{status_waiting} > 0;
926 my ($ip, $pl, $ping, $time, $frags, $no, $name) = ($1, $2, $3, $4, $5, $6, $7);
927 $store{"playerslot_$no"} = { ip => $ip, pl => $pl, ping => $ping, 'time' => $time, frags => $frags, no => $no, name => $name };
928 push @{$store{playerslots_active_new}}, $no;
929 if(--$store{status_waiting} == 0)
931 $store{playerslots_active} = $store{playerslots_active_new};
937 [ irc => q{:(([^! ]*)![^ ]*) (?i:PRIVMSG) [^&#%]\S* :(.*)} => sub {
938 return 0 unless $config{irc_admin_password} ne '';
940 my ($hostmask, $nick, $command) = @_;
941 my $dpnick = color_dpfix $nick;
943 if($command eq "login $config{irc_admin_password}")
945 $store{logins}{$hostmask} = time() + $config{irc_admin_timeout};
946 out irc => 0, "PRIVMSG $nick :my wish is your command";
950 if($command =~ /^login /)
952 out irc => 0, "PRIVMSG $nick :invalid password";
956 if(($store{logins}{$hostmask} || 0) < time())
958 out irc => 0, "PRIVMSG $nick :authentication required";
962 if($command =~ /^status(?: (.*))?$/)
967 for my $slot(@{$store{playerslots_active} || []})
969 my $s = $store{"playerslot_$slot"};
971 if(not defined $match or index(color_dp2none($s->{name}), $match) >= 0)
973 out irc => 0, sprintf 'PRIVMSG %s :%-21s %2i %4i %8s %4i #%-3u %s', $nick, $s->{ip}, $s->{pl}, $s->{ping}, $s->{time}, $s->{frags}, $slot, color_dp2irc $s->{name};
982 out irc => 0, "PRIVMSG $nick :the server is empty";
986 out irc => 0, "PRIVMSG $nick :no nicknames match";
992 if($command =~ /^kick # (\d+) (.*)$/)
994 my ($id, $reason) = ($1, $2);
995 my $dpreason = color_irc2dp $reason;
996 $dpreason =~ s/^(~?)(.*)/$1irc $dpnick: $2/g;
997 $dpreason =~ s/(["\\])/\\$1/g;
998 out dp => 0, "kick # $id $dpreason";
999 my $slotnik = "playerslot_$id";
1000 out irc => 0, "PRIVMSG $nick :kicked #$id (@{[color_dp2irc $store{$slotnik}{name}]} @ $store{$slotnik}{ip}) ($reason)";
1004 if($command =~ /^kickban # (\d+) (\d+) (\d+) (.*)$/)
1006 my ($id, $bantime, $mask, $reason) = ($1, $2, $3, $4);
1007 my $dpreason = color_irc2dp $reason;
1008 $dpreason =~ s/^(~?)(.*)/$1irc $dpnick: $2/g;
1009 $dpreason =~ s/(["\\])/\\$1/g;
1010 out dp => 0, "kickban # $id $bantime $mask $dpreason";
1011 my $slotnik = "playerslot_$id";
1012 out irc => 0, "PRIVMSG $nick :kickbanned #$id (@{[color_dp2irc $store{$slotnik}{name}]} @ $store{$slotnik}{ip}), netmask $mask, for $bantime seconds ($reason)";
1016 if($command eq "bans")
1020 map { "$_ ($store{bans}[$_]{ip}, $store{bans}[$_]{time}s)" }
1021 0..@{$store{bans} || []}-1;
1022 $banlist = "no bans"
1024 out irc => 0, "PRIVMSG $nick :$banlist";
1028 if($command =~ /^unban (\d+)$/)
1031 out dp => 0, "unban $id";
1032 out irc => 0, "PRIVMSG $nick :removed ban $id ($store{bans}[$id]{ip})";
1036 out irc => 0, "PRIVMSG $nick :unknown command (supported: status [substring], kick # id reason, kickban # id bantime mask reason, bans, unban banid)";
1041 # LMS: detect "no more lives" message
1042 [ dp => q{\^4.*\^4 has no more lives left} => sub {
1043 if(!$store{lms_blocked})
1045 $store{lms_blocked} = 1;
1046 if(!$store{slots_full})
1049 if($store{lms_blocked})
1051 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION can't be joined until next round (a player has no more lives left)\001";
1058 # detect IRC errors and reconnect
1059 [ irc => q{ERROR .*} => \&irc_error ],
1060 [ system => q{error irc} => \&irc_error ],
1063 [ irc => q{:[^ ]* 433 .*} => sub {
1064 return irc_joinstage(433);
1068 [ irc => q{:[^ ]* 001 .*} => sub {
1069 $store{irc_seen_welcome} = 1;
1070 $store{irc_nick} = $store{irc_nick_requested};
1071 return irc_joinstage(0);
1074 # IRC my nickname changed
1075 [ irc => q{:(?i:(??{$store{irc_nick}}))![^ ]* (?i:NICK) :(.*)} => sub {
1077 $store{irc_nick} = $n;
1078 return irc_joinstage(0);
1081 # Quakenet: challenge from Q
1082 [ irc => q{(??{$config{irc_quakenet_challengeprefix}}) (.*)} => sub {
1083 $store{irc_quakenet_challenge} = $1;
1084 return irc_joinstage(0);
1087 # shut down everything on SIGINT
1088 [ system => q{quit (.*)} => sub {
1090 out irc => 1, "QUIT :$cause";
1091 $store{quitcookie} = int rand 1000000000;
1092 out dp => 0, "rcon2irc_quit $store{quitcookie}";
1095 # remove myself from the log destinations and exit everything
1096 [ dp => q{quitting rcon2irc (??{$store{quitcookie}}): log_dest_udp is (.*) *} => sub {
1098 my @dests = grep { $_ ne $config{dp_listen} } split ' ', $dest;
1099 out dp => 0, 'log_dest_udp "' . join(" ", @dests) . '"';
1105 [ irc => q{PING (.*)} => sub {
1107 out irc => 1, "PONG $data";
1112 [ irc => q{:[^ ]* PONG .* :(.*)} => sub {
1115 if not defined $store{irc_pingtime};
1117 if $data ne $store{irc_pingtime};
1118 print "* measured IRC line delay: @{[time() - $store{irc_pingtime}]}\n";
1119 undef $store{irc_pingtime};
1123 # detect channel join message and note hostname length to get the maximum allowed line length
1124 [ irc => q{(:(?i:(??{$store{irc_nick}}))![^ ]* )(?i:JOIN) :(?i:(??{$config{irc_channel}}))} => sub {
1125 $store{irc_maxlen} = 510 - length($1);
1126 $store{irc_joined_channel} = 1;
1127 print "* detected maximum line length for channel messages: $store{irc_maxlen}\n";
1131 # chat: Nexuiz server -> IRC channel
1132 [ dp => q{\001(.*?)\^7: (.*)} => sub {
1133 my ($nick, $message) = map { color_dp2irc $_ } @_;
1134 out irc => 0, "PRIVMSG $config{irc_channel} :<$nick\017> $message";
1138 # chat: Nexuiz server -> IRC channel, nick set
1139 [ dp => q{:join:(\d+):(\d+):([^:]*):(.*)} => sub {
1140 my ($id, $slot, $ip, $nick) = @_;
1141 $nick = color_dp2irc $nick;
1142 $store{"playernick_$id"} = $nick;
1143 $store{"playerslot_$id"} = $slot;
1144 $store{"playerip_$id"} = $ip;
1148 # chat: Nexuiz server -> IRC channel, nick change/set
1149 [ dp => q{:name:(\d+):(.*)} => sub {
1150 my ($id, $nick) = @_;
1151 $nick = color_dp2irc $nick;
1152 my $oldnick = $store{"playernick_$id"};
1153 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 is now known as $nick";
1154 $store{"playernick_$id"} = $nick;
1158 # chat: Nexuiz server -> IRC channel, vote call
1159 [ dp => q{:vote:vcall:(\d+):(.*)} => sub {
1160 my ($id, $command) = @_;
1161 $command = color_dp2irc $command;
1162 my $oldnick = $id ? $store{"playernick_$id"} : "(console)";
1163 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 calls a vote for \"$command\017\"";
1167 # chat: Nexuiz server -> IRC channel, vote stop
1168 [ dp => q{:vote:vstop:(\d+)} => sub {
1170 my $oldnick = $id ? $store{"playernick_$id"} : "(console)";
1171 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 stopped the vote";
1175 # chat: Nexuiz server -> IRC channel, master login
1176 [ dp => q{:vote:vlogin:(\d+)} => sub {
1178 my $oldnick = $id ? $store{"playernick_$id"} : "(console)";
1179 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 logged in as master";
1183 # chat: Nexuiz server -> IRC channel, master do
1184 [ dp => q{:vote:vdo:(\d+):(.*)} => sub {
1185 my ($id, $command) = @_;
1186 $command = color_dp2irc $command;
1187 my $oldnick = $id ? $store{"playernick_$id"} : "(console)";
1188 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 used his master status to do \"$command\017\"";
1192 # chat: Nexuiz server -> IRC channel, result
1193 [ dp => q{:vote:v(yes|no|timeout):(\d+):(\d+):(\d+):(\d+):(-?\d+)} => sub {
1194 my ($result, $yes, $no, $abstain, $not, $min) = @_;
1195 my $spam = "$yes:$no" . (($min >= 0) ? " ($min needed)" : "") . ", $abstain didn't care, $not didn't vote";
1196 out irc => 0, "PRIVMSG $config{irc_channel} :* the vote ended with $result: $spam";
1200 # chat: IRC channel -> Nexuiz server
1201 [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$config{irc_channel}})) :(?i:(??{$store{irc_nick}}))(?: |: ?|, ?)(.*)} => sub {
1202 my ($nick, $message) = @_;
1203 $nick = color_dpfix $nick;
1204 # allow the nickname to contain colors in DP format! Therefore, NO color_irc2dp on the nickname!
1205 $message = color_irc2dp $message;
1206 $message =~ s/(["\\])/\\$1/g;
1207 out dp => 0, "rcon2irc_say_as \"$nick on IRC\" \"$message\"";
1212 length $config{irc_trigger}
1214 [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$config{irc_channel}})) :(?i:(??{$config{irc_trigger}}))(?: |: ?|, ?)(.*)} => sub {
1215 my ($nick, $message) = @_;
1216 $nick = color_dpfix $nick;
1217 # allow the nickname to contain colors in DP format! Therefore, NO color_irc2dp on the nickname!
1218 $message = color_irc2dp $message;
1219 $message =~ s/(["\\])/\\$1/g;
1220 out dp => 0, "rcon2irc_say_as \"$nick on IRC\" \"$message\"";
1227 # irc: CTCP VERSION reply
1228 [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$store{irc_nick}})) :\001VERSION( .*)?\001} => sub {
1230 my $ver = $store{dp_version} or return 0;
1231 $ver .= ", rcon2irc $VERSION";
1232 out irc => 0, "NOTICE $nick :\001VERSION $ver\001";
1235 # on game start, notify the channel
1236 [ dp => q{:gamestart:(.*):[0-9.]*} => sub {
1238 $store{playing} = 1;
1240 $store{map_starttime} = time();
1241 my $slotsstr = nex_slotsstring();
1242 out irc => 0, "PRIVMSG $config{irc_channel} :\00304" . $map . "\017 has begun$slotsstr";
1243 delete $store{lms_blocked};
1247 # on game over, clear the current map
1248 [ dp => q{:gameover} => sub {
1249 $store{playing} = 0;
1253 # scores: Nexuiz server -> IRC channel (start)
1254 [ dp => q{:scores:(.*):(\d+)} => sub {
1255 my ($map, $time) = @_;
1256 $store{scores} = {};
1257 $store{scores}{map} = $map;
1258 $store{scores}{time} = $time;
1259 $store{scores}{players} = [];
1260 delete $store{lms_blocked};
1264 # scores: Nexuiz server -> IRC channel, legacy format
1265 [ dp => q{:player:(-?\d+):(\d+):(\d+):(\d+):(\d+):(.*)} => sub {
1266 my ($frags, $deaths, $time, $team, $id, $name) = @_;
1267 return if not exists $store{scores};
1268 push @{$store{scores}{players}}, [$frags, $team, $name]
1269 unless $frags <= -666; # no spectators
1273 # scores: Nexuiz server -> IRC channel (CTF), legacy format
1274 [ dp => q{:teamscores:(\d+:-?\d*(?::\d+:-?\d*)*)} => sub {
1276 return if not exists $store{scores};
1277 $store{scores}{teams} = {split /:/, $teams};
1281 # scores: Nexuiz server -> IRC channel, new format
1282 [ dp => q{:player:see-labels:(\d+)[-0-9,]*:(\d+):(\d+):(\d+):(.*)} => sub {
1283 my ($frags, $time, $team, $id, $name) = @_;
1284 return if not exists $store{scores};
1285 push @{$store{scores}{players}}, [$frags, $team, $name];
1289 # scores: Nexuiz server -> IRC channel (CTF), new format
1290 [ dp => q{:teamscores:see-labels:(\d+)[-0-9,]*:(\d+)} => sub {
1291 my ($frags, $team) = @_;
1292 return if not exists $store{scores};
1293 $store{scores}{teams}{$team} = $frags;
1297 # scores: Nexuiz server -> IRC channel
1298 [ dp => q{:end} => sub {
1299 return if not exists $store{scores};
1300 my $s = $store{scores};
1301 delete $store{scores};
1302 my $teams_matter = nex_is_teamplay($s->{map});
1309 # put players into teams
1311 for(@{$s->{players}})
1313 my $thisteam = ($t{$_->[1]} ||= {score => 0, team => $_->[1], players => []});
1314 push @{$thisteam->{players}}, [$_->[0], $_->[1], $_->[2]];
1317 $thisteam->{score} = $s->{teams}{$_->[1]};
1321 $thisteam->{score} += $_->[0];
1325 # sort by team score
1326 @t = sort { $b->{score} <=> $a->{score} } values %t;
1328 # sort by player score
1332 @{$_->{players}} = sort { $b->[0] <=> $a->[0] } @{$_->{players}};
1333 push @p, @{$_->{players}};
1338 @p = sort { $b->[0] <=> $a->[0] } @{$s->{players}};
1341 # no display for empty server
1345 # make message fit somehow
1346 for my $maxnamelen(reverse 3..64)
1348 my $scores_string = "PRIVMSG $config{irc_channel} :\00304" . $s->{map} . "\017 ended:";
1354 $scores_string .= $sep . sprintf "\003%02d\%d\017", $color_team2irc_table{$_->{team}}, $_->{score};
1361 my ($frags, $team, $name) = @$_;
1362 $name = color_dpfix substr($name, 0, $maxnamelen);
1365 $name = "\003" . $color_team2irc_table{$team} . " " . color_dp2none $name;
1369 $name = " " . color_dp2irc $name;
1371 $scores_string .= "$sep$name\017 $frags";
1374 if(length($scores_string) <= ($store{irc_maxlen} || 256))
1376 out irc => 0, $scores_string;
1380 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION would have LIKED to put the scores here, but they wouldn't fit :(\001";
1384 # complain when system load gets too high
1385 [ dp => q{timing: (([0-9.]*)% CPU, ([0-9.]*)% lost, offset avg ([0-9.]*)ms, max ([0-9.]*)ms, sdev ([0-9.]*)ms)} => sub {
1386 my ($all, $cpu, $lost, $avg, $max, $sdev) = @_;
1387 return 0 # don't complain when just on the voting screen
1388 if !$store{playing};
1389 return 0 # don't complain if it was less than 0.5%
1391 return 0 # don't complain if nobody is looking
1392 if $store{slots_active} == 0;
1393 return 0 # don't complain in the first two minutes
1394 if time() - $store{map_starttime} < 120;
1395 return 0 # don't complain if it was already at least half as bad in this round
1396 if $store{map_starttime} == $store{timingerror_map_starttime} and $lost <= 2 * $store{timingerror_lost};
1397 $store{timingerror_map_starttime} = $store{map_starttime};
1398 $store{timingerror_lost} = $lost;
1399 out dp => 0, 'rcon2irc_say_as server "There are currently some severe system load problems. The admins have been notified."';
1400 out irc => 1, "PRIVMSG $config{irc_channel} :\001ACTION has big trouble on $store{map} after @{[int(time() - $store{map_starttime})]}s: $all\001";
1401 #out irc => 1, "PRIVMSG OpBaI :\001ACTION has big trouble on $store{map} after @{[int(time() - $store{map_starttime})]}s: $all\001";
1408 # Load plugins and add them to the handler list in the front.
1409 for my $p(split ' ', $config{plugins})
1411 my @h = eval { do $p; }
1412 or die "Invalid plugin $p: $@";
1415 ref $_ eq 'ARRAY' or die "Invalid plugin $p: did not return a list of arrays";
1416 @$_ == 3 or die "Invalid plugin $p: did not return a list of three-element arrays";
1417 !ref $_->[0] && !ref $_->[1] && ref $_->[2] eq 'CODE' or die "Invalid plugin $p: did not return a list of string-string-sub arrays";
1418 unshift @handlers, $_;
1424 # verify that the server is up by letting it echo back a string that causes
1425 # re-initialization of the required aliases
1426 out dp => 0, 'echo "Unknown command \"rcon2irc_eval\""'; # assume the server has been restarted
1430 # regularily, query the server status and if it still is connected to us using
1431 # the log_dest_udp feature. If not, we will detect the response to this rcon
1432 # command and re-initialize the server's connection to us (either by log_dest_udp
1433 # not containing our own IP:port, or by rcon2irc_eval not being a defined command).
1436 out dp => 0, 'sv_cmd bans', 'status 1', 'log_dest_udp', 'rcon2irc_eval set dummy 1';
1437 $store{status_waiting} = -1;
1438 schedule $timer => (exists $store{dp_hostname} ? $config{dp_status_delay} : 1);;
1443 # Continue with connecting to IRC as soon as we get our first status reply from
1444 # the DP server (which contains the server's hostname that we'll use as
1445 # realname for IRC).
1449 # log on to IRC when needed
1450 if(exists $store{dp_hostname} && !exists $store{irc_logged_in})
1452 $store{irc_nick_requested} = $config{irc_nick};
1453 out irc => 1, "NICK $config{irc_nick}", "USER $config{irc_user} localhost localhost :$store{dp_hostname}";
1454 $store{irc_logged_in} = 1;
1455 undef $store{irc_maxlen};
1456 undef $store{irc_pingtime};
1459 schedule $timer => 1;;
1464 # Regularily ping the IRC server to detect if the connection is down. If it is,
1465 # schedule an IRC error that will cause reconnection later.
1469 if($store{irc_logged_in})
1471 if(defined $store{irc_pingtime})
1473 # IRC connection apparently broke
1474 # so... KILL IT WITH FIRE
1475 $channels{system}->send("error irc", 0);
1479 # everything is fine, send a new ping
1480 $store{irc_pingtime} = time();
1481 out irc => 1, "PING $store{irc_pingtime}";
1485 schedule $timer => $config{irc_ping_delay};;
1493 # Build up an IO::Select object for all our channels.
1494 my $s = IO::Select->new();
1495 for my $chan(values %channels)
1497 $s->add($_) for $chan->fds();
1500 # wait for something to happen on our sockets, or wait 2 seconds without anything happening there
1502 my @errors = $s->has_exception(0);
1504 # on every channel, look for incoming messages
1506 for my $chanstr(keys %channels)
1508 my $chan = $channels{$chanstr};
1509 my @chanfds = $chan->fds();
1511 for my $chanfd(@chanfds)
1513 if(grep { $_ == $chanfd } @errors)
1515 # STOP! This channel errored!
1516 $channels{system}->send("error $chanstr", 0);
1523 for my $line($chan->recv())
1525 # found one! Check if it matches the regular expression of one of
1529 for my $h(@handlers)
1531 my ($chanstr_wanted, $re, $sub) = @$h;
1533 if $chanstr_wanted ne $chanstr;
1535 my @matches = ($line =~ /^$re$/s);
1539 # and if it is a match, handle it.
1541 my $result = $sub->(@matches);
1547 # print the message, together with info on whether it has been handled or not
1550 print " $chanstr >> (private)\n";
1554 print " $chanstr >> $line\n";
1558 print "unhandled: $chanstr >> $line\n";
1563 if($@ eq "read error\n")
1565 $channels{system}->send("error $chanstr", 0);
1576 # handle scheduled tasks...
1579 # by emptying the list of tasks...
1583 my ($time, $sub) = @$_;
1586 # calling them if they are schedled for the "past"...
1591 # or re-adding them to the task list if they still are scheduled for the "future"
1592 push @tasks, [$time, $sub];