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