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