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