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