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