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