]> icculus.org git repositories - divverent/nexuiz.git/blob - Docs/server/rcon2irc/rcon2irc.pl
+//g_maplist_check_waypoints in server.cfg; fix small bug in rcon script displaying...
[divverent/nexuiz.git] / Docs / 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 # Interfaces:
29 #   Connection:
30 #     $conn->sockname() returns a connection type specific representation
31 #       string of the local address, or undef if not applicable.
32 #     $conn->send("string") sends something over the connection.
33 #     $conn->recv() receives a string from the connection, or returns "" if no
34 #       data is available.
35 #     $conn->fds() returns all file descriptors used by the connection, so one
36 #       can use select() on them.
37 #   Channel:
38 #     Usually wraps around a connection and implements a command based
39 #     structure over it. It usually is constructed using new
40 #     ChannelType($connection, someparameters...)
41 #     @cmds = $chan->join_commands(@cmds) joins multiple commands to a single
42 #       command string if the protocol supports it, or does nothing and leaves
43 #       @cmds unchanged if the protocol does not support that usage (this is
44 #       meant to save send() invocations).
45 #     $chan->send($command, $nothrottle) sends a command over the channel. If
46 #       $nothrottle is sent, the command must not be left out even if the channel
47 #       is saturated (for example, because of IRC's flood control mechanism).
48 #     $chan->quote($str) returns a string in a quoted form so it can safely be
49 #       inserted as a substring into a command, or returns $str as is if not
50 #       applicable. It is assumed that the result of the quote method is used
51 #       as part of a quoted string, if the protocol supports that.
52 #     $chan->recv() returns a list of received commands from the channel, or
53 #       the empty list if none are available.
54 #     $conn->fds() returns all file descriptors used by the channel's
55 #       connections, so one can use select() on them.
56
57
58
59
60
61
62
63 # Socket connection.
64 # Represents a connection over a socket.
65 # Mainly used to wrap a channel around it for, in this case, line based or rcon-like operation.
66 package Connection::Socket;
67 use strict;
68 use warnings;
69 use IO::Socket::INET;
70 use IO::Handle;
71
72 # Constructor:
73 #   my $conn = new Connection::Socket(tcp => "localaddress" => "remoteaddress" => 6667);
74 # If the remote address does not contain a port number, the numeric port is
75 # used (it serves as a default port).
76 sub new($$)
77 {
78         my ($class, $proto, $local, $remote, $defaultport) = @_;
79         my $sock = IO::Socket::INET->new(
80                 Proto => $proto,
81                 (length($local) ? (LocalAddr => $local) : ()),
82                 PeerAddr => $remote,
83                 PeerPort => $defaultport
84         ) or die "socket $proto/$local/$remote: $!";
85         $sock->blocking(0);
86         my $you = {
87                 # Mortal fool! Release me from this wretched tomb! I must be set free
88                 # or I will haunt you forever! I will hide your keys beneath the
89                 # cushions of your upholstered furniture... and NEVERMORE will you be
90                 # able to find socks that match!
91                 sock => $sock,
92                 # My demonic powers have made me OMNIPOTENT! Bwahahahahahahaha!
93         };
94         return
95                 bless $you, 'Connection::Socket';
96 }
97
98 # $sock->sockname() returns the local address of the socket.
99 sub sockname($)
100 {
101         my ($self) = @_;
102         my ($port, $addr) = sockaddr_in $self->{sock}->sockname();
103         return "@{[inet_ntoa $addr]}:$port";
104 }
105
106 # $sock->send($data) sends some data over the socket; on success, 1 is returned.
107 sub send($$)
108 {
109         my ($self, $data) = @_;
110         return 1
111                 if not length $data;
112         if(not eval { $self->{sock}->send($data); })
113         {
114                 warn "$@";
115                 return 0;
116         }
117         return 1;
118 }
119
120 # $sock->recv() receives as much as possible from the socket (or at most 32k). Returns "" if no data is available.
121 sub recv($)
122 {
123         my ($self) = @_;
124         my $data = "";
125         $self->{sock}->recv($data, 32768, 0);
126         return $data;
127 }
128
129 # $sock->fds() returns the socket file descriptor.
130 sub fds($)
131 {
132         my ($self) = @_;
133         return fileno $self->{sock};
134 }
135
136
137
138
139
140
141
142 # Line-based buffered connectionless FIFO channel.
143 # Whatever is sent to it using send() is echoed back when using recv().
144 package Channel::FIFO;
145 use strict;
146 use warnings;
147
148 # Constructor:
149 #   my $chan = new Channel::FIFO();
150 sub new($)
151 {
152         my ($class) = @_;
153         my $you = {
154                 buffer => []
155         };
156         return
157                 bless $you, 'Channel::FIFO';
158 }
159
160 sub join_commands($@)
161 {
162         my ($self, @data) = @_;
163         return @data;
164 }
165
166 sub send($$$)
167 {
168         my ($self, $line, $nothrottle) = @_;
169         push @{$self->{buffer}}, $line;
170 }
171
172 sub quote($$)
173 {
174         my ($self, $data) = @_;
175         return $data;
176 }
177
178 sub recv($)
179 {
180         my ($self) = @_;
181         my $r = $self->{buffer};
182         $self->{buffer} = [];
183         return @$r;
184 }
185
186 sub fds($)
187 {
188         my ($self) = @_;
189         return ();
190 }
191
192
193
194
195
196
197
198 # QW rcon protocol channel.
199 # Wraps around a UDP based Connection and sends commands as rcon commands as
200 # well as receives rcon replies. The quote and join_commands methods are using
201 # DarkPlaces engine specific rcon protocol extensions.
202 package Channel::QW;
203 use strict;
204 use warnings;
205
206 # Constructor:
207 #   my $chan = new Channel::QW($connection, "password");
208 sub new($$)
209 {
210         my ($class, $conn, $password) = @_;
211         my $you = {
212                 connector => $conn,
213                 password => $password,
214                 recvbuf => "",
215         };
216         return
217                 bless $you, 'Channel::QW';
218 }
219
220 # Note: multiple commands in one rcon packet is a DarkPlaces extension.
221 sub join_commands($@)
222 {
223         my ($self, @data) = @_;
224         return join "\0", @data;
225 }
226
227 sub send($$$)
228 {
229         my ($self, $line, $nothrottle) = @_;
230         return $self->{connector}->send("\377\377\377\377rcon $self->{password} $line");
231 }
232
233 # Note: backslash and quotation mark escaping is a DarkPlaces extension.
234 sub quote($$)
235 {
236         my ($self, $data) = @_;
237         $data =~ s/[\000-\037]//g;
238         $data =~ s/([\\"])/\\$1/g;
239         $data =~ s/\$/\$\$/g;
240         return $data;
241 }
242
243 sub recv($)
244 {
245         my ($self) = @_;
246         for(;;)
247         {
248                 length(my $s = $self->{connector}->recv())
249                         or last;
250                 next
251                         if $s !~ /^\377\377\377\377n(.*)$/s;
252                 $self->{recvbuf} .= $1;
253         }
254         my @out = ();
255         while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
256         {
257                 push @out, $1;
258         }
259         return @out;
260 }
261
262 sub fds($)
263 {
264         my ($self) = @_;
265         return $self->{connector}->fds();
266 }
267
268
269
270
271
272
273
274 # Line based protocol channel.
275 # Wraps around a TCP based Connection and sends commands as text lines
276 # (separated by CRLF). When reading responses from the Connection, any type of
277 # line ending is accepted.
278 # A flood control mechanism is implemented.
279 package Channel::Line;
280 use strict;
281 use warnings;
282 use Time::HiRes qw/time/;
283
284 # Constructor:
285 #   my $chan = new Channel::Line($connection);
286 sub new($$)
287 {
288         my ($class, $conn) = @_;
289         my $you = {
290                 connector => $conn,
291                 recvbuf => "",
292                 capacity => undef,
293                 linepersec => undef,
294                 maxlines => undef,
295                 lastsend => time()
296         };
297         return 
298                 bless $you, 'Channel::Line';
299 }
300
301 sub join_commands($@)
302 {
303         my ($self, @data) = @_;
304         return @data;
305 }
306
307 # Sets new flood control parameters:
308 #   $chan->throttle(maximum lines per second, maximum burst length allowed to
309 #     exceed the lines per second limit);
310 #   RFC 1459 describes these parameters to be 0.5 and 5 for the IRC protocol.
311 #   If the $nothrottle flag is set while sending, the line is sent anyway even
312 #   if flooding would take place.
313 sub throttle($$$)
314 {
315         my ($self, $linepersec, $maxlines) = @_;
316         $self->{linepersec} = $linepersec;
317         $self->{maxlines} = $maxlines;
318         $self->{capacity} = $maxlines;
319 }
320
321 sub send($$$)
322 {
323         my ($self, $line, $nothrottle) = @_;
324         my $t = time();
325         if(defined $self->{capacity})
326         {
327                 $self->{capacity} += ($t - $self->{lastsend}) * $self->{linepersec};
328                 $self->{lastsend} = $t;
329                 $self->{capacity} = $self->{maxlines}
330                         if $self->{capacity} > $self->{maxlines};
331                 if(!$nothrottle)
332                 {
333                         return -1
334                                 if $self->{capacity} < 0;
335                 }
336                 $self->{capacity} -= 1;
337         }
338         $line =~ s/\r|\n//g;
339         return $self->{connector}->send("$line\r\n");
340 }
341
342 sub quote($$)
343 {
344         my ($self, $data) = @_;
345         $data =~ s/\r\n?/\n/g;
346         $data =~ s/\n/*/g;
347         return $data;
348 }
349
350 sub recv($)
351 {
352         my ($self) = @_;
353         for(;;)
354         {
355                 length(my $s = $self->{connector}->recv())
356                         or last;
357                 $self->{recvbuf} .= $s;
358         }
359         my @out = ();
360         while($self->{recvbuf} =~ s/^(.*?)(?:\r\n?|\n)//)
361         {
362                 push @out, $1;
363         }
364         return @out;
365 }
366
367 sub fds($)
368 {
369         my ($self) = @_;
370         return $self->{connector}->fds();
371 }
372
373
374
375
376
377
378 # main program... a gateway between IRC and DarkPlaces servers
379 package main;
380
381 use strict;
382 use warnings;
383 use IO::Select;
384 use Digest::MD5;
385 use Time::HiRes qw/time/;
386
387 our @handlers = (); # list of [channel, expression, sub to handle result]
388 our @tasks = (); # list of [time, sub]
389 our %channels = ();
390 our %store = (
391         irc_nick => "",
392 );
393 our %config = (
394         irc_server => undef,
395         irc_nick => undef,
396         irc_user => undef,
397         irc_channel => undef,
398         irc_ping_delay => 120,
399
400         irc_nickserv_password => "",
401         irc_nickserv_identify => 'PRIVMSG NickServ :IDENTIFY %2$s',
402         irc_nickserv_ghost => 'PRIVMSG NickServ :GHOST %1$s %2$s',
403         irc_nickserv_ghost_attempts => 3,
404
405         irc_quakenet_authname => "",
406         irc_quakenet_password => "",
407         irc_quakenet_getchallenge => 'PRIVMSG Q@CServe.quakenet.org :CHALLENGE',
408         irc_quakenet_challengeauth => 'PRIVMSG Q@CServe.quakenet.org :CHALLENGEAUTH',
409         irc_quakenet_challengeprefix => ':Q!TheQBot@CServe.quakenet.org NOTICE [^:]+ :CHALLENGE',
410
411         dp_server => undef,
412         dp_listen => "", 
413         dp_password => undef,
414         dp_status_delay => 30,
415         dp_server_from_wan => "",
416
417         plugins => "",
418 );
419
420
421
422 # MISC STRING UTILITY ROUTINES to convert between DarkPlaces and IRC conventions
423
424 # convert mIRC color codes to DP color codes
425 our @color_irc2dp_table = (7, 0, 4, 2, 1, 1, 6, 1, 3, 2, 5, 5, 4, 6, 7, 7);
426 our @color_dp2irc_table = (14, 4, 9, 8, 12, 11, 13, 14, 15, 15); # not accurate, but legible
427 our @color_dp2ansi_table = ("m", "1;31m", "1;32m", "1;33m", "1;34m", "1;36m", "1;35m", "m", "1m", "1m"); # not accurate, but legible
428 our %color_team2dp_table = (5 => 1, 14 => 4, 13 => 3, 10 => 6);
429 our %color_team2irc_table = (5 => 4, 14 => 12, 13 => 8, 10 => 13);
430 sub color_irc2dp($)
431 {
432         my ($message) = @_;
433         $message =~ s/\^/^^/g;
434         my $color = 7;
435         $message =~ s{\003(\d\d?)(?:,(\d?\d?))?|(\017)}{
436                 # $1 is FG, $2 is BG, but let's ignore BG
437                 my $oldcolor = $color;
438                 if($3)
439                 {
440                         $color = 7;
441                 }
442                 else
443                 {
444                         $color = $color_irc2dp_table[$1];
445                         $color = $oldcolor if not defined $color;
446                 }
447                 ($color == $oldcolor) ? '' : '^' . $color;
448         }esg;
449         $message =~ s{[\000-\037]}{}gs; # kill bold etc. for now
450         return $message;
451 }
452
453 our @text_qfont_table = ( # ripped from DP console.c qfont_table
454     "\0", '#',  '#',  '#',  '#',  '.',  '#',  '#',
455     '#',  9,    10,   '#',  ' ',  13,   '.',  '.',
456     '[',  ']',  '0',  '1',  '2',  '3',  '4',  '5',
457     '6',  '7',  '8',  '9',  '.',  '<',  '=',  '>',
458     ' ',  '!',  '"',  '#',  '$',  '%',  '&',  '\'',
459     '(',  ')',  '*',  '+',  ',',  '-',  '.',  '/',
460     '0',  '1',  '2',  '3',  '4',  '5',  '6',  '7',
461     '8',  '9',  ':',  ';',  '<',  '=',  '>',  '?',
462     '@',  'A',  'B',  'C',  'D',  'E',  'F',  'G',
463     'H',  'I',  'J',  'K',  'L',  'M',  'N',  'O',
464     'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',
465     'X',  'Y',  'Z',  '[',  '\\', ']',  '^',  '_',
466     '`',  'a',  'b',  'c',  'd',  'e',  'f',  'g',
467     'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o',
468     'p',  'q',  'r',  's',  't',  'u',  'v',  'w',
469     'x',  'y',  'z',  '{',  '|',  '}',  '~',  '<',
470     '<',  '=',  '>',  '#',  '#',  '.',  '#',  '#',
471     '#',  '#',  ' ',  '#',  ' ',  '>',  '.',  '.',
472     '[',  ']',  '0',  '1',  '2',  '3',  '4',  '5',
473     '6',  '7',  '8',  '9',  '.',  '<',  '=',  '>',
474     ' ',  '!',  '"',  '#',  '$',  '%',  '&',  '\'',
475     '(',  ')',  '*',  '+',  ',',  '-',  '.',  '/',
476     '0',  '1',  '2',  '3',  '4',  '5',  '6',  '7',
477     '8',  '9',  ':',  ';',  '<',  '=',  '>',  '?',
478     '@',  'A',  'B',  'C',  'D',  'E',  'F',  'G',
479     'H',  'I',  'J',  'K',  'L',  'M',  'N',  'O',
480     'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',
481     'X',  'Y',  'Z',  '[',  '\\', ']',  '^',  '_',
482     '`',  'a',  'b',  'c',  'd',  'e',  'f',  'g',
483     'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o',
484     'p',  'q',  'r',  's',  't',  'u',  'v',  'w',
485     'x',  'y',  'z',  '{',  '|',  '}',  '~',  '<'
486 );
487 sub text_dp2ascii($)
488 {
489         my ($message) = @_;
490         $message = join '', map { $text_qfont_table[ord $_] } split //, $message;
491 }
492
493 sub color_dp2none($)
494 {
495         my ($message) = @_;
496         my $color = -1;
497         $message =~ s{\^(.)(?=([0-9,]?))}{
498                 my $c = $1;
499                 $c eq '^' ? '^' :
500                 $c =~ /^[0-9]$/ ? '' : "^$c";
501         }esg;
502         return text_dp2ascii $message;
503 }
504
505 sub color_dp2irc($)
506 {
507         my ($message) = @_;
508         my $color = -1;
509         $message =~ s{\^(.)(?=([0-9,]?))}{
510                 my $c = $1;
511                 my $f = $2;
512                 $c eq '^' ? '^' :
513                 $c =~ /^[0-9]$/ ? do {
514                         my $oldcolor = $color;
515                         $c = 0 if $c >= 7; # map 0, 7, 8, 9 to default (no bright white or such stuff)
516                         $color = $color_dp2irc_table[$c];
517                         ($color == $oldcolor) ? '' :
518                         $c == 0 ? "\0001" :
519                         $f eq ',' ? "\0003$color\0002\0002" :
520                         $f ne ''  ? sprintf "\0003%02d", $color : "\0003$color";
521                 } : "^$c";
522         }esg;
523         $message = text_dp2ascii $message;
524         $message =~ s/\0001/\017/g;
525         $message =~ s/\0002/\002/g;
526         $message =~ s/\0003/\003/g;
527         return $message;
528 }
529
530 sub color_dp2ansi($)
531 {
532         my ($message) = @_;
533         my $color = -1;
534         $message =~ s{\^(.)}{
535                 my $c = $1;
536                 $c eq '^' ? '^' :
537                 $c =~ /^[0-9]$/ ? do {
538                         my $oldcolor = $color;
539                         $color = $color_dp2ansi_table[$c];
540                         ($color eq $oldcolor) ? '' :
541                         "\000[${color}" # "
542                 } : "^$c";
543         }esg;
544         $message = text_dp2ascii $message;
545         $message =~ s/\000/\033/g;
546         return $message;
547 }
548
549 sub color_dpfix($)
550 {
551         my ($message) = @_;
552         # if the message ends with an odd number of ^, kill one
553         chop $message if $message =~ /(?:^|[^\^])\^(\^\^)*$/;
554         return $message;
555 }
556
557
558
559 # Nexuiz specific parsing of some server messages
560
561 sub nex_is_teamplay($)
562 {
563         my ($map) = @_;
564         return $map =~ /^(?:kh|ctf|tdm|dom)_/;
565 }
566
567 sub nex_slotsstring()
568 {
569         my $slotsstr = "";
570         if(defined $store{slots_max})
571         {
572                 my $slots = $store{slots_max} - $store{slots_active};
573                 my $slots_s = ($slots == 1) ? '' : 's';
574                 $slotsstr = " ($slots free slot$slots_s)";
575                 my $s = $config{dp_server_from_wan} || $config{dp_server};
576                 $slotsstr .= "; join now: \002nexuiz +connect $s"
577                         if $slots >= 1 and not $store{lms_blocked};
578         }
579         return $slotsstr;
580 }
581
582
583
584 # Do we have a config file? If yes, read and parse it (syntax: key = value
585 # pairs, separated by newlines), if not, complain.
586 die "Usage: $0 configfile\n"
587         unless @ARGV == 1;
588
589 open my $fh, "<", $ARGV[0]
590         or die "open $ARGV[0]: $!";
591 while(<$fh>)
592 {
593         chomp;
594         /^#/ and next;
595         /^(.*?)\s+=(?:\s+(.*))?$/ or next;
596         warn "Undefined config item: $1"
597                 unless exists $config{$1};
598         $config{$1} = defined $2 ? $2 : "";
599 }
600 close $fh;
601 my @missing = grep { !defined $config{$_} } keys %config;
602 die "The following config items are missing: @missing"
603         if @missing;
604
605
606
607 # Create a channel for error messages and other internal status messages...
608
609 $channels{system} = new Channel::FIFO();
610
611 # for example, quit messages caused by signals (if SIGTERM or SIGINT is first
612 # received, try to shut down cleanly, and if such a signal is received a second
613 # time, just exit)
614 my $quitting = 0;
615 $SIG{INT} = sub {
616         exit 1 if $quitting++;
617         $channels{system}->send("quit SIGINT");
618 };
619 $SIG{TERM} = sub {
620         exit 1 if $quitting++;
621         $channels{system}->send("quit SIGTERM");
622 };
623
624
625
626 # Create the two channels to gateway between...
627
628 $channels{irc} = new Channel::Line(new Connection::Socket(tcp => "" => $config{irc_server} => 6667));
629 $channels{dp} = new Channel::QW(my $dpsock = new Connection::Socket(udp => $config{dp_listen} => $config{dp_server} => 26000), $config{dp_password});
630 $config{dp_listen} = $dpsock->sockname();
631 print "Listening on $config{dp_listen}\n";
632
633
634
635 # Utility routine to write to a channel by name, also outputting what's been written and some status
636 sub out($$@)
637 {
638         my $chanstr = shift;
639         my $nothrottle = shift;
640         my $chan = $channels{$chanstr};
641         if(!$chan)
642         {
643                 print "UNDEFINED: $chanstr, ignoring message\n";
644                 return;
645         }
646         @_ = $chan->join_commands(@_);
647         for(@_)
648         {
649                 my $result = $chan->send($_, $nothrottle);
650                 if($result > 0)
651                 {
652                         print "           $chanstr << $_\n";
653                 }
654                 elsif($result < 0)
655                 {
656                         print "FLOOD:     $chanstr << $_\n";
657                 }
658                 else
659                 {
660                         print "ERROR:     $chanstr << $_\n";
661                         $channels{system}->send("error $chanstr", 0);
662                 }
663         }
664 }
665
666
667
668 # Schedule a task for later execution by the main loop; usage: schedule sub {
669 # task... }, $time; When a scheduled task is run, a reference to the task's own
670 # sub is passed as first argument; that way, the task is able to re-schedule
671 # itself so it gets periodically executed.
672 sub schedule($$)
673 {
674         my ($sub, $time) = @_;
675         push @tasks, [time() + $time, $sub];
676 }
677
678 # Build up an IO::Select object for all our channels.
679 my $s = IO::Select->new();
680 for my $chan(values %channels)
681 {
682         $s->add($_) for $chan->fds();
683 }
684
685 # On IRC error, delete some data store variables of the connection, and
686 # reconnect to the IRC server soon (but only if someone is actually playing)
687 sub irc_error()
688 {
689         # prevent multiple instances of this timer
690         return if $store{irc_error_active};
691         $store{irc_error_active} = 1;
692
693         delete $channels{irc};
694         schedule sub {
695                 my ($timer) = @_;
696                 if(!defined $store{slots_full})
697                 {
698                         # DP is not running, then delay IRC reconnecting
699                         #use Data::Dumper; print Dumper \$timer;
700                         schedule $timer => 1;;
701                         return;
702                         # this will keep irc_error_active
703                 }
704                 $channels{irc} = new Channel::Line(new Connection::Socket(tcp => "" => $config{irc_server}));
705                 delete $store{$_} for grep { /^irc_/ } keys %store;
706                 $store{irc_nick} = "";
707                 schedule sub {
708                         my ($timer) = @_;
709                         out dp => 0, 'status', 'log_dest_udp';
710                 } => 1;
711                 # this will clear irc_error_active
712         } => 30;
713         return 0;
714 }
715
716 # IRC joining (if this is called as response to a nick name collision, $is433 is set);
717 # among other stuff, it performs NickServ or Quakenet authentication. This is to be called
718 # until the channel has been joined for every message that may be "interesting" (basically,
719 # IRC 001 hello messages, 443 nick collision messages and some notices by services).
720 sub irc_joinstage($)
721 {
722         my($is433) = @_;
723
724         return 0
725                 if $store{irc_joined_channel};
726         
727                 #use Data::Dumper; print Dumper \%store;
728
729         if($is433)
730         {
731                 if(length $store{irc_nick})
732                 {
733                         # we already have another nick, but couldn't change to the new one
734                         # try ghosting and then get the nick again
735                         if(length $config{irc_nickserv_password})
736                         {
737                                 if(++$store{irc_nickserv_ghost_attempts} <= $config{irc_nickserv_ghost_attempts})
738                                 {
739                                         $store{irc_nick_requested} = $config{irc_nick};
740                                         out irc => 1, sprintf($config{irc_nickserv_ghost}, $config{irc_nick}, $config{irc_nickserv_password});
741                                         schedule sub {
742                                                 out irc => 1, "NICK $config{irc_nick}";
743                                         } => 1;
744                                         return; # we'll get here again for the NICK success message, or for a 433 failure
745                                 }
746                                 # otherwise, we failed to ghost and will continue with the wrong
747                                 # nick... also, no need to try to identify here
748                         }
749                         # otherwise, we can't handle this and will continue with our wrong nick
750                 }
751                 else
752                 {
753                         # we failed to get an initial nickname
754                         # change ours a bit and try again
755                         if(length $store{irc_nick_requested} < 9)
756                         {
757                                 $store{irc_nick_requested} .= '_';
758                         }
759                         else
760                         {
761                                 substr $store{irc_nick_requested}, int(rand length $store{irc_nick_requested}), 1, chr(97 + int rand 26);
762                         }
763                         out irc => 1, "NICK $store{irc_nick_requested}";
764                         return; # when it fails, we'll get here again, and when it succeeds, we will continue
765                 }
766         }
767
768         # we got a 001 or a NICK message, so $store{irc_nick} has been updated
769         if(length $config{irc_nickserv_password})
770         {
771                 if($store{irc_nick} eq $config{irc_nick})
772                 {
773                         # identify
774                         out irc => 1, sprintf($config{irc_nickserv_identify}, $config{irc_nick}, $config{irc_nickserv_password});
775                 }
776                 else
777                 {
778                         # ghost
779                         if(++$store{irc_nickserv_ghost_attempts} <= $config{irc_nickserv_ghost_attempts})
780                         {
781                                 $store{irc_nick_requested} = $config{irc_nick};
782                                 out irc => 1, sprintf($config{irc_nickserv_ghost}, $config{irc_nick}, $config{irc_nickserv_password});
783                                 schedule sub {
784                                         out irc => 1, "NICK $config{irc_nick}";
785                                 } => 1;
786                                 return; # we'll get here again for the NICK success message, or for a 433 failure
787                         }
788                         # otherwise, we failed to ghost and will continue with the wrong
789                         # nick... also, no need to try to identify here
790                 }
791         }
792
793         # we are on Quakenet. Try to authenticate.
794         if(length $config{irc_quakenet_password} and length $config{irc_quakenet_authname})
795         {
796                 if(defined $store{irc_quakenet_challenge})
797                 {
798                         if($store{irc_quakenet_challenge} =~ /^MD5 (.*)/)
799                         {
800                                 out irc => 1, "$config{irc_quakenet_challengeauth} $config{irc_quakenet_authname} " . Digest::MD5::md5_hex("$config{irc_quakenet_password} $1");
801                         }
802                 }
803                 else
804                 {
805                         out irc => 1, $config{irc_quakenet_getchallenge};
806                         return;
807                         # we get here again when Q asks us
808                 }
809         }
810         
811         # if we get here, we are on IRC
812         $store{irc_joined_channel} = 1;
813         schedule sub {
814                 out irc => 1, "JOIN $config{irc_channel}";
815         } => 1;
816         return 0;
817 }
818
819
820
821 # List of all handlers on the various sockets. Additional handlers can be added by a plugin.
822 @handlers = (
823         # detect a server restart and set it up again
824         [ dp => q{ *(?:Warning: Could not expand \$|Unknown command ")(?:rcon2irc_[a-z0-9_]*)[" ]*} => sub {
825                 out dp => 0,
826                         'alias rcon2irc_eval "$*"',
827                         'log_dest_udp',
828                         'sv_logscores_console 0',
829                         'sv_logscores_bots 1',
830                         'sv_eventlog 1',
831                         'sv_eventlog_console 1',
832                         'alias rcon2irc_say_as "set say_as_restorenick \"$sv_adminnick\"; sv_adminnick \"$1^3\"; say \"^7$2\"; rcon2irc_say_as_restore"',
833                         'alias rcon2irc_say_as_restore "set sv_adminnick \"$say_as_restorenick\""',
834                         'alias rcon2irc_quit "echo \"quitting rcon2irc $1: log_dest_udp is $log_dest_udp\""'; # note: \\\\\\" ->perl \\\" ->console \"
835                 return 0;
836         } ],
837
838         # detect missing entry in log_dest_udp and fix it
839         [ dp => q{"log_dest_udp" is "([^"]*)" \["[^"]*"\]} => sub {
840                 my ($dest) = @_;
841                 my @dests = split ' ', $dest;
842                 return 0 if grep { $_ eq $config{dp_listen} } @dests;
843                 out dp => 0, 'log_dest_udp "' . join(" ", @dests, $config{dp_listen}) . '"';
844                 return 0;
845         } ],
846
847         # retrieve hostname from status replies
848         [ dp => q{host:     (.*)} => sub {
849                 my ($name) = @_;
850                 $store{dp_hostname} = $name;
851                 return 0;
852         } ],
853
854         # retrieve version from status replies
855         [ dp => q{version:  (.*)} => sub {
856                 my ($version) = @_;
857                 $store{dp_version} = $version;
858                 return 0;
859         } ],
860
861         # retrieve number of open player slots
862         [ dp => q{players:  (\d+) active \((\d+) max\)} => sub {
863                 my ($active, $max) = @_;
864                 my $full = ($active >= $max);
865                 $store{slots_max} = $max;
866                 $store{slots_active} = $active;
867                 if($full != ($store{slots_full} || 0))
868                 {
869                         $store{slots_full} = $full;
870                         return 0
871                                 if $store{lms_blocked};
872                         if($full)
873                         {
874                                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION is full!\001";
875                         }
876                         else
877                         {
878                                 my $slotsstr = nex_slotsstring();
879                                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION can be joined again$slotsstr!\001";
880                         }
881                 }
882                 return 0;
883         } ],
884
885         # LMS: detect "no more lives" message
886         [ dp => q{\^4.*\^4 has no more lives left} => sub {
887                 if(!$store{lms_blocked})
888                 {
889                         $store{lms_blocked} = 1;
890                         if(!$store{slots_full})
891                         {
892                                 schedule sub {
893                                         if($store{lms_blocked})
894                                         {
895                                                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION can't be joined until next round (a player has no more lives left)\001";
896                                         }
897                                 } => 1;
898                         }
899                 }
900         } ],
901
902         # detect IRC errors and reconnect
903         [ irc => q{ERROR .*} => \&irc_error ],
904         [ system => q{error irc} => \&irc_error ],
905
906         # IRC nick in use
907         [ irc => q{:[^ ]* 433 .*} => sub {
908                 return irc_joinstage(433);
909         } ],
910
911         # IRC welcome
912         [ irc => q{:[^ ]* 001 .*} => sub {
913                 $store{irc_seen_welcome} = 1;
914                 $store{irc_nick} = $store{irc_nick_requested};
915                 return irc_joinstage(0);
916         } ],
917
918         # IRC my nickname changed
919         [ irc => q{:(?i:(??{$store{irc_nick}}))![^ ]* (?i:NICK) :(.*)} => sub {
920                 my ($n) = @_;
921                 $store{irc_nick} = $n;
922                 return irc_joinstage(0);
923         } ],
924
925         # Quakenet: challenge from Q
926         [ irc => q{(??{$config{irc_quakenet_challengeprefix}}) (.*)} => sub {
927                 $store{irc_quakenet_challenge} = $1;
928                 return irc_joinstage(0);
929         } ],
930
931         # shut down everything on SIGINT
932         [ system => q{quit (.*)} => sub {
933                 my ($cause) = @_;
934                 out irc => 1, "QUIT :$cause";
935                 $store{quitcookie} = int rand 1000000000;
936                 out dp => 0, "rcon2irc_quit $store{quitcookie}";
937         } ],
938
939         # remove myself from the log destinations and exit everything
940         [ dp => q{quitting rcon2irc (??{$store{quitcookie}}): log_dest_udp is (.*) *} => sub {
941                 my ($dest) = @_;
942                 my @dests = grep { $_ ne $config{dp_listen} } split ' ', $dest;
943                 out dp => 0, 'log_dest_udp "' . join(" ", @dests) . '"';
944                 exit 0;
945                 return 0;
946         } ],
947
948         # IRC PING
949         [ irc => q{PING (.*)} => sub {
950                 my ($data) = @_;
951                 out irc => 1, "PONG $data";
952                 return 1;
953         } ],
954
955         # IRC PONG
956         [ irc => q{:[^ ]* PONG .* :(.*)} => sub {
957                 my ($data) = @_;
958                 return 0
959                         if not defined $store{irc_pingtime};
960                 return 0
961                         if $data ne $store{irc_pingtime};
962                 print "* measured IRC line delay: @{[time() - $store{irc_pingtime}]}\n";
963                 undef $store{irc_pingtime};
964                 return 0;
965         } ],
966
967         # detect channel join message and note hostname length to get the maximum allowed line length
968         [ irc => q{(:(?i:(??{$store{irc_nick}}))![^ ]* )(?i:JOIN) :(?i:(??{$config{irc_channel}}))} => sub {
969                 $store{irc_maxlen} = 510 - length($1);
970                 $store{irc_joined_channel} = 1;
971                 print "* detected maximum line length for channel messages: $store{irc_maxlen}\n";
972                 return 0;
973         } ],
974
975         # chat: Nexuiz server -> IRC channel
976         [ dp => q{\001(.*?)\^7: (.*)} => sub {
977                 my ($nick, $message) = map { color_dp2irc $_ } @_;
978                 out irc => 0, "PRIVMSG $config{irc_channel} :<$nick\017> $message";
979                 return 0;
980         } ],
981
982         # chat: IRC channel -> Nexuiz server
983         [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$config{irc_channel}})) :(?i:(??{$store{irc_nick}}))(?: |: ?)(.*)} => sub {
984                 my ($nick, $message) = @_;
985                 $nick = color_dpfix $nick;
986                         # allow the nickname to contain colors in DP format! Therefore, NO color_irc2dp on the nickname!
987                 $message = color_irc2dp $message;
988                 $message =~ s/(["\\])/\\$1/g;
989                 out dp => 0, "rcon2irc_say_as \"$nick on IRC\" \"$message\"";
990                 return 0;
991         } ],
992
993         # irc: CTCP VERSION reply
994         [ irc => q{:([^! ]*)![^ ]* (?i:PRIVMSG) (?i:(??{$store{irc_nick}})) :\001VERSION( .*)?\001} => sub {
995                 my ($nick) = @_;
996                 my $ver = $store{dp_version} or return 0;
997                 $ver .= ", rcon2irc $VERSION";
998                 out irc => 0, "NOTICE $nick :\001VERSION $ver\001";
999         } ],
1000
1001         # on game start, notify the channel
1002         [ dp => q{:gamestart:(.*):[0-9.]*} => sub {
1003                 my ($map) = @_;
1004                 $store{playing} = 1;
1005                 $store{map} = $map;
1006                 $store{map_starttime} = time();
1007                 my $slotsstr = nex_slotsstring();
1008                 out irc => 0, "PRIVMSG $config{irc_channel} :\00304" . $map . "\017 has begun$slotsstr";
1009                 delete $store{lms_blocked};
1010                 return 0;
1011         } ],
1012
1013         # on game over, clear the current map
1014         [ dp => q{:gameover} => sub {
1015                 $store{playing} = 0;
1016                 return 0;
1017         } ],
1018
1019         # scores: Nexuiz server -> IRC channel (start)
1020         [ dp => q{:scores:(.*):(\d+)} => sub {
1021                 my ($map, $time) = @_;
1022                 $store{scores} = {};
1023                 $store{scores}{map} = $map;
1024                 $store{scores}{time} = $time;
1025                 $store{scores}{players} = [];
1026                 delete $store{lms_blocked};
1027                 return 0;
1028         } ],
1029
1030         # scores: Nexuiz server -> IRC channel
1031         [ dp => q{:player:(-?\d+):(\d+):(\d+):(\d+):(\d+):(.*)} => sub {
1032                 my ($frags, $deaths, $time, $team, $id, $name) = @_;
1033                 return if not exists $store{scores};
1034                 push @{$store{scores}{players}}, [$frags, $team, $name]
1035                         unless $frags <= -666; # no spectators
1036                 return 0;
1037         } ],
1038
1039         # scores: Nexuiz server -> IRC channel
1040         [ dp => q{:end} => sub {
1041                 return if not exists $store{scores};
1042                 my $s = $store{scores};
1043                 delete $store{scores};
1044                 my $teams_matter = nex_is_teamplay($s->{map});
1045
1046                 my @t = ();
1047                 my @p = ();
1048
1049                 if($teams_matter)
1050                 {
1051                         # put players into teams
1052                         my %t = ();
1053                         for(@{$s->{players}})
1054                         {
1055                                 my $thisteam = ($t{$_->[1]} ||= {score => 0, team => $_->[1], players => []});
1056                                 push @{$thisteam->{players}}, [$_->[0], $_->[1], $_->[2]];
1057                                 $thisteam->{score} += $_->[0];
1058                         }
1059
1060                         # sort by team score
1061                         @t = sort { $b->{score} <=> $a->{score} } values %t;
1062
1063                         # sort by player score
1064                         @p = ();
1065                         for(@t)
1066                         {
1067                                 @{$_->{players}} = sort { $b->[0] <=> $a->[0] } @{$_->{players}};
1068                                 push @p, @{$_->{players}};
1069                         }
1070                 }
1071                 else
1072                 {
1073                         @p = sort { $b->[0] <=> $a->[0] } @{$s->{players}};
1074                 }
1075
1076                 # no display for empty server
1077                 return 0
1078                         if !@p;
1079
1080                 # make message fit somehow
1081                 for my $maxnamelen(reverse 3..64)
1082                 {
1083                         my $scores_string = "PRIVMSG $config{irc_channel} :\00304" . $s->{map} . "\017 ended:";
1084                         if($teams_matter)
1085                         {
1086                                 my $sep = ' ';
1087                                 for(@t)
1088                                 {
1089                                         $scores_string .= $sep . sprintf "\003%02d\%d\017", $color_team2irc_table{$_->{team}}, $_->{score};
1090                                         $sep = ':';
1091                                 }
1092                         }
1093                         my $sep = '';
1094                         for(@p)
1095                         {
1096                                 my ($frags, $team, $name) = @$_;
1097                                 $name = color_dpfix substr($name, 0, $maxnamelen);
1098                                 if($teams_matter)
1099                                 {
1100                                         $name = "\003" . $color_team2irc_table{$team} . " " . color_dp2none $name;
1101                                 }
1102                                 else
1103                                 {
1104                                         $name = " " . color_dp2irc $name;
1105                                 }
1106                                 $scores_string .= "$sep$name\017 $frags";
1107                                 $sep = ',';
1108                         }
1109                         if(length($scores_string) <= ($store{irc_maxlen} || 256))
1110                         {
1111                                 out irc => 0, $scores_string;
1112                                 return 0;
1113                         }
1114                 }
1115                 out irc => 0, "PRIVMSG $config{irc_channel} :\001ACTION would have LIKED to put the scores here, but they wouldn't fit :(\001";
1116                 return 0;
1117         } ],
1118
1119         # complain when system load gets too high
1120         [ dp => q{timing:   (([0-9.]*)% CPU, ([0-9.]*)% lost, offset avg ([0-9.]*)ms, max ([0-9.]*)ms, sdev ([0-9.]*)ms)} => sub {
1121                 my ($all, $cpu, $lost, $avg, $max, $sdev) = @_;
1122                 return 0 # don't complain when just on the voting screen
1123                         if !$store{playing};
1124                 return 0 # don't complain if it was less than 0.5%
1125                         if $lost < 0.5;
1126                 return 0 # don't complain if nobody is looking
1127                         if $store{slots_active} == 0;
1128                 return 0 # don't complain in the first two minutes
1129                         if time() - $store{map_starttime} < 120;
1130                 return 0 # don't complain if it was already at least half as bad in this round
1131                         if $store{map_starttime} == $store{timingerror_map_starttime} and $lost <= 2 * $store{timingerror_lost};
1132                 $store{timingerror_map_starttime} = $store{map_starttime};
1133                 $store{timingerror_lost} = $lost;
1134                 out dp => 0, 'rcon2irc_say_as server "There are currently some severe system load problems. The admins have been notified."';
1135                 out irc => 1, "PRIVMSG $config{irc_channel} :\001ACTION has big trouble on $store{map} after @{[int(time() - $store{map_starttime})]}s: $all\001";
1136                 #out irc => 1, "PRIVMSG OpBaI :\001ACTION has big trouble on $store{map} after @{[int(time() - $store{map_starttime})]}s: $all\001";
1137                 return 0;
1138         } ],
1139 );
1140
1141
1142
1143 # Load plugins and add them to the handler list in the front.
1144 for my $p(split ' ', $config{plugins})
1145 {
1146         my @h = eval { do $p; }
1147                 or die "Invalid plugin $p: $@";
1148         for(reverse @h)
1149         {
1150                 ref $_ eq 'ARRAY' or die "Invalid plugin $p: did not return a list of arrays";
1151                 @$_ == 3 or die "Invalid plugin $p: did not return a list of three-element arrays";
1152                 !ref $_->[0] && !ref $_->[1] && ref $_->[2] eq 'CODE' or die "Invalid plugin $p: did not return a list of string-string-sub arrays";
1153                 unshift @handlers, $_;
1154         }
1155 }
1156
1157
1158
1159 # verify that the server is up by letting it echo back a string that causes
1160 # re-initialization of the required aliases
1161 out dp => 0, 'echo "Unknown command \"rcon2irc_eval\""'; # assume the server has been restarted
1162
1163
1164
1165 # regularily, query the server status and if it still is connected to us using
1166 # the log_dest_udp feature. If not, we will detect the response to this rcon
1167 # command and re-initialize the server's connection to us (either by log_dest_udp
1168 # not containing our own IP:port, or by rcon2irc_eval not being a defined command).
1169 schedule sub {
1170         my ($timer) = @_;
1171         out dp => 0, 'status', 'log_dest_udp', 'rcon2irc_eval set dummy 1';
1172         schedule $timer => (exists $store{dp_hostname} ? $config{dp_status_delay} : 1);;
1173 } => 1;
1174
1175
1176
1177 # Continue with connecting to IRC as soon as we get our first status reply from
1178 # the DP server (which contains the server's hostname that we'll use as
1179 # realname for IRC).
1180 schedule sub {
1181         my ($timer) = @_;
1182
1183         # log on to IRC when needed
1184         if(exists $store{dp_hostname} && !exists $store{irc_logged_in})
1185         {
1186                 $store{irc_nick_requested} = $config{irc_nick};
1187                 out irc => 1, "NICK $config{irc_nick}", "USER $config{irc_user} localhost localhost :$store{dp_hostname}";
1188                 $store{irc_logged_in} = 1;
1189                 undef $store{irc_maxlen};
1190                 undef $store{irc_pingtime};
1191         }
1192
1193         schedule $timer => 1;;
1194 } => 1;
1195
1196
1197
1198 # Regularily ping the IRC server to detect if the connection is down. If it is,
1199 # schedule an IRC error that will cause reconnection later.
1200 schedule sub {
1201         my ($timer) = @_;
1202
1203         if($store{irc_logged_in})
1204         {
1205                 if(defined $store{irc_pingtime})
1206                 {
1207                         # IRC connection apparently broke
1208                         # so... KILL IT WITH FIRE
1209                         channels{system}->send("error irc", 0);
1210                 }
1211                 else
1212                 {
1213                         # everything is fine, send a new ping
1214                         $store{irc_pingtime} = time();
1215                         out irc => 1, "PING $store{irc_pingtime}";
1216                 }
1217         }
1218
1219         schedule $timer => $config{irc_ping_delay};;
1220 } => 1;
1221
1222
1223
1224 # Main loop.
1225 for(;;)
1226 {
1227         # wait for something to happen on our sockets, or wait 2 seconds without anything happening there
1228         $s->can_read(2);
1229         my @errors = $s->has_exception(0);
1230
1231         # on every channel, look for incoming messages
1232         CHANNEL:
1233         for my $chanstr(keys %channels)
1234         {
1235                 my $chan = $channels{$chanstr};
1236                 my @chanfds = $chan->fds();
1237
1238                 for my $chanfd(@chanfds)
1239                 {
1240                         if(grep { $_ == $chanfd } @errors)
1241                         {
1242                                 # STOP! This channel errored!
1243                                 $channels{system}->send("error $chanstr", 0);
1244                                 next CHANNEL;
1245                         }
1246                 }
1247
1248                 for my $line($chan->recv())
1249                 {
1250                         # found one! Check if it matches the regular expression of one of
1251                         # our handlers...
1252                         my $handled = 0;
1253                         for my $h(@handlers)
1254                         {
1255                                 my ($chanstr_wanted, $re, $sub) = @$h;
1256                                 next
1257                                         if $chanstr_wanted ne $chanstr;
1258                                 use re 'eval';
1259                                 my @matches = ($line =~ /^$re$/s);
1260                                 no re 'eval';
1261                                 next
1262                                         unless @matches;
1263                                 # and if it is a match, handle it.
1264                                 ++$handled;
1265                                 my $result = $sub->(@matches);
1266                                 last
1267                                         if $result;
1268                         }
1269                         # print the message, together with info on whether it has been handled or not
1270                         if($handled)
1271                         {
1272                                 print "           $chanstr >> $line\n";
1273                         }
1274                         else
1275                         {
1276                                 print "unhandled: $chanstr >> $line\n";
1277                         }
1278                 }
1279         }
1280
1281         # handle scheduled tasks...
1282         my @t = @tasks;
1283         my $t = time();
1284         # by emptying the list of tasks...
1285         @tasks = ();
1286         for(@t)
1287         {
1288                 my ($time, $sub) = @$_;
1289                 if($t >= $time)
1290                 {
1291                         # calling them if they are schedled for the "past"...
1292                         $sub->($sub);
1293                 }
1294                 else
1295                 {
1296                         # or re-adding them to the task list if they still are scheduled for the "future"
1297                         push @tasks, [$time, $sub];
1298                 }
1299         }
1300 }