]> icculus.org git repositories - divverent/nexuiz.git/blob - server/rcon2irc/rcon2irc.pl
irc_nick_alternates;
[divverent/nexuiz.git] / server / rcon2irc / rcon2irc.pl
1 #!/usr/bin/perl
2
3 our $VERSION = '0.4.2 svn $Revision$';
4
5 # Copyright (c) 2008 Rudolf "divVerent" Polzer
6
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
14 # conditions:
15
16 # The above copyright notice and this permission notice shall be
17 # included in all copies or substantial portions of the Software.
18
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.
27
28 # MISC STRING UTILITY ROUTINES to convert between DarkPlaces and IRC conventions
29
30 # convert mIRC color codes to DP color codes
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);
36 sub color_irc2dp($)
37 {
38         my ($message) = @_;
39         $message =~ s/\^/^^/g;
40         my $color = 7;
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;
44                 if($3)
45                 {
46                         $color = 7;
47                 }
48                 else
49                 {
50                         $color = $color_irc2dp_table[$1];
51                         $color = $oldcolor if not defined $color;
52                 }
53                 ($color == $oldcolor) ? '' : '^' . $color;
54         }esg;
55         $message =~ s{[\000-\037]}{}gs; # kill bold etc. for now
56         return $message;
57 }
58
59 our @text_qfont_table = ( # ripped from DP console.c qfont_table
60     "\0", '#',  '#',  '#',  '#',  '.',  '#',  '#',
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',  '{',  '|',  '}',  '~',  '<'
92 );
93 sub text_dp2ascii($)
94 {
95         my ($message) = @_;
96         $message = join '', map { $text_qfont_table[ord $_] } split //, $message;
97 }
98
99 sub color_dp_transform(&$)
100 {
101         my ($block, $message) = @_;
102
103         $message =~ s{(?:(\^\^)|\^x([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])|\^([0-9])|(.))(?=([0-9,]?))}{
104                 defined $1 ? $block->(char => '^', $7) :
105                 defined $2 ? $block->(rgb => [hex $2, hex $3, hex $4], $7) :
106                 defined $5 ? $block->(color => $5, $7) :
107                 defined $6 ? $block->(char => $6, $7) :
108                         die "Invalid match";
109         }esg;
110
111         return $message;
112 }
113
114 sub color_dp2none($)
115 {
116         my ($message) = @_;
117
118         return color_dp_transform
119         {
120                 my ($type, $data, $next) = @_;
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 { $a <=> $b } ($R, $G, $B)]->[0];
133         my $max = [sort { $a <=> $b } ($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                 $type eq 'char'  ? ($data eq '^' ? '^^' : $data) :
178                 $type eq 'color' ? "^$data" :
179                 $type eq 'rgb'   ? "^" . color_rgb2basic $data :
180                         die "Invalid type";
181         }
182         $message;
183 }
184
185 sub color_dp2irc($)
186 {
187         my ($message) = @_;
188         my $color = -1;
189         return color_dp_transform
190         {
191                 my ($type, $data, $next) = @_;
192
193                 if($type eq 'rgb')
194                 {
195                         $type = 'color';
196                         $data = color_rgb2basic $data;
197                 }
198
199                 $type eq 'char'  ? $text_qfont_table[ord $data] :
200                 $type eq 'color' ? do {
201                         my $oldcolor = $color;
202                         $color = $color_dp2irc_table[$data];
203
204                         $color == $oldcolor ? '' :
205                         $color < 0          ? "\017" :
206                         $next eq ','        ? "\003$color\002\002" :
207                                               sprintf "\003%02d", $color;
208                 } :
209                         die "Invalid type";
210         }
211         $message;
212 }
213
214 sub color_dp2ansi($)
215 {
216         my ($message) = @_;
217         my $color = -1;
218         return color_dp_transform
219         {
220                 my ($type, $data, $next) = @_;
221
222                 if($type eq 'rgb')
223                 {
224                         $type = 'color';
225                         $data = color_rgb2basic $data;
226                 }
227
228                 $type eq 'char'  ? $text_qfont_table[ord $data] :
229                 $type eq 'color' ? do {
230                         my $oldcolor = $color;
231                         $color = $color_dp2ansi_table[$data];
232
233                         $color eq $oldcolor ? '' :
234                                               "\033[${color}"
235                 } :
236                         die "Invalid type";
237         }
238         $message;
239 }
240
241 sub color_dpfix($)
242 {
243         my ($message) = @_;
244         # if the message ends with an odd number of ^, kill one
245         chop $message if $message =~ /(?:^|[^\^])\^(\^\^)*$/;
246         return $message;
247 }
248
249
250
251
252 # Interfaces:
253 #   Connection:
254 #     $conn->sockname() returns a connection type specific representation
255 #       string of the local address, or undef if not applicable.
256 #     $conn->send("string") sends something over the connection.
257 #     $conn->recv() receives a string from the connection, or returns "" if no
258 #       data is available.
259 #     $conn->fds() returns all file descriptors used by the connection, so one
260 #       can use select() on them.
261 #   Channel:
262 #     Usually wraps around a connection and implements a command based
263 #     structure over it. It usually is constructed using new
264 #     ChannelType($connection, someparameters...)
265 #     @cmds = $chan->join_commands(@cmds) joins multiple commands to a single
266 #       command string if the protocol supports it, or does nothing and leaves
267 #       @cmds unchanged if the protocol does not support that usage (this is
268 #       meant to save send() invocations).
269 #     $chan->send($command, $nothrottle) sends a command over the channel. If
270 #       $nothrottle is sent, the command must not be left out even if the channel
271 #       is saturated (for example, because of IRC's flood control mechanism).
272 #     $chan->quote($str) returns a string in a quoted form so it can safely be
273 #       inserted as a substring into a command, or returns $str as is if not
274 #       applicable. It is assumed that the result of the quote method is used
275 #       as part of a quoted string, if the protocol supports that.
276 #     $chan->recv() returns a list of received commands from the channel, or
277 #       the empty list if none are available.
278 #     $conn->fds() returns all file descriptors used by the channel's
279 #       connections, so one can use select() on them.
280
281
282
283
284
285
286
287 # Socket connection.
288 # Represents a connection over a socket.
289 # Mainly used to wrap a channel around it for, in this case, line based or rcon-like operation.
290 package Connection::Socket;
291 use strict;
292 use warnings;
293 use IO::Socket::INET;
294 use IO::Handle;
295
296 # Constructor:
297 #   my $conn = new Connection::Socket(tcp => "localaddress" => "remoteaddress" => 6667);
298 # If the remote address does not contain a port number, the numeric port is
299 # used (it serves as a default port).
300 sub new($$)
301 {
302         my ($class, $proto, $local, $remote, $defaultport) = @_;
303         my $sock = IO::Socket::INET->new(
304                 Proto => $proto,
305                 (length($local) ? (LocalAddr => $local) : ()),
306                 PeerAddr => $remote,
307                 PeerPort => $defaultport
308         ) or die "socket $proto/$local/$remote: $!";
309         $sock->blocking(0);
310         my $you = {
311                 # Mortal fool! Release me from this wretched tomb! I must be set free
312                 # or I will haunt you forever! I will hide your keys beneath the
313                 # cushions of your upholstered furniture... and NEVERMORE will you be
314                 # able to find socks that match!
315                 sock => $sock,
316                 # My demonic powers have made me OMNIPOTENT! Bwahahahahahahaha!
317         };
318         return
319                 bless $you, 'Connection::Socket';
320 }
321
322 # $sock->sockname() returns the local address of the socket.
323 sub sockname($)
324 {
325         my ($self) = @_;
326         my ($port, $addr) = sockaddr_in $self->{sock}->sockname();
327         return "@{[inet_ntoa $addr]}:$port";
328 }
329
330 # $sock->send($data) sends some data over the socket; on success, 1 is returned.
331 sub send($$)
332 {
333         my ($self, $data) = @_;
334         return 1
335                 if not length $data;
336         if(not eval { $self->{sock}->send($data); })
337         {
338                 warn "$@";
339                 return 0;
340         }
341         return 1;
342 }
343
344 # $sock->recv() receives as much as possible from the socket (or at most 32k). Returns "" if no data is available.
345 sub recv($)
346 {
347         my ($self) = @_;
348         my $data = "";
349         if(defined $self->{sock}->recv($data, 32768, 0))
350         {
351                 return $data;
352         }
353         elsif($!{EAGAIN})
354         {
355                 return "";
356         }
357         else
358         {
359                 return undef;
360         }
361 }
362
363 # $sock->fds() returns the socket file descriptor.
364 sub fds($)
365 {
366         my ($self) = @_;
367         return fileno $self->{sock};
368 }
369
370
371
372
373
374
375
376 # Line-based buffered connectionless FIFO channel.
377 # Whatever is sent to it using send() is echoed back when using recv().
378 package Channel::FIFO;
379 use strict;
380 use warnings;
381
382 # Constructor:
383 #   my $chan = new Channel::FIFO();
384 sub new($)
385 {
386         my ($class) = @_;
387         my $you = {
388                 buffer => []
389         };
390         return
391                 bless $you, 'Channel::FIFO';
392 }
393
394 sub join_commands($@)
395 {
396         my ($self, @data) = @_;
397         return @data;
398 }
399
400 sub send($$$)
401 {
402         my ($self, $line, $nothrottle) = @_;
403         push @{$self->{buffer}}, $line;
404 }
405
406 sub quote($$)
407 {
408         my ($self, $data) = @_;
409         return $data;
410 }
411
412 sub recv($)
413 {
414         my ($self) = @_;
415         my $r = $self->{buffer};
416         $self->{buffer} = [];
417         return @$r;
418 }
419
420 sub fds($)
421 {
422         my ($self) = @_;
423         return ();
424 }
425
426
427
428
429
430
431
432 # QW rcon protocol channel.
433 # Wraps around a UDP based Connection and sends commands as rcon commands as
434 # well as receives rcon replies. The quote and join_commands methods are using
435 # DarkPlaces engine specific rcon protocol extensions.
436 package Channel::QW;
437 use strict;
438 use warnings;
439
440 # Constructor:
441 #   my $chan = new Channel::QW($connection, "password");
442 sub new($$)
443 {
444         my ($class, $conn, $password) = @_;
445         my $you = {
446                 connector => $conn,
447                 password => $password,
448                 recvbuf => "",
449         };
450         return
451                 bless $you, 'Channel::QW';
452 }
453
454 # Note: multiple commands in one rcon packet is a DarkPlaces extension.
455 sub join_commands($@)
456 {
457         my ($self, @data) = @_;
458         return join "\0", @data;
459 }
460
461 sub send($$$)
462 {
463         my ($self, $line, $nothrottle) = @_;
464         return $self->{connector}->send("\377\377\377\377rcon $self->{password} $line");
465 }
466
467 # Note: backslash and quotation mark escaping is a DarkPlaces extension.
468 sub quote($$)
469 {
470         my ($self, $data) = @_;
471         $data =~ s/[\000-\037]//g;
472         $data =~ s/([\\"])/\\$1/g;
473         $data =~ s/\$/\$\$/g;
474         return $data;
475 }
476
477 sub recv($)
478 {
479         my ($self) = @_;
480         for(;;)
481         {
482                 my $s = $self->{connector}->recv();
483                 die "read error\n"
484                         if not defined $s;
485                 length $s
486                         or last;
487                 next
488                         if $s !~ /^\377\377\377\377n(.*)$/s;
489                 $self->{recvbuf} .= $1;
490         }
491         my @out = ();
492         while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
493         {
494                 push @out, $1;
495         }
496         return @out;
497 }
498
499 sub fds($)
500 {
501         my ($self) = @_;
502         return $self->{connector}->fds();
503 }
504
505
506
507
508
509
510
511 # Line based protocol channel.
512 # Wraps around a TCP based Connection and sends commands as text lines
513 # (separated by CRLF). When reading responses from the Connection, any type of
514 # line ending is accepted.
515 # A flood control mechanism is implemented.
516 package Channel::Line;
517 use strict;
518 use warnings;
519 use Time::HiRes qw/time/;
520
521 # Constructor:
522 #   my $chan = new Channel::Line($connection);
523 sub new($$)
524 {
525         my ($class, $conn) = @_;
526         my $you = {
527                 connector => $conn,
528                 recvbuf => "",
529                 capacity => undef,
530                 linepersec => undef,
531                 maxlines => undef,
532                 lastsend => time()
533         };
534         return 
535                 bless $you, 'Channel::Line';
536 }
537
538 sub join_commands($@)
539 {
540         my ($self, @data) = @_;
541         return @data;
542 }
543
544 # Sets new flood control parameters:
545 #   $chan->throttle(maximum lines per second, maximum burst length allowed to
546 #     exceed the lines per second limit);
547 #   RFC 1459 describes these parameters to be 0.5 and 5 for the IRC protocol.
548 #   If the $nothrottle flag is set while sending, the line is sent anyway even
549 #   if flooding would take place.
550 sub throttle($$$)
551 {
552         my ($self, $linepersec, $maxlines) = @_;
553         $self->{linepersec} = $linepersec;
554         $self->{maxlines} = $maxlines;
555         $self->{capacity} = $maxlines;
556 }
557
558 sub send($$$)
559 {
560         my ($self, $line, $nothrottle) = @_;
561         my $t = time();
562         if(defined $self->{capacity})
563         {
564                 $self->{capacity} += ($t - $self->{lastsend}) * $self->{linepersec};
565                 $self->{lastsend} = $t;
566                 $self->{capacity} = $self->{maxlines}
567                         if $self->{capacity} > $self->{maxlines};
568                 if(!$nothrottle)
569                 {
570                         return -1
571                                 if $self->{capacity} < 0;
572                 }
573                 $self->{capacity} -= 1;
574         }
575         $line =~ s/\r|\n//g;
576         return $self->{connector}->send("$line\r\n");
577 }
578
579 sub quote($$)
580 {
581         my ($self, $data) = @_;
582         $data =~ s/\r\n?/\n/g;
583         $data =~ s/\n/*/g;
584         return $data;
585 }
586
587 sub recv($)
588 {
589         my ($self) = @_;
590         for(;;)
591         {
592                 my $s = $self->{connector}->recv();
593                 die "read error\n"
594                         if not defined $s;
595                 length $s
596                         or last;
597                 $self->{recvbuf} .= $s;
598         }
599         my @out = ();
600         while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
601         {
602                 push @out, $1;
603         }
604         return @out;
605 }
606
607 sub fds($)
608 {
609         my ($self) = @_;
610         return $self->{connector}->fds();
611 }
612
613
614
615
616
617
618 # main program... a gateway between IRC and DarkPlaces servers
619 package main;
620
621 use strict;
622 use warnings;
623 use IO::Select;
624 use Digest::MD5;
625 use Time::HiRes qw/time/;
626
627 our @handlers = (); # list of [channel, expression, sub to handle result]
628 our @tasks = (); # list of [time, sub]
629 our %channels = ();
630 our %store = (
631         irc_nick => "",
632         playernick_byid_0 => "(console)",
633 );
634 our %config = (
635         irc_server => undef,
636         irc_nick => undef,
637         irc_nick_alternates => "",
638         irc_user => undef,
639         irc_channel => undef,
640         irc_ping_delay => 120,
641         irc_trigger => "",
642
643         irc_nickserv_password => "",
644         irc_nickserv_identify => 'PRIVMSG NickServ :IDENTIFY %2$s',
645         irc_nickserv_ghost => 'PRIVMSG NickServ :GHOST %1$s %2$s',
646         irc_nickserv_ghost_attempts => 3,
647
648         irc_quakenet_authname => "",
649         irc_quakenet_password => "",
650         irc_quakenet_getchallenge => 'PRIVMSG Q@CServe.quakenet.org :CHALLENGE',
651         irc_quakenet_challengeauth => 'PRIVMSG Q@CServe.quakenet.org :CHALLENGEAUTH',
652         irc_quakenet_challengeprefix => ':Q!TheQBot@CServe.quakenet.org NOTICE [^:]+ :CHALLENGE',
653
654         dp_server => undef,
655         dp_listen => "", 
656         dp_password => undef,
657         dp_status_delay => 30,
658         dp_server_from_wan => "",
659         irc_local => "",
660
661         irc_admin_password => "",
662         irc_admin_timeout => 3600,
663
664         plugins => "",
665 );
666
667
668
669 # Nexuiz specific parsing of some server messages
670
671 sub nex_is_teamplay($)
672 {
673         my ($map) = @_;
674         return $map =~ /^(?:kh|ctf|tdm|dom)_/;
675 }
676
677 sub nex_slotsstring()
678 {
679         my $slotsstr = "";
680         if(defined $store{slots_max})
681         {
682                 my $slots = $store{slots_max} - $store{slots_active};
683                 my $slots_s = ($slots == 1) ? '' : 's';
684                 $slotsstr = " ($slots free slot$slots_s)";
685                 my $s = $config{dp_server_from_wan} || $config{dp_server};
686                 $slotsstr .= "; join now: \002nexuiz +connect $s"
687                         if $slots >= 1 and not $store{lms_blocked};
688         }
689         return $slotsstr;
690 }
691
692
693
694 # Do we have a config file? If yes, read and parse it (syntax: key = value
695 # pairs, separated by newlines), if not, complain.
696 die "Usage: $0 configfile\n"
697         unless @ARGV == 1;
698
699 open my $fh, "<", $ARGV[0]
700         or die "open $ARGV[0]: $!";
701 while(<$fh>)
702 {
703         chomp;
704         /^#/ and next;
705         /^(.*?)\s*=(?:\s*(.*))?$/ or next;
706         warn "Undefined config item: $1"
707                 unless exists $config{$1};
708         $config{$1} = defined $2 ? $2 : "";
709 }
710 close $fh;
711 my @missing = grep { !defined $config{$_} } keys %config;
712 die "The following config items are missing: @missing"
713         if @missing;
714
715
716
717 # Create a channel for error messages and other internal status messages...
718
719 $channels{system} = new Channel::FIFO();
720
721 # for example, quit messages caused by signals (if SIGTERM or SIGINT is first
722 # received, try to shut down cleanly, and if such a signal is received a second
723 # time, just exit)
724 my $quitting = 0;
725 $SIG{INT} = sub {
726         exit 1 if $quitting++;
727         $channels{system}->send("quit SIGINT");
728 };
729 $SIG{TERM} = sub {
730         exit 1 if $quitting++;
731         $channels{system}->send("quit SIGTERM");
732 };
733
734
735
736 # Create the two channels to gateway between...
737
738 $channels{irc} = new Channel::Line(new Connection::Socket(tcp => $config{irc_local} => $config{irc_server} => 6667));
739 $channels{dp} = new Channel::QW(my $dpsock = new Connection::Socket(udp => $config{dp_listen} => $config{dp_server} => 26000), $config{dp_password});
740 $config{dp_listen} = $dpsock->sockname();
741 print "Listening on $config{dp_listen}\n";
742
743 $channels{irc}->throttle(0.5, 5);
744
745
746 # Utility routine to write to a channel by name, also outputting what's been written and some status
747 sub out($$@)
748 {
749         my $chanstr = shift;
750         my $nothrottle = shift;
751         my $chan = $channels{$chanstr};
752         if(!$chan)
753         {
754                 print "UNDEFINED: $chanstr, ignoring message\n";
755                 return;
756         }
757         @_ = $chan->join_commands(@_);
758         for(@_)
759         {
760                 my $result = $chan->send($_, $nothrottle);
761                 if($result > 0)
762                 {
763                         print "           $chanstr << $_\n";
764                 }
765                 elsif($result < 0)
766                 {
767                         print "FLOOD:     $chanstr << $_\n";
768                 }
769                 else
770                 {
771                         print "ERROR:     $chanstr << $_\n";
772                         $channels{system}->send("error $chanstr", 0);
773                 }
774         }
775 }
776
777
778
779 # Schedule a task for later execution by the main loop; usage: schedule sub {
780 # task... }, $time; When a scheduled task is run, a reference to the task's own
781 # sub is passed as first argument; that way, the task is able to re-schedule
782 # itself so it gets periodically executed.
783 sub schedule($$)
784 {
785         my ($sub, $time) = @_;
786         push @tasks, [time() + $time, $sub];
787 }
788
789 # On IRC error, delete some data store variables of the connection, and
790 # reconnect to the IRC server soon (but only if someone is actually playing)
791 sub irc_error()
792 {
793         # prevent multiple instances of this timer
794         return if $store{irc_error_active};
795         $store{irc_error_active} = 1;
796
797         delete $channels{irc};
798         schedule sub {
799                 my ($timer) = @_;
800                 if(!defined $store{slots_full})
801                 {
802                         # DP is not running, then delay IRC reconnecting
803                         #use Data::Dumper; print Dumper \$timer;
804                         schedule $timer => 1;;
805                         return;
806                         # this will keep irc_error_active
807                 }
808                 $channels{irc} = new Channel::Line(new Connection::Socket(tcp => "" => $config{irc_server}));
809                 delete $store{$_} for grep { /^irc_/ } keys %store;
810                 $store{irc_nick} = "";
811                 schedule sub {
812                         my ($timer) = @_;
813                         out dp => 0, 'sv_cmd bans', 'status 1', 'log_dest_udp';
814                         $store{status_waiting} = -1;
815                 } => 1;
816                 # this will clear irc_error_active
817         } => 30;
818         return 0;
819 }
820
821 sub uniq(@)
822 {
823         my @out = ();
824         my %found = ();
825         for(@_)
826         {
827                 next if $found{$_}++;
828                 push @out, $_;
829         }
830         return @out;
831 }
832
833 # IRC joining (if this is called as response to a nick name collision, $is433 is set);
834 # among other stuff, it performs NickServ or Quakenet authentication. This is to be called
835 # until the channel has been joined for every message that may be "interesting" (basically,
836 # IRC 001 hello messages, 443 nick collision messages and some notices by services).
837 sub irc_joinstage($)
838 {
839         my($is433) = @_;
840
841         return 0
842                 if $store{irc_joined_channel};
843         
844                 #use Data::Dumper; print Dumper \%store;
845
846         if($is433)
847         {
848                 if(length $store{irc_nick})
849                 {
850                         # we already have another nick, but couldn't change to the new one
851                         # try ghosting and then get the nick again
852                         if(length $config{irc_nickserv_password})
853                         {
854                                 if(++$store{irc_nickserv_ghost_attempts} <= $config{irc_nickserv_ghost_attempts})
855                                 {
856                                         $store{irc_nick_requested} = $config{irc_nick};
857                                         out irc => 1, sprintf($config{irc_nickserv_ghost}, $config{irc_nick}, $config{irc_nickserv_password});
858                                         schedule sub {
859                                                 out irc => 1, "NICK $config{irc_nick}";
860                                         } => 1;
861                                         return; # we'll get here again for the NICK success message, or for a 433 failure
862                                 }
863                                 # otherwise, we failed to ghost and will continue with the wrong
864                                 # nick... also, no need to try to identify here
865                         }
866                         # otherwise, we can't handle this and will continue with our wrong nick
867                 }
868                 else
869                 {
870                         # we failed to get an initial nickname
871                         # change ours a bit and try again
872
873                         my @alternates = ($config{irc_nick}, grep { $_ ne "" } split /\s+/, $config{irc_nick_alternates});
874                         my $nextnick = undef;
875                         for(0..@alternates-2)
876                         {
877                                 if($store{irc_nick_requested} eq $alternates[$_])
878                                 {
879                                         $nextnick = $alternates[$_+1];
880                                 }
881                         }
882                         if($store{irc_nick_requested} eq $alternates[@alternates-1])
883                         {
884                                 $store{irc_nick_requested} = $alternates[0];
885                                 # but don't set nextnick, so we edit it
886                         }
887                         if(not defined $nextnick)
888                         {
889                                 for(;;)
890                                 {
891                                         if(length $store{irc_nick_requested} < 9)
892                                         {
893                                                 $store{irc_nick_requested} .= '_';
894                                         }
895                                         else
896                                         {
897                                                 substr $store{irc_nick_requested}, int(rand length $store{irc_nick_requested}), 1, chr(97 + int rand 26);
898                                         }
899                                         last unless grep { $_ eq $store{irc_nick_requested} } @alternates;
900                                 }
901                         }
902                         out irc => 1, "NICK $store{irc_nick_requested}";
903                         return; # when it fails, we'll get here again, and when it succeeds, we will continue
904                 }
905         }
906
907         # we got a 001 or a NICK message, so $store{irc_nick} has been updated
908         if(length $config{irc_nickserv_password})
909         {
910                 if($store{irc_nick} eq $config{irc_nick})
911                 {
912                         # identify
913                         out irc => 1, sprintf($config{irc_nickserv_identify}, $config{irc_nick}, $config{irc_nickserv_password});
914                 }
915                 else
916                 {
917                         # ghost
918                         if(++$store{irc_nickserv_ghost_attempts} <= $config{irc_nickserv_ghost_attempts})
919                         {
920                                 $store{irc_nick_requested} = $config{irc_nick};
921                                 out irc => 1, sprintf($config{irc_nickserv_ghost}, $config{irc_nick}, $config{irc_nickserv_password});
922                                 schedule sub {
923                                         out irc => 1, "NICK $config{irc_nick}";
924                                 } => 1;
925                                 return; # we'll get here again for the NICK success message, or for a 433 failure
926                         }
927                         # otherwise, we failed to ghost and will continue with the wrong
928                         # nick... also, no need to try to identify here
929                 }
930         }
931
932         # we are on Quakenet. Try to authenticate.
933         if(length $config{irc_quakenet_password} and length $config{irc_quakenet_authname})
934         {
935                 if(defined $store{irc_quakenet_challenge})
936                 {
937                         if($store{irc_quakenet_challenge} =~ /^MD5 (.*)/)
938                         {
939                                 out irc => 1, "$config{irc_quakenet_challengeauth} $config{irc_quakenet_authname} " . Digest::MD5::md5_hex("$config{irc_quakenet_password} $1");
940                         }
941                 }
942                 else
943                 {
944                         out irc => 1, $config{irc_quakenet_getchallenge};
945                         return;
946                         # we get here again when Q asks us
947                 }
948         }
949         
950         # if we get here, we are on IRC
951         $store{irc_joined_channel} = 1;
952         schedule sub {
953                 out irc => 1, "JOIN $config{irc_channel}";
954         } => 1;
955         return 0;
956 }
957
958 my $RE_FAIL = qr/$ $/;
959 my $RE_SUCCEED = qr//;
960 sub cond($)
961 {
962         return $_[0] ? $RE_FAIL : $RE_SUCCEED;
963 }
964
965
966 # List of all handlers on the various sockets. Additional handlers can be added by a plugin.
967 @handlers = (
968         # detect a server restart and set it up again
969         [ dp => q{ *(?:Warning: Could not expand \$|Unknown command ")(?:rcon2irc_[a-z0-9_]*)[" ]*} => sub {
970                 out dp => 0,
971                         'alias rcon2irc_eval "$*"',
972                         'log_dest_udp',
973                         'sv_logscores_console 0',
974                         'sv_logscores_bots 1',
975                         'sv_eventlog 1',
976                         'sv_eventlog_console 1',
977                         'alias rcon2irc_say_as "set say_as_restorenick \"$sv_adminnick\"; sv_adminnick \"$1^3\"; say \"^7$2\"; rcon2irc_say_as_restore"',
978                         'alias rcon2irc_say_as_restore "set sv_adminnick \"$say_as_restorenick\""',
979                         'alias rcon2irc_quit "echo \"quitting rcon2irc $1: log_dest_udp is $log_dest_udp\""'; # note: \\\\\\" ->perl \\\" ->console \"
980                 return 0;
981         } ],
982
983         # detect missing entry in log_dest_udp and fix it
984         [ dp => q{"log_dest_udp" is "([^"]*)" \["[^"]*"\]} => sub {
985                 my ($dest) = @_;
986                 my @dests = split ' ', $dest;
987                 return 0 if grep { $_ eq $config{dp_listen} } @dests;
988                 out dp => 0, 'log_dest_udp "' . join(" ", @dests, $config{dp_listen}) . '"';
989                 return 0;
990         } ],
991
992         # retrieve list of banned hosts
993         [ dp => q{#(\d+): (\S+) is still banned for (\S+) seconds} => sub {
994                 return 0 unless $store{status_waiting} < 0;
995                 my ($id, $ip, $time) = @_;
996                 $store{bans_new} = [] if $id == 0;
997                 $store{bans_new}[$id] = { ip => $ip, 'time' => $time };
998                 return 0;
999         } ],
1000
1001         # retrieve hostname from status replies
1002         [ dp => q{host:     (.*)} => sub {
1003                 return 0 unless $store{status_waiting} < 0;
1004                 my ($name) = @_;
1005                 $store{dp_hostname} = $name;
1006                 $store{bans} = $store{bans_new};
1007                 return 0;
1008         } ],
1009
1010         # retrieve version from status replies
1011         [ dp => q{version:  (.*)} => sub {
1012                 return 0 unless $store{status_waiting} < 0;
1013                 my ($version) = @_;
1014                 $store{dp_version} = $version;
1015                 return 0;
1016         } ],
1017
1018         # retrieve player names
1019         [ dp => q{players:  (\d+) active \((\d+) max\)} => sub {
1020                 return 0 unless $store{status_waiting} < 0;
1021                 my ($active, $max) = @_;
1022                 my $full = ($active >= $max);
1023                 $store{slots_max} = $max;
1024                 $store{slots_active} = $active;
1025                 $store{status_waiting} = $active;
1026                 $store{playerslots_active_new} = [];
1027                 if($store{status_waiting} == 0)
1028                 {
1029                         $store{playerslots_active} = $store{playerslots_active_new};
1030                 }
1031                 if($full != ($store{slots_full} || 0))
1032                 {
1033                         $store{slots_full} = $full;
1034                         return 0
1035                                 if $store{lms_blocked};
1036                         if($full)
1037                         {
1038                                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION is full!\001";
1039                         }
1040                         else
1041                         {
1042                                 my $slotsstr = nex_slotsstring();
1043                                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION can be joined again$slotsstr!\001";
1044                         }
1045                 }
1046                 return 0;
1047         } ],
1048
1049         # retrieve player names
1050         [ dp => q{\^\d(\S+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(-?\d+)\s+\#(\d+)\s+\^\d(.*)} => sub {
1051                 return 0 unless $store{status_waiting} > 0;
1052                 my ($ip, $pl, $ping, $time, $frags, $no, $name) = ($1, $2, $3, $4, $5, $6, $7);
1053                 $store{"playerslot_$no"} = { ip => $ip, pl => $pl, ping => $ping, 'time' => $time, frags => $frags, no => $no, name => $name };
1054                 push @{$store{playerslots_active_new}}, $no;
1055                 if(--$store{status_waiting} == 0)
1056                 {
1057                         $store{playerslots_active} = $store{playerslots_active_new};
1058                 }
1059                 return 0;
1060         } ],
1061
1062         # IRC admin commands
1063         [ irc => q{:(([^! ]*)![^ ]*) (?i:PRIVMSG) [^&#%]\S* :(.*)} => sub {
1064                 return 0 unless $config{irc_admin_password} ne '';
1065
1066                 my ($hostmask, $nick, $command) = @_;
1067                 my $dpnick = color_dpfix $nick;
1068
1069                 if($command eq "login $config{irc_admin_password}")
1070                 {
1071                         $store{logins}{$hostmask} = time() + $config{irc_admin_timeout};
1072                         out irc => 0, "PRIVMSG $nick :my wish is your command";
1073                         return -1;
1074                 }
1075
1076                 if($command =~ /^login /)
1077                 {
1078                         out irc => 0, "PRIVMSG $nick :invalid password";
1079                         return -1;
1080                 }
1081
1082                 if(($store{logins}{$hostmask} || 0) < time())
1083                 {
1084                         out irc => 0, "PRIVMSG $nick :authentication required";
1085                         return -1;
1086                 }
1087
1088                 if($command =~ /^status(?: (.*))?$/)
1089                 {
1090                         my ($match) = $1;
1091                         my $found = 0;
1092                         my $foundany = 0;
1093                         for my $slot(@{$store{playerslots_active} || []})
1094                         {
1095                                 my $s = $store{"playerslot_$slot"};
1096                                 next unless $s;
1097                                 if(not defined $match or index(color_dp2none($s->{name}), $match) >= 0)
1098                                 {
1099                                         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};
1100                                         ++$found;
1101                                 }
1102                                 ++$foundany;
1103                         }
1104                         if(!$found)
1105                         {
1106                                 if(!$foundany)
1107                                 {
1108                                         out irc => 0, "PRIVMSG $nick :the server is empty";
1109                                 }
1110                                 else
1111                                 {
1112                                         out irc => 0, "PRIVMSG $nick :no nicknames match";
1113                                 }
1114                         }
1115                         return 0;
1116                 }
1117
1118                 if($command =~ /^kick # (\d+) (.*)$/)
1119                 {
1120                         my ($id, $reason) = ($1, $2);
1121                         my $dpreason = color_irc2dp $reason;
1122                         $dpreason =~ s/^(~?)(.*)/$1irc $dpnick: $2/g;
1123                         $dpreason =~ s/(["\\])/\\$1/g;
1124                         out dp => 0, "kick # $id $dpreason";
1125                         my $slotnik = "playerslot_$id";
1126                         out irc => 0, "PRIVMSG $nick :kicked #$id (@{[color_dp2irc $store{$slotnik}{name}]} @ $store{$slotnik}{ip}) ($reason)";
1127                         return 0;
1128                 }
1129
1130                 if($command =~ /^kickban # (\d+) (\d+) (\d+) (.*)$/)
1131                 {
1132                         my ($id, $bantime, $mask, $reason) = ($1, $2, $3, $4);
1133                         my $dpreason = color_irc2dp $reason;
1134                         $dpreason =~ s/^(~?)(.*)/$1irc $dpnick: $2/g;
1135                         $dpreason =~ s/(["\\])/\\$1/g;
1136                         out dp => 0, "kickban # $id $bantime $mask $dpreason";
1137                         my $slotnik = "playerslot_$id";
1138                         out irc => 0, "PRIVMSG $nick :kickbanned #$id (@{[color_dp2irc $store{$slotnik}{name}]} @ $store{$slotnik}{ip}), netmask $mask, for $bantime seconds ($reason)";
1139                         return 0;
1140                 }
1141
1142                 if($command eq "bans")
1143                 {
1144                         my $banlist =
1145                                 join ", ",
1146                                 map { "$_ ($store{bans}[$_]{ip}, $store{bans}[$_]{time}s)" }
1147                                 0..@{$store{bans} || []}-1;
1148                         $banlist = "no bans"
1149                                 if $banlist eq "";
1150                         out irc => 0, "PRIVMSG $nick :$banlist";
1151                         return 0;
1152                 }
1153
1154                 if($command =~ /^unban (\d+)$/)
1155                 {
1156                         my ($id) = ($1);
1157                         out dp => 0, "unban $id";
1158                         out irc => 0, "PRIVMSG $nick :removed ban $id ($store{bans}[$id]{ip})";
1159                         return 0;
1160                 }
1161
1162                 out irc => 0, "PRIVMSG $nick :unknown command (supported: status [substring], kick # id reason, kickban # id bantime mask reason, bans, unban banid)";
1163
1164                 return -1;
1165         } ],
1166
1167         # LMS: detect "no more lives" message
1168         [ dp => q{\^4.*\^4 has no more lives left} => sub {
1169                 if(!$store{lms_blocked})
1170                 {
1171                         $store{lms_blocked} = 1;
1172                         if(!$store{slots_full})
1173                         {
1174                                 schedule sub {
1175                                         if($store{lms_blocked})
1176                                         {
1177                                                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION can't be joined until next round (a player has no more lives left)\001";
1178                                         }
1179                                 } => 1;
1180                         }
1181                 }
1182         } ],
1183
1184         # detect IRC errors and reconnect
1185         [ irc => q{ERROR .*} => \&irc_error ],
1186         [ system => q{error irc} => \&irc_error ],
1187
1188         # IRC nick in use
1189         [ irc => q{:[^ ]* 433 .*} => sub {
1190                 return irc_joinstage(433);
1191         } ],
1192
1193         # IRC welcome
1194         [ irc => q{:[^ ]* 001 .*} => sub {
1195                 $store{irc_seen_welcome} = 1;
1196                 $store{irc_nick} = $store{irc_nick_requested};
1197                 return irc_joinstage(0);
1198         } ],
1199
1200         # IRC my nickname changed
1201         [ irc => q{:(?i:(??{$store{irc_nick}}))![^ ]* (?i:NICK) :(.*)} => sub {
1202                 my ($n) = @_;
1203                 $store{irc_nick} = $n;
1204                 return irc_joinstage(0);
1205         } ],
1206
1207         # Quakenet: challenge from Q
1208         [ irc => q{(??{$config{irc_quakenet_challengeprefix}}) (.*)} => sub {
1209                 $store{irc_quakenet_challenge} = $1;
1210                 return irc_joinstage(0);
1211         } ],
1212
1213         # shut down everything on SIGINT
1214         [ system => q{quit (.*)} => sub {
1215                 my ($cause) = @_;
1216                 out irc => 1, "QUIT :$cause";
1217                 $store{quitcookie} = int rand 1000000000;
1218                 out dp => 0, "rcon2irc_quit $store{quitcookie}";
1219         } ],
1220
1221         # remove myself from the log destinations and exit everything
1222         [ dp => q{quitting rcon2irc (??{$store{quitcookie}}): log_dest_udp is (.*) *} => sub {
1223                 my ($dest) = @_;
1224                 my @dests = grep { $_ ne $config{dp_listen} } split ' ', $dest;
1225                 out dp => 0, 'log_dest_udp "' . join(" ", @dests) . '"';
1226                 exit 0;
1227                 return 0;
1228         } ],
1229
1230         # IRC PING
1231         [ irc => q{PING (.*)} => sub {
1232                 my ($data) = @_;
1233                 out irc => 1, "PONG $data";
1234                 return 1;
1235         } ],
1236
1237         # IRC PONG
1238         [ irc => q{:[^ ]* PONG .* :(.*)} => sub {
1239                 my ($data) = @_;
1240                 return 0
1241                         if not defined $store{irc_pingtime};
1242                 return 0
1243                         if $data ne $store{irc_pingtime};
1244                 print "* measured IRC line delay: @{[time() - $store{irc_pingtime}]}\n";
1245                 undef $store{irc_pingtime};
1246                 return 0;
1247         } ],
1248
1249         # detect channel join message and note hostname length to get the maximum allowed line length
1250         [ irc => q{(:(?i:(??{$store{irc_nick}}))![^ ]* )(?i:JOIN) :(?i:(??{$config{irc_channel}}))} => sub {
1251                 $store{irc_maxlen} = 510 - length($1);
1252                 $store{irc_joined_channel} = 1;
1253                 print "* detected maximum line length for channel messages: $store{irc_maxlen}\n";
1254                 return 0;
1255         } ],
1256
1257         # chat: Nexuiz server -> IRC channel
1258         [ dp => q{\001(.*?)\^7: (.*)} => sub {
1259                 my ($nick, $message) = map { color_dp2irc $_ } @_;
1260                 out irc => 0, "PRIVMSG $config{irc_channel} :<$nick\017> $message";
1261                 return 0;
1262         } ],
1263
1264         # chat: Nexuiz server -> IRC channel, nick set
1265         [ dp => q{:join:(\d+):(\d+):([^:]*):(.*)} => sub {
1266                 my ($id, $slot, $ip, $nick) = @_;
1267                 $nick = color_dp2irc $nick;
1268                 $store{"playernick_byid_$id"} = $nick;
1269                 $store{"playerip_byid_$id"} = $ip;
1270                 $store{"playerslot_byid_$id"} = $slot;
1271                 $store{"playerid_byslot_$slot"} = $id;
1272                 return 0;
1273         } ],
1274
1275         # chat: Nexuiz server -> IRC channel, nick change/set
1276         [ dp => q{:name:(\d+):(.*)} => sub {
1277                 my ($id, $nick) = @_;
1278                 $nick = color_dp2irc $nick;
1279                 my $oldnick = $store{"playernick_byid_$id"};
1280                 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 is now known as $nick";
1281                 $store{"playernick_byid_$id"} = $nick;
1282                 return 0;
1283         } ],
1284
1285         # chat: Nexuiz server -> IRC channel, vote call
1286         [ dp => q{:vote:vcall:(\d+):(.*)} => sub {
1287                 my ($id, $command) = @_;
1288                 $command = color_dp2irc $command;
1289                 my $oldnick = $id ? $store{"playernick_byid_$id"} : "(console)";
1290                 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 calls a vote for \"$command\017\"";
1291                 return 0;
1292         } ],
1293
1294         # chat: Nexuiz server -> IRC channel, vote stop
1295         [ dp => q{:vote:vstop:(\d+)} => sub {
1296                 my ($id) = @_;
1297                 my $oldnick = $id ? $store{"playernick_byid_$id"} : "(console)";
1298                 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 stopped the vote";
1299                 return 0;
1300         } ],
1301
1302         # chat: Nexuiz server -> IRC channel, master login
1303         [ dp => q{:vote:vlogin:(\d+)} => sub {
1304                 my ($id) = @_;
1305                 my $oldnick = $id ? $store{"playernick_byid_$id"} : "(console)";
1306                 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 logged in as master";
1307                 return 0;
1308         } ],
1309
1310         # chat: Nexuiz server -> IRC channel, master do
1311         [ dp => q{:vote:vdo:(\d+):(.*)} => sub {
1312                 my ($id, $command) = @_;
1313                 $command = color_dp2irc $command;
1314                 my $oldnick = $id ? $store{"playernick_byid_$id"} : "(console)";
1315                 out irc => 0, "PRIVMSG $config{irc_channel} :* $oldnick\017 used his master status to do \"$command\017\"";
1316                 return 0;
1317         } ],
1318
1319         # chat: Nexuiz server -> IRC channel, result
1320         [ dp => q{:vote:v(yes|no|timeout):(\d+):(\d+):(\d+):(\d+):(-?\d+)} => sub {
1321                 my ($result, $yes, $no, $abstain, $not, $min) = @_;
1322                 my $spam = "$yes:$no" . (($min >= 0) ? " ($min needed)" : "") . ", $abstain didn't care, $not didn't vote";
1323                 out irc => 0, "PRIVMSG $config{irc_channel} :* the vote ended with $result: $spam";
1324                 return 0;
1325         } ],
1326
1327         # chat: IRC channel -> Nexuiz server
1328         [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$config{irc_channel}})) :(?i:(??{$store{irc_nick}}))(?: |: ?|, ?)(.*)} => sub {
1329                 my ($nick, $message) = @_;
1330                 $nick = color_dpfix $nick;
1331                         # allow the nickname to contain colors in DP format! Therefore, NO color_irc2dp on the nickname!
1332                 $message = color_irc2dp $message;
1333                 $message =~ s/(["\\])/\\$1/g;
1334                 out dp => 0, "rcon2irc_say_as \"$nick on IRC\" \"$message\"";
1335                 return 0;
1336         } ],
1337
1338         (
1339                 length $config{irc_trigger}
1340                         ?
1341                                 [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$config{irc_channel}})) :(?i:(??{$config{irc_trigger}}))(?: |: ?|, ?)(.*)} => sub {
1342                                         my ($nick, $message) = @_;
1343                                         $nick = color_dpfix $nick;
1344                                                 # allow the nickname to contain colors in DP format! Therefore, NO color_irc2dp on the nickname!
1345                                         $message = color_irc2dp $message;
1346                                         $message =~ s/(["\\])/\\$1/g;
1347                                         out dp => 0, "rcon2irc_say_as \"$nick on IRC\" \"$message\"";
1348                                         return 0;
1349                                 } ]
1350                         :
1351                                 ()
1352         ),
1353
1354         # irc: CTCP VERSION reply
1355         [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$store{irc_nick}})) :\001VERSION( .*)?\001} => sub {
1356                 my ($nick) = @_;
1357                 my $ver = $store{dp_version} or return 0;
1358                 $ver .= ", rcon2irc $VERSION";
1359                 out irc => 0, "NOTICE $nick :\001VERSION $ver\001";
1360         } ],
1361
1362         # on game start, notify the channel
1363         [ dp => q{:gamestart:(.*):[0-9.]*} => sub {
1364                 my ($map) = @_;
1365                 $store{playing} = 1;
1366                 $store{map} = $map;
1367                 $store{map_starttime} = time();
1368                 my $slotsstr = nex_slotsstring();
1369                 out irc => 0, "PRIVMSG $config{irc_channel} :\00304" . $map . "\017 has begun$slotsstr";
1370                 delete $store{lms_blocked};
1371                 return 0;
1372         } ],
1373
1374         # on game over, clear the current map
1375         [ dp => q{:gameover} => sub {
1376                 $store{playing} = 0;
1377                 return 0;
1378         } ],
1379
1380         # scores: Nexuiz server -> IRC channel (start)
1381         [ dp => q{:scores:(.*):(\d+)} => sub {
1382                 my ($map, $time) = @_;
1383                 $store{scores} = {};
1384                 $store{scores}{map} = $map;
1385                 $store{scores}{time} = $time;
1386                 $store{scores}{players} = [];
1387                 delete $store{lms_blocked};
1388                 return 0;
1389         } ],
1390
1391         # scores: Nexuiz server -> IRC channel, legacy format
1392         [ dp => q{:player:(-?\d+):(\d+):(\d+):(\d+):(\d+):(.*)} => sub {
1393                 my ($frags, $deaths, $time, $team, $id, $name) = @_;
1394                 return if not exists $store{scores};
1395                 push @{$store{scores}{players}}, [$frags, $team, $name]
1396                         unless $frags <= -666; # no spectators
1397                 return 0;
1398         } ],
1399
1400         # scores: Nexuiz server -> IRC channel (CTF), legacy format
1401         [ dp => q{:teamscores:(\d+:-?\d*(?::\d+:-?\d*)*)} => sub {
1402                 my ($teams) = @_;
1403                 return if not exists $store{scores};
1404                 $store{scores}{teams} = {split /:/, $teams};
1405                 return 0;
1406         } ],
1407
1408         # scores: Nexuiz server -> IRC channel, new format
1409         [ dp => q{:player:see-labels:(-?\d+)[-0-9,]*:(\d+):(\d+):(\d+):(.*)} => sub {
1410                 my ($frags, $time, $team, $id, $name) = @_;
1411                 return if not exists $store{scores};
1412                 push @{$store{scores}{players}}, [$frags, $team, $name];
1413                 return 0;
1414         } ],
1415
1416         # scores: Nexuiz server -> IRC channel (CTF), new format
1417         [ dp => q{:teamscores:see-labels:(-?\d+)[-0-9,]*:(\d+)} => sub {
1418                 my ($frags, $team) = @_;
1419                 return if not exists $store{scores};
1420                 $store{scores}{teams}{$team} = $frags;
1421                 return 0;
1422         } ],
1423
1424         # scores: Nexuiz server -> IRC channel
1425         [ dp => q{:end} => sub {
1426                 return if not exists $store{scores};
1427                 my $s = $store{scores};
1428                 delete $store{scores};
1429                 my $teams_matter = nex_is_teamplay($s->{map});
1430
1431                 my @t = ();
1432                 my @p = ();
1433
1434                 if($teams_matter)
1435                 {
1436                         # put players into teams
1437                         my %t = ();
1438                         for(@{$s->{players}})
1439                         {
1440                                 my $thisteam = ($t{$_->[1]} ||= {score => 0, team => $_->[1], players => []});
1441                                 push @{$thisteam->{players}}, [$_->[0], $_->[1], $_->[2]];
1442                                 if($s->{teams})
1443                                 {
1444                                         $thisteam->{score} = $s->{teams}{$_->[1]};
1445                                 }
1446                                 else
1447                                 {
1448                                         $thisteam->{score} += $_->[0];
1449                                 }
1450                         }
1451
1452                         # sort by team score
1453                         @t = sort { $b->{score} <=> $a->{score} } values %t;
1454
1455                         # sort by player score
1456                         @p = ();
1457                         for(@t)
1458                         {
1459                                 @{$_->{players}} = sort { $b->[0] <=> $a->[0] } @{$_->{players}};
1460                                 push @p, @{$_->{players}};
1461                         }
1462                 }
1463                 else
1464                 {
1465                         @p = sort { $b->[0] <=> $a->[0] } @{$s->{players}};
1466                 }
1467
1468                 # no display for empty server
1469                 return 0
1470                         if !@p;
1471
1472                 # make message fit somehow
1473                 for my $maxnamelen(reverse 3..64)
1474                 {
1475                         my $scores_string = "PRIVMSG $config{irc_channel} :\00304" . $s->{map} . "\017 ended:";
1476                         if($teams_matter)
1477                         {
1478                                 my $sep = ' ';
1479                                 for(@t)
1480                                 {
1481                                         $scores_string .= $sep . sprintf "\003%02d\%d\017", $color_team2irc_table{$_->{team}}, $_->{score};
1482                                         $sep = ':';
1483                                 }
1484                         }
1485                         my $sep = '';
1486                         for(@p)
1487                         {
1488                                 my ($frags, $team, $name) = @$_;
1489                                 $name = color_dpfix substr($name, 0, $maxnamelen);
1490                                 if($teams_matter)
1491                                 {
1492                                         $name = "\003" . $color_team2irc_table{$team} . " " . color_dp2none $name;
1493                                 }
1494                                 else
1495                                 {
1496                                         $name = " " . color_dp2irc $name;
1497                                 }
1498                                 $scores_string .= "$sep$name\017 $frags";
1499                                 $sep = ',';
1500                         }
1501                         if(length($scores_string) <= ($store{irc_maxlen} || 256))
1502                         {
1503                                 out irc => 0, $scores_string;
1504                                 return 0;
1505                         }
1506                 }
1507                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION would have LIKED to put the scores here, but they wouldn't fit :(\001";
1508                 return 0;
1509         } ],
1510
1511         # complain when system load gets too high
1512         [ dp => q{timing:   (([0-9.]*)% CPU, ([0-9.]*)% lost, offset avg ([0-9.]*)ms, max ([0-9.]*)ms, sdev ([0-9.]*)ms)} => sub {
1513                 my ($all, $cpu, $lost, $avg, $max, $sdev) = @_;
1514                 return 0 # don't complain when just on the voting screen
1515                         if !$store{playing};
1516                 return 0 # don't complain if it was less than 0.5%
1517                         if $lost < 0.5;
1518                 return 0 # don't complain if nobody is looking
1519                         if $store{slots_active} == 0;
1520                 return 0 # don't complain in the first two minutes
1521                         if time() - $store{map_starttime} < 120;
1522                 return 0 # don't complain if it was already at least half as bad in this round
1523                         if $store{map_starttime} == $store{timingerror_map_starttime} and $lost <= 2 * $store{timingerror_lost};
1524                 $store{timingerror_map_starttime} = $store{map_starttime};
1525                 $store{timingerror_lost} = $lost;
1526                 out dp => 0, 'rcon2irc_say_as server "There are currently some severe system load problems. The admins have been notified."';
1527                 out irc => 1, "PRIVMSG $config{irc_channel} :\001ACTION has big trouble on $store{map} after @{[int(time() - $store{map_starttime})]}s: $all\001";
1528                 #out irc => 1, "PRIVMSG OpBaI :\001ACTION has big trouble on $store{map} after @{[int(time() - $store{map_starttime})]}s: $all\001";
1529                 return 0;
1530         } ],
1531 );
1532
1533
1534
1535 # Load plugins and add them to the handler list in the front.
1536 for my $p(split ' ', $config{plugins})
1537 {
1538         my @h = eval { do $p; }
1539                 or die "Invalid plugin $p: $@";
1540         for(reverse @h)
1541         {
1542                 ref $_ eq 'ARRAY' or die "Invalid plugin $p: did not return a list of arrays";
1543                 @$_ == 3 or die "Invalid plugin $p: did not return a list of three-element arrays";
1544                 !ref $_->[0] && !ref $_->[1] && ref $_->[2] eq 'CODE' or die "Invalid plugin $p: did not return a list of string-string-sub arrays";
1545                 unshift @handlers, $_;
1546         }
1547 }
1548
1549
1550
1551 # verify that the server is up by letting it echo back a string that causes
1552 # re-initialization of the required aliases
1553 out dp => 0, 'echo "Unknown command \"rcon2irc_eval\""'; # assume the server has been restarted
1554
1555
1556
1557 # regularily, query the server status and if it still is connected to us using
1558 # the log_dest_udp feature. If not, we will detect the response to this rcon
1559 # command and re-initialize the server's connection to us (either by log_dest_udp
1560 # not containing our own IP:port, or by rcon2irc_eval not being a defined command).
1561 schedule sub {
1562         my ($timer) = @_;
1563         out dp => 0, 'sv_cmd bans', 'status 1', 'log_dest_udp', 'rcon2irc_eval set dummy 1';
1564         $store{status_waiting} = -1;
1565         schedule $timer => (exists $store{dp_hostname} ? $config{dp_status_delay} : 1);;
1566 } => 1;
1567
1568
1569
1570 # Continue with connecting to IRC as soon as we get our first status reply from
1571 # the DP server (which contains the server's hostname that we'll use as
1572 # realname for IRC).
1573 schedule sub {
1574         my ($timer) = @_;
1575
1576         # log on to IRC when needed
1577         if(exists $store{dp_hostname} && !exists $store{irc_logged_in})
1578         {
1579                 $store{irc_nick_requested} = $config{irc_nick};
1580                 out irc => 1, "NICK $config{irc_nick}", "USER $config{irc_user} localhost localhost :$store{dp_hostname}";
1581                 $store{irc_logged_in} = 1;
1582                 undef $store{irc_maxlen};
1583                 undef $store{irc_pingtime};
1584         }
1585
1586         schedule $timer => 1;;
1587 } => 1;
1588
1589
1590
1591 # Regularily ping the IRC server to detect if the connection is down. If it is,
1592 # schedule an IRC error that will cause reconnection later.
1593 schedule sub {
1594         my ($timer) = @_;
1595
1596         if($store{irc_logged_in})
1597         {
1598                 if(defined $store{irc_pingtime})
1599                 {
1600                         # IRC connection apparently broke
1601                         # so... KILL IT WITH FIRE
1602                         $channels{system}->send("error irc", 0);
1603                 }
1604                 else
1605                 {
1606                         # everything is fine, send a new ping
1607                         $store{irc_pingtime} = time();
1608                         out irc => 1, "PING $store{irc_pingtime}";
1609                 }
1610         }
1611
1612         schedule $timer => $config{irc_ping_delay};;
1613 } => 1;
1614
1615
1616
1617 # Main loop.
1618 for(;;)
1619 {
1620         # Build up an IO::Select object for all our channels.
1621         my $s = IO::Select->new();
1622         for my $chan(values %channels)
1623         {
1624                 $s->add($_) for $chan->fds();
1625         }
1626
1627         # wait for something to happen on our sockets, or wait 2 seconds without anything happening there
1628         $s->can_read(2);
1629         my @errors = $s->has_exception(0);
1630
1631         # on every channel, look for incoming messages
1632         CHANNEL:
1633         for my $chanstr(keys %channels)
1634         {
1635                 my $chan = $channels{$chanstr};
1636                 my @chanfds = $chan->fds();
1637
1638                 for my $chanfd(@chanfds)
1639                 {
1640                         if(grep { $_ == $chanfd } @errors)
1641                         {
1642                                 # STOP! This channel errored!
1643                                 $channels{system}->send("error $chanstr", 0);
1644                                 next CHANNEL;
1645                         }
1646                 }
1647
1648                 eval
1649                 {
1650                         for my $line($chan->recv())
1651                         {
1652                                 # found one! Check if it matches the regular expression of one of
1653                                 # our handlers...
1654                                 my $handled = 0;
1655                                 my $private = 0;
1656                                 for my $h(@handlers)
1657                                 {
1658                                         my ($chanstr_wanted, $re, $sub) = @$h;
1659                                         next
1660                                                 if $chanstr_wanted ne $chanstr;
1661                                         use re 'eval';
1662                                         my @matches = ($line =~ /^$re$/s);
1663                                         no re 'eval';
1664                                         next
1665                                                 unless @matches;
1666                                         # and if it is a match, handle it.
1667                                         ++$handled;
1668                                         my $result = $sub->(@matches);
1669                                         $private = 1
1670                                                 if $result < 0;
1671                                         last
1672                                                 if $result;
1673                                 }
1674                                 # print the message, together with info on whether it has been handled or not
1675                                 if($private)
1676                                 {
1677                                         print "           $chanstr >> (private)\n";
1678                                 }
1679                                 elsif($handled)
1680                                 {
1681                                         print "           $chanstr >> $line\n";
1682                                 }
1683                                 else
1684                                 {
1685                                         print "unhandled: $chanstr >> $line\n";
1686                                 }
1687                         }
1688                         1;
1689                 } or do {
1690                         if($@ eq "read error\n")
1691                         {
1692                                 $channels{system}->send("error $chanstr", 0);
1693                                 next CHANNEL;
1694                         }
1695                         else
1696                         {
1697                                 # re-throw
1698                                 die $@;
1699                         }
1700                 };
1701         }
1702
1703         # handle scheduled tasks...
1704         my @t = @tasks;
1705         my $t = time();
1706         # by emptying the list of tasks...
1707         @tasks = ();
1708         for(@t)
1709         {
1710                 my ($time, $sub) = @$_;
1711                 if($t >= $time)
1712                 {
1713                         # calling them if they are schedled for the "past"...
1714                         $sub->($sub);
1715                 }
1716                 else
1717                 {
1718                         # or re-adding them to the task list if they still are scheduled for the "future"
1719                         push @tasks, [$time, $sub];
1720                 }
1721         }
1722 }