546c63c89faaf0eeec25208bd2399871c0c53824
[ircu2.10.12-pk.git] / ircd / test / test-driver.pl
1 #! /usr/bin/perl -wT
2
3 # If you edit this file, please check carefully that the garbage
4 # collection isn't broken.  POE is sometimes too clever for our good
5 # in finding references to sessions, and keeps running even after we
6 # want to stop.
7 # $Id$
8
9 # This interprets a simple scripting language.  Lines starting with a
10 # hash mark (#, aka octothorpe, pound sign, etc) are ignored.  The
11 # special commands look like this, where angle brackets indicate a
12 # metavariable:
13 #  define <macro> <value>
14 #  undef <macro>
15 #  connect <name> <nick> <ident> <server> :<userinfo>
16 #  sync <name1>,<name2>[,<name3>]*
17 #  :<name> <command>[ <args]*
18 # For the last line syntax, <command> may be an IRC or IRC-like
19 # command.  Supported non-IRC commands are:
20 #  :<name> expect <source|*name2> [...]
21 #  :<name> raw <text>
22 #  :<name> sleep <seconds>
23 #  :<name> wait <name2>
24
25 require 5.006;
26
27 use bytes;
28 use warnings;
29 use strict;
30 use vars;
31 use constant DELAY => 2;
32 use constant EXPECT_TIMEOUT => 15;
33 use constant RECONNECT_TIMEOUT => 5;
34 use constant THROTTLED_TIMEOUT => 90;
35
36 use FileHandle;
37 use POE;
38 use POE::Component::IRC;
39
40 # this defines commands that take "zero time" to execute
41 # (specifically, those which do not send commands from the issuing
42 # client to the server)
43 our $zero_time = {
44                   expect => 1,
45                   sleep => 1,
46                   wait => 1,
47                  };
48
49 # Create the main session and start POE.
50 # All the empty anonymous subs are just to make POE:Session::ASSERT_STATES happy.
51 POE::Session->create(inline_states =>
52                      {
53                       # POE kernel interaction
54                       _start => \&drv_start,
55                       _child => sub {},
56                       _stop => sub {
57                         my $heap = $_[HEAP];
58                         print "\nThat's all, folks!";
59                         print "(exiting at line $heap->{lineno}: $heap->{line})"
60                           if $heap->{line};
61                         print "\n";
62                       },
63                       _default => \&drv_default,
64                       # generic utilities or miscellaneous functions
65                       heartbeat => \&drv_heartbeat,
66                       timeout_expect => \&drv_timeout_expect,
67                       reconnect => \&drv_reconnect,
68                       enable_client => sub { $_[ARG0]->{ready} = 1; },
69                       disable_client => sub { $_[ARG0]->{ready} = 0; },
70                       die => sub { $_[KERNEL]->signal($_[SESSION], 'TERM'); },
71                       # client-based command issuers
72                       cmd_die => \&cmd_generic,
73                       cmd_expect => \&cmd_expect,
74                       cmd_invite => \&cmd_generic,
75                       cmd_join => \&cmd_generic,
76                       cmd_mode => \&cmd_generic,
77                       cmd_nick => \&cmd_generic,
78                       cmd_notice => \&cmd_message,
79                       cmd_oper => \&cmd_generic,
80                       cmd_part => \&cmd_generic,
81                       cmd_privmsg => \&cmd_message,
82                       cmd_quit => \&cmd_generic,
83                       cmd_raw => \&cmd_raw,
84                       cmd_sleep => \&cmd_sleep,
85                       cmd_wait => \&cmd_wait,
86                       # handlers for messages from IRC
87                       irc_001 => \&irc_connected, # Welcome to ...
88                       irc_snotice => sub {}, # notice from a server (anonymous/our uplink)
89                       irc_notice => \&irc_notice, # NOTICE to self or channel
90                       irc_msg => \&irc_msg, # PRIVMSG to self
91                       irc_public => \&irc_public, # PRIVMSG to channel
92                       irc_connected => sub {},
93                       irc_ctcp_action => sub {},
94                       irc_ctcp_ping => sub {},
95                       irc_ctcp_time => sub {},
96                       irc_ctcpreply_ping => sub {},
97                       irc_ctcpreply_time => sub {},
98                       irc_invite => \&irc_invite, # INVITE to channel
99                       irc_join => sub {},
100                       irc_kick => sub {},
101                       irc_kill => sub {},
102                       irc_mode => sub {},
103                       irc_nick => sub {},
104                       irc_part => sub {},
105                       irc_ping => sub {},
106                       irc_quit => sub {},
107                       irc_topic => sub {},
108                       irc_error => \&irc_error,
109                       irc_disconnected => \&irc_disconnected,
110                       irc_socketerr => \&irc_socketerr,
111                      },
112                      args => [@ARGV]);
113
114 $| = 1;
115 $poe_kernel->run();
116 exit;
117
118 # Core/bookkeeping test driver functions
119
120 sub drv_start {
121   my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
122
123   # initialize heap
124   $heap->{clients} = {}; # session details, indexed by (short) session name
125   $heap->{sessions} = {}; # session details, indexed by session ref
126   $heap->{servers} = {}; # server addresses, indexed by short names
127   $heap->{macros} = {}; # macros
128
129   # Parse arguments
130   foreach my $arg (@_[ARG0..$#_]) {
131     if ($arg =~ /^-D$/) {
132       $heap->{irc_debug} = 1;
133     } elsif ($arg =~ /^-V$/) {
134       $heap->{verbose} = 1;
135     } else {
136       die "Extra command-line argument $arg\n" if $heap->{script};
137       $heap->{script} = new FileHandle($arg, 'r')
138         or die "Unable to open $arg for reading: $!\n";
139     }
140   }
141   die "No test name specified\n" unless $heap->{script};
142
143   # hook in to POE
144   $kernel->alias_set('control');
145   $kernel->yield('heartbeat');
146 }
147
148 sub drv_heartbeat {
149   my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
150   my $script = $heap->{script};
151   my $used = {};
152   my $delay = DELAY;
153
154   while (1) {
155     my ($line, $lineno);
156     if ($heap->{line}) {
157       $line = delete $heap->{line};
158     } elsif (defined($line = <$script>)) {
159       $heap->{lineno} = $.;
160       print "." unless $heap->{irc_debug};
161     } else {
162       # close all connections
163       foreach my $client (values %{$heap->{clients}}) {
164         $kernel->call($client->{irc}, 'quit', "I fell off the end of my script");
165         $client->{quitting} = 1;
166       }
167       # unalias the control session
168       $kernel->alias_remove('control');
169       # die in a few seconds
170       $kernel->delay_set('die', 5);
171       return;
172     }
173
174     chomp $line;
175     # ignore comments and blank lines
176     next if $line =~ /^\#/ or $line !~ /\S/;
177
178     # expand any macros in the line
179     $line =~ s/(?<=[^\\])%(\S+?)%/$heap->{macros}->{$1}
180       or die "Use of undefined macro $1 at $heap->{lineno}\n"/eg;
181     # remove any \-escapes
182     $line =~ s/\\(.)/$1/g;
183     # figure out the type of line
184     if ($line =~ /^#/) {
185       # comment, silently ignore it
186     } elsif ($line =~ /^define (\S+) (.+)$/i) {
187       # define a new macro
188       $heap->{macros}->{$1} = $2;
189     } elsif ($line =~ /^undef (\S+)$/i) {
190       # remove the macro
191       delete $heap->{macros}->{$1};
192     } elsif ($line =~ /^connect (\S+) (\S+) (\S+) (\S+) :(.+)$/i) {
193       # connect a new session (named $1) to server $4
194       my ($name, $nick, $ident, $server, $userinfo, $port) = ($1, $2, $3, $4, $5, 6667);
195       $server = $heap->{servers}->{$server} || $server;
196       if ($server =~ /(.+):(\d+)/) {
197         $server = $1;
198         $port = $2;
199       }
200       die "Client with nick $nick already exists (line $heap->{lineno})" if $heap->{clients}->{$nick};
201       my $alias = "client_$name";
202       POE::Component::IRC->new($alias)
203           or die "Unable to create new user $nick (line $heap->{lineno}): $!";
204       my $client = { name => $name,
205                      nick => $nick,
206                      ready => 0,
207                      expect => [],
208                      expect_alarms => [],
209                      irc => $kernel->alias_resolve($alias),
210                      params => { Nick     => $nick,
211                                  Server   => $server,
212                                  Port     => $port,
213                                  Username => $ident,
214                                  Ircname  => $userinfo,
215                                  Debug    => $heap->{irc_debug},
216                                }
217                    };
218       $heap->{clients}->{$client->{name}} = $client;
219       $heap->{sessions}->{$client->{irc}} = $client;
220       $kernel->call($client->{irc}, 'register', 'all');
221       $kernel->call($client->{irc}, 'connect', $client->{params});
222       $used->{$name} = 1;
223     } elsif ($line =~ /^sync (.+)$/i) {
224       # do multi-way synchronization between every session named in $1
225       my @synced = split(/,|\s/, $1);
226       # first, check that they exist and are ready
227       foreach my $clnt (@synced) {
228         die "Unknown session name $clnt (line $heap->{lineno})" unless $heap->{clients}->{$clnt};
229         goto REDO unless $heap->{clients}->{$clnt}->{ready};
230       }
231       # next we actually send the synchronization signals
232       foreach my $clnt (@synced) {
233         my $client = $heap->{clients}->{$clnt};
234         $client->{sync_wait} = [map { $_ eq $clnt ? () : $heap->{clients}->{$_}->{nick} } @synced];
235         $kernel->call($client->{irc}, 'notice', $client->{sync_wait}, 'SYNC');
236         $kernel->call($session, 'disable_client', $client);
237       }
238     } elsif ($line =~ /^:(\S+) (\S+)(.*)$/i) {
239       # generic command handler
240       my ($names, $cmd, $args) = ($1, lc($2), $3);
241       my (@avail, @unavail);
242       # figure out whether each listed client is available or not
243       foreach my $c (split ',', $names) {
244         my $client = $heap->{clients}->{$c};
245         if (not $client) {
246           print "ERROR: Unknown session name $c (line $heap->{lineno}; ignoring)\n";
247         } elsif (($used->{$c} and not $zero_time->{$cmd}) or not $client->{ready}) {
248           push @unavail, $c;
249         } else {
250           push @avail, $c;
251         }
252       }
253       # redo command with unavailable clients
254       if (@unavail) {
255         # This will break if the command can cause a redo for
256         # available clients.. this should be fixed sometime
257         $line = ':'.join(',', @unavail).' '.$cmd.$args;
258         $heap->{redo} = 1;
259       }
260       # do command with available clients
261       if (@avail) {
262         # split up the argument part of the line
263         $args =~ /^((?:(?: [^:])|[^ ])+)?(?: :(.+))?$/;
264         $args = [($1 ? split(' ', $1) : ()), ($2 ? $2 : ())];
265         # find the client and figure out if we need to wait
266         foreach my $c (@avail) {
267           my $client = $heap->{clients}->{$c};
268           die "Client $c used twice as source (line $heap->{lineno})" if $used->{c} and not $zero_time->{$cmd};
269           $kernel->call($session, 'cmd_'.$cmd, $client, $args);
270           $used->{$c} = 1 unless $zero_time->{$cmd};
271         }
272       }
273     } else {
274       die "Unrecognized input line $heap->{lineno}: $line";
275     }
276     if ($heap->{redo}) {
277     REDO:
278       delete $heap->{redo};
279       $heap->{line} = $line;
280       last;
281     }
282   }
283   # issue new heartbeat with appropriate delay
284   $kernel->delay_set('heartbeat', $delay);
285 }
286
287 sub drv_timeout_expect {
288   my ($kernel, $session, $client) = @_[KERNEL, SESSION, ARG0];
289   print "ERROR: Dropping timed-out expectation by $client->{name}: ".join(',', @{$client->{expect}->[0]})."\n";
290   $client->{expect_alarms}->[0] = undef;
291   unexpect($kernel, $session, $client);
292 }
293
294 sub drv_reconnect {
295   my ($kernel, $session, $client) = @_[KERNEL, SESSION, ARG0];
296   $kernel->call($client->{irc}, 'connect', $client->{params});
297 }
298
299 sub drv_default {
300   my ($kernel, $heap, $sender, $session, $state, $args) = @_[KERNEL, HEAP, SENDER, SESSION, ARG0, ARG1];
301   if ($state =~ /^irc_(\d\d\d)$/) {
302     my $client = $heap->{sessions}->{$sender};
303     if (@{$client->{expect}}
304         and $args->[0] eq $client->{expect}->[0]->[0]
305         and $client->{expect}->[0]->[1] eq "$1") {
306       my $expect = $client->{expect}->[0];
307       my $mismatch;
308       for (my $x=2; ($x<=$#$expect) and ($x<=$#$args) and not $mismatch; $x++) {
309         $mismatch = 1 unless $args->[$x] =~ /$expect->[$x]/i;
310       }
311       unexpect($kernel, $session, $client) unless $mismatch;
312     }
313     return undef;
314   }
315   print "ERROR: Unexpected event $state to test driver (from ".$sender->ID.")\n";
316   return undef;
317 }
318
319 # client-based command issuers
320
321 sub cmd_message {
322   my ($kernel, $heap, $event, $client, $args) = @_[KERNEL, HEAP, STATE, ARG0, ARG1];
323   die "Missing arguments" unless $#$args >= 1;
324   # translate each target as appropriate (e.g. *sessionname)
325   my @targets = split(/,/, $args->[0]);
326   foreach my $target (@targets) {
327     if ($target =~ /^\*(.+)$/) {
328       my $other = $heap->{clients}->{$1} or die "Unknown session name $1 (line $heap->{lineno})\n";
329       $target = $other->{nick};
330     }
331   }
332   $kernel->call($client->{irc}, substr($event, 4), \@targets, $args->[1]);
333 }
334
335 sub cmd_generic {
336   my ($kernel, $heap, $event, $client, $args) = @_[KERNEL, HEAP, STATE, ARG0, ARG1];
337   $event =~ s/^cmd_//;
338   $kernel->call($client->{irc}, $event, @$args);
339 }
340
341 sub cmd_raw {
342   my ($kernel, $heap, $client, $args) = @_[KERNEL, HEAP, ARG0, ARG1];
343   die "Missing argument" unless $#$args >= 0;
344   $kernel->call($client->{irc}, 'sl', $args->[0]);
345 }
346
347 sub cmd_sleep {
348   my ($kernel, $session, $heap, $client, $args) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
349   die "Missing argument" unless $#$args >= 0;
350   $kernel->call($session, 'disable_client', $client);
351   $kernel->delay_set('enable_client', $args->[0], $client);
352 }
353
354 sub cmd_wait {
355   my ($kernel, $session, $heap, $client, $args) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
356   die "Missing argument" unless $#$args >= 0;
357   # if argument was comma-delimited, split it up (space-delimited is split by generic parser)
358   $args = [split(/,/, $args->[0])] if $args->[0] =~ /,/;
359   # make sure we only wait if all the other clients are ready
360   foreach my $other (@$args) {
361     if (not $heap->{clients}->{$other}->{ready}) {
362       $heap->{redo} = 1;
363       return;
364     }
365   }
366   # disable this client, make the others send SYNC to it
367   $kernel->call($session, 'disable_client', $client);
368   $client->{sync_wait} = [map { $heap->{clients}->{$_}->{nick} } @$args];
369   foreach my $other (@$args) {
370     die "Cannot wait on self" if $other eq $client->{name};
371     $kernel->call($heap->{clients}->{$other}->{irc}, 'notice', $client->{nick}, 'SYNC');
372   }
373 }
374
375 sub cmd_expect {
376   my ($kernel, $session, $heap, $client, $args) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
377   die "Missing argument" unless $#$args >= 0;
378   push @{$client->{expect}}, $args;
379   push @{$client->{expect_alarms}}, $kernel->delay_set('timeout_expect', EXPECT_TIMEOUT, $client);
380   $kernel->call($session, 'disable_client', $client);
381 }
382
383 # handlers for messages from IRC
384
385 sub unexpect {
386   my ($kernel, $session, $client) = @_;
387   shift @{$client->{expect}};
388   my $alarm_id = shift @{$client->{expect_alarms}};
389   $kernel->alarm_remove($alarm_id) if $alarm_id;
390   $kernel->call($session, 'enable_client', $client) unless @{$client->{expect}};
391 }
392
393 sub check_expect {
394   my ($kernel, $session, $heap, $poe_sender, $sender, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1];
395   my $client = $heap->{sessions}->{$poe_sender};
396   my $expected = $client->{expect}->[0];
397
398   # check sender
399   if ($expected->[0] =~ /\*(.+)/) {
400     # we expect *sessionname, so look up session's current nick
401     my $exp = $1;
402     $sender =~ /^(.+)!/;
403     return 0 if lc($heap->{clients}->{$exp}->{nick}) ne lc($1);
404   } elsif ($expected->[0] =~ /^:?(.+!.+)/) {
405     # expect :nick!user@host, so compare whole thing
406     return 0 if lc($1) ne lc($sender);
407   } else {
408     # we only expect :nick, so compare that part
409     $sender =~ /^:?(.+)!/;
410     return 0 if lc($expected->[0]) ne lc($1);
411   }
412
413   # compare text
414   return 0 if lc($text) !~ /$expected->[2]/i;
415
416   # drop expectation of event
417   unexpect($kernel, $session, $client);
418 }
419
420 sub irc_connected {
421   my ($kernel, $session, $heap, $sender) = @_[KERNEL, SESSION, HEAP, SENDER];
422   my $client = $heap->{sessions}->{$sender};
423   print "Client $client->{name} connected to server $_[ARG0]\n" if $heap->{verbose};
424   $kernel->call($session, 'enable_client', $client);
425 }
426
427 sub irc_disconnected {
428   my ($kernel, $session, $heap, $sender, $server) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0];
429   my $client = $heap->{sessions}->{$sender};
430   print "Client $client->{name} disconnected from server $_[ARG0]\n" if $heap->{verbose};
431   if ($client->{quitting}) {
432     $kernel->call($sender, 'unregister', 'all');
433     delete $heap->{sessions}->{$sender};
434     delete $heap->{clients}->{$client->{name}};
435   } else {
436     if ($client->{disconnect_expected}) {
437       delete $client->{disconnect_expected};
438     } else {
439       print "Got unexpected disconnect for $client->{name} (nick $client->{nick})\n";
440     }
441     $kernel->call($session, 'disable_client', $client);
442     $kernel->delay_set('reconnect', $client->{throttled} ? THROTTLED_TIMEOUT : RECONNECT_TIMEOUT, $client);
443     delete $client->{throttled};
444   }
445 }
446
447 sub irc_socketerr {
448   my ($kernel, $session, $heap, $sender, $msg) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0];
449   my $client = $heap->{sessions}->{$sender};
450   print "Client $client->{name} (re-)connect error: $_[ARG0]\n";
451   if ($client->{quitting}) {
452     $kernel->call($sender, 'unregister', 'all');
453     delete $heap->{sessions}->{$sender};
454     delete $heap->{clients}->{$client->{name}};
455   } else {
456     if ($client->{disconnect_expected}) {
457       delete $client->{disconnect_expected};
458     } else {
459       print "Got unexpected disconnect for $client->{name} (nick $client->{nick})\n";
460     }
461     $kernel->call($session, 'disable_client', $client);
462     $kernel->delay_set('reconnect', $client->{throttled} ? THROTTLED_TIMEOUT : RECONNECT_TIMEOUT, $client);
463     delete $client->{throttled};
464   }
465 }
466
467 sub irc_notice {
468   my ($kernel, $session, $heap, $sender, $from, $to, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
469   my $client = $heap->{sessions}->{$sender};
470   if ($client->{sync_wait} and $text eq 'SYNC') {
471     $from =~ s/!.+$//;
472     my $x;
473     # find who sent it..
474     for ($x=0; $x<=$#{$client->{sync_wait}}; $x++) {
475       last if $from eq $client->{sync_wait}->[$x];
476     }
477     # exit if we don't expect them
478     if ($x>$#{$client->{sync_wait}}) {
479       print "Got unexpected SYNC from $from to $client->{name} ($client->{nick})\n";
480       return;
481     }
482     # remove from the list of people we're waiting for
483     splice @{$client->{sync_wait}}, $x, 1;
484     # re-enable client if we're done waiting
485     if ($#{$client->{sync_wait}} == -1) {
486       delete $client->{sync_wait};
487       $kernel->call($session, 'enable_client', $client);
488     }
489   } elsif (@{$client->{expect}}
490            and $client->{expect}->[0]->[1] =~ /notice/i) {
491     check_expect(@_[0..ARG0], $text);
492   }
493 }
494
495 sub irc_msg {
496   my ($kernel, $session, $heap, $sender, $from, $to, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
497   my $client = $heap->{sessions}->{$sender};
498   if (@{$client->{expect}}
499       and $client->{expect}->[0]->[1] =~ /msg/i) {
500     check_expect(@_[0..ARG0], $text);
501   }
502 }
503
504 sub irc_public {
505   my ($kernel, $session, $heap, $sender, $from, $to, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
506   my $client = $heap->{sessions}->{$sender};
507   if (@{$client->{expect}}
508       and $client->{expect}->[0]->[1] =~ /public/i
509       and grep($client->{expect}->[0]->[2], @$to)) {
510     splice @{$client->{expect}->[0]}, 2, 1;
511     check_expect(@_[0..ARG0], $text);
512   }
513 }
514
515 sub irc_invite {
516   my ($kernel, $session, $heap, $sender, $from, $to) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
517   my $client = $heap->{sessions}->{$sender};
518   if (ref $client->{expect} eq 'ARRAY'
519       and $client->{expect}->[0]->[1] =~ /invite/i
520       and $to =~ /$client->{expect}->[0]->[2]/) {
521     check_expect(@_[0..ARG0], $to);
522   }
523 }
524
525 sub irc_error {
526   my ($kernel, $session, $heap, $sender, $what) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0];
527   my $client = $heap->{sessions}->{$sender};
528   if (@{$client->{expect}}
529       and $client->{expect}->[0]->[1] =~ /error/i) {
530     splice @{$client->{expect}->[0]}, 2, 1;
531     unexpect($kernel, $session, $client);
532     $client->{disconnect_expected} = 1;
533   } else {
534     print "ERROR: From server to $client->{name}: $what\n";
535   }
536   $client->{throttled} = 1 if $what =~ /throttled/i;
537 }