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