7ee09cde50b2c45f46a548c711ffb63ca129c9e0
[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     } elsif ($arg =~ /^-vhost=(.*)$/) {
136       $heap->{vhost} = $1;
137     } else {
138       die "Extra command-line argument $arg\n" if $heap->{script};
139       $heap->{script} = new FileHandle($arg, 'r')
140         or die "Unable to open $arg for reading: $!\n";
141     }
142   }
143   die "No test name specified\n" unless $heap->{script};
144
145   # hook in to POE
146   $kernel->alias_set('control');
147   $kernel->yield('heartbeat');
148 }
149
150 sub drv_heartbeat {
151   my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
152   my $script = $heap->{script};
153   my $used = {};
154   my $delay = DELAY;
155
156   while (1) {
157     my ($line, $lineno);
158     if ($heap->{line}) {
159       $line = delete $heap->{line};
160     } elsif (defined($line = <$script>)) {
161       $heap->{lineno} = $.;
162       print "." unless $heap->{irc_debug};
163     } else {
164       # close all connections
165       foreach my $client (values %{$heap->{clients}}) {
166         $kernel->call($client->{irc}, 'quit', "I fell off the end of my script");
167         $client->{quitting} = 1;
168       }
169       # unalias the control session
170       $kernel->alias_remove('control');
171       # die in a few seconds
172       $kernel->delay_set('die', 5);
173       return;
174     }
175
176     chomp $line;
177     # ignore comments and blank lines
178     next if $line =~ /^\#/ or $line !~ /\S/;
179
180     # expand any macros in the line
181     $line =~ s/(?<=[^\\])%(\S+?)%/$heap->{macros}->{$1}
182       or die "Use of undefined macro $1 at $heap->{lineno}\n"/eg;
183     # remove any \-escapes
184     $line =~ s/\\(.)/$1/g;
185     # figure out the type of line
186     if ($line =~ /^#/) {
187       # comment, silently ignore it
188     } elsif ($line =~ /^define (\S+) (.+)$/i) {
189       # define a new macro
190       $heap->{macros}->{$1} = $2;
191     } elsif ($line =~ /^undef (\S+)$/i) {
192       # remove the macro
193       delete $heap->{macros}->{$1};
194     } elsif ($line =~ /^connect (\S+) (\S+) (\S+) (\S+) :(.+)$/i) {
195       # connect a new session (named $1) to server $4
196       my ($name, $nick, $ident, $server, $userinfo, $port) = ($1, $2, $3, $4, $5, 6667);
197       $server = $heap->{servers}->{$server} || $server;
198       if ($server =~ /(.+):(\d+)/) {
199         $server = $1;
200         $port = $2;
201       }
202       die "Client with nick $nick already exists (line $heap->{lineno})" if $heap->{clients}->{$nick};
203       my $alias = "client_$name";
204       POE::Component::IRC->new($alias)
205           or die "Unable to create new user $nick (line $heap->{lineno}): $!";
206       my $client = { name => $name,
207                      nick => $nick,
208                      ready => 0,
209                      expect => [],
210                      expect_alarms => [],
211                      irc => $kernel->alias_resolve($alias),
212                      params => { Nick     => $nick,
213                                  Server   => $server,
214                                  Port     => $port,
215                                  Username => $ident,
216                                  Ircname  => $userinfo,
217                                  Debug    => $heap->{irc_debug},
218                                }
219                    };
220       $client->params->{LocalAddr} = $heap->{vhost}
221         if $heap->{vhost};
222       $heap->{clients}->{$client->{name}} = $client;
223       $heap->{sessions}->{$client->{irc}} = $client;
224       $kernel->call($client->{irc}, 'register', 'all');
225       $kernel->call($client->{irc}, 'connect', $client->{params});
226       $used->{$name} = 1;
227     } elsif ($line =~ /^sync (.+)$/i) {
228       # do multi-way synchronization between every session named in $1
229       my @synced = split(/,|\s/, $1);
230       # first, check that they exist and are ready
231       foreach my $clnt (@synced) {
232         die "Unknown session name $clnt (line $heap->{lineno})" unless $heap->{clients}->{$clnt};
233         goto REDO unless $heap->{clients}->{$clnt}->{ready};
234       }
235       # next we actually send the synchronization signals
236       foreach my $clnt (@synced) {
237         my $client = $heap->{clients}->{$clnt};
238         $client->{sync_wait} = [map { $_ eq $clnt ? () : $heap->{clients}->{$_}->{nick} } @synced];
239         $kernel->call($client->{irc}, 'notice', $client->{sync_wait}, 'SYNC');
240         $kernel->call($session, 'disable_client', $client);
241       }
242     } elsif ($line =~ /^:(\S+) (\S+)(.*)$/i) {
243       # generic command handler
244       my ($names, $cmd, $args) = ($1, lc($2), $3);
245       my (@avail, @unavail);
246       # figure out whether each listed client is available or not
247       foreach my $c (split ',', $names) {
248         my $client = $heap->{clients}->{$c};
249         if (not $client) {
250           print "ERROR: Unknown session name $c (line $heap->{lineno}; ignoring)\n";
251         } elsif (($used->{$c} and not $zero_time->{$cmd}) or not $client->{ready}) {
252           push @unavail, $c;
253         } else {
254           push @avail, $c;
255         }
256       }
257       # redo command with unavailable clients
258       if (@unavail) {
259         # This will break if the command can cause a redo for
260         # available clients.. this should be fixed sometime
261         $line = ':'.join(',', @unavail).' '.$cmd.$args;
262         $heap->{redo} = 1;
263       }
264       # do command with available clients
265       if (@avail) {
266         # split up the argument part of the line
267         $args =~ /^((?:(?: [^:])|[^ ])+)?(?: :(.+))?$/;
268         $args = [($1 ? split(' ', $1) : ()), ($2 ? $2 : ())];
269         # find the client and figure out if we need to wait
270         foreach my $c (@avail) {
271           my $client = $heap->{clients}->{$c};
272           die "Client $c used twice as source (line $heap->{lineno})" if $used->{c} and not $zero_time->{$cmd};
273           $kernel->call($session, 'cmd_'.$cmd, $client, $args);
274           $used->{$c} = 1 unless $zero_time->{$cmd};
275         }
276       }
277     } else {
278       die "Unrecognized input line $heap->{lineno}: $line";
279     }
280     if ($heap->{redo}) {
281     REDO:
282       delete $heap->{redo};
283       $heap->{line} = $line;
284       last;
285     }
286   }
287   # issue new heartbeat with appropriate delay
288   $kernel->delay_set('heartbeat', $delay);
289 }
290
291 sub drv_timeout_expect {
292   my ($kernel, $session, $client) = @_[KERNEL, SESSION, ARG0];
293   print "ERROR: Dropping timed-out expectation by $client->{name}: ".join(',', @{$client->{expect}->[0]})."\n";
294   $client->{expect_alarms}->[0] = undef;
295   unexpect($kernel, $session, $client);
296 }
297
298 sub drv_reconnect {
299   my ($kernel, $session, $client) = @_[KERNEL, SESSION, ARG0];
300   $kernel->call($client->{irc}, 'connect', $client->{params});
301 }
302
303 sub drv_default {
304   my ($kernel, $heap, $sender, $session, $state, $args) = @_[KERNEL, HEAP, SENDER, SESSION, ARG0, ARG1];
305   if ($state =~ /^irc_(\d\d\d)$/) {
306     my $client = $heap->{sessions}->{$sender};
307     if (@{$client->{expect}}
308         and $args->[0] eq $client->{expect}->[0]->[0]
309         and $client->{expect}->[0]->[1] eq "$1") {
310       my $expect = $client->{expect}->[0];
311       my $mismatch;
312       for (my $x=2; ($x<=$#$expect) and ($x<=$#$args) and not $mismatch; $x++) {
313         $mismatch = 1 unless $args->[$x] =~ /$expect->[$x]/i;
314       }
315       unexpect($kernel, $session, $client) unless $mismatch;
316     }
317     return undef;
318   }
319   print "ERROR: Unexpected event $state to test driver (from ".$sender->ID.")\n";
320   return undef;
321 }
322
323 # client-based command issuers
324
325 sub cmd_message {
326   my ($kernel, $heap, $event, $client, $args) = @_[KERNEL, HEAP, STATE, ARG0, ARG1];
327   die "Missing arguments" unless $#$args >= 1;
328   # translate each target as appropriate (e.g. *sessionname)
329   my @targets = split(/,/, $args->[0]);
330   foreach my $target (@targets) {
331     if ($target =~ /^\*(.+)$/) {
332       my $other = $heap->{clients}->{$1} or die "Unknown session name $1 (line $heap->{lineno})\n";
333       $target = $other->{nick};
334     }
335   }
336   $kernel->call($client->{irc}, substr($event, 4), \@targets, $args->[1]);
337 }
338
339 sub cmd_generic {
340   my ($kernel, $heap, $event, $client, $args) = @_[KERNEL, HEAP, STATE, ARG0, ARG1];
341   $event =~ s/^cmd_//;
342   $kernel->call($client->{irc}, $event, @$args);
343 }
344
345 sub cmd_raw {
346   my ($kernel, $heap, $client, $args) = @_[KERNEL, HEAP, ARG0, ARG1];
347   die "Missing argument" unless $#$args >= 0;
348   $kernel->call($client->{irc}, 'sl', $args->[0]);
349 }
350
351 sub cmd_sleep {
352   my ($kernel, $session, $heap, $client, $args) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
353   die "Missing argument" unless $#$args >= 0;
354   $kernel->call($session, 'disable_client', $client);
355   $kernel->delay_set('enable_client', $args->[0], $client);
356 }
357
358 sub cmd_wait {
359   my ($kernel, $session, $heap, $client, $args) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
360   die "Missing argument" unless $#$args >= 0;
361   # if argument was comma-delimited, split it up (space-delimited is split by generic parser)
362   $args = [split(/,/, $args->[0])] if $args->[0] =~ /,/;
363   # make sure we only wait if all the other clients are ready
364   foreach my $other (@$args) {
365     if (not $heap->{clients}->{$other}->{ready}) {
366       $heap->{redo} = 1;
367       return;
368     }
369   }
370   # disable this client, make the others send SYNC to it
371   $kernel->call($session, 'disable_client', $client);
372   $client->{sync_wait} = [map { $heap->{clients}->{$_}->{nick} } @$args];
373   foreach my $other (@$args) {
374     die "Cannot wait on self" if $other eq $client->{name};
375     $kernel->call($heap->{clients}->{$other}->{irc}, 'notice', $client->{nick}, 'SYNC');
376   }
377 }
378
379 sub cmd_expect {
380   my ($kernel, $session, $heap, $client, $args) = @_[KERNEL, SESSION, HEAP, ARG0, ARG1];
381   die "Missing argument" unless $#$args >= 0;
382   push @{$client->{expect}}, $args;
383   push @{$client->{expect_alarms}}, $kernel->delay_set('timeout_expect', EXPECT_TIMEOUT, $client);
384   $kernel->call($session, 'disable_client', $client);
385 }
386
387 # handlers for messages from IRC
388
389 sub unexpect {
390   my ($kernel, $session, $client) = @_;
391   shift @{$client->{expect}};
392   my $alarm_id = shift @{$client->{expect_alarms}};
393   $kernel->alarm_remove($alarm_id) if $alarm_id;
394   $kernel->call($session, 'enable_client', $client) unless @{$client->{expect}};
395 }
396
397 sub check_expect {
398   my ($kernel, $session, $heap, $poe_sender, $sender, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1];
399   my $client = $heap->{sessions}->{$poe_sender};
400   my $expected = $client->{expect}->[0];
401
402   # check sender
403   if ($expected->[0] =~ /\*(.+)/) {
404     # we expect *sessionname, so look up session's current nick
405     my $exp = $1;
406     $sender =~ /^(.+)!/;
407     return 0 if lc($heap->{clients}->{$exp}->{nick}) ne lc($1);
408   } elsif ($expected->[0] =~ /^:?(.+!.+)/) {
409     # expect :nick!user@host, so compare whole thing
410     return 0 if lc($1) ne lc($sender);
411   } else {
412     # we only expect :nick, so compare that part
413     $sender =~ /^:?(.+)!/;
414     return 0 if lc($expected->[0]) ne lc($1);
415   }
416
417   # compare text
418   return 0 if lc($text) !~ /$expected->[2]/i;
419
420   # drop expectation of event
421   unexpect($kernel, $session, $client);
422 }
423
424 sub irc_connected {
425   my ($kernel, $session, $heap, $sender) = @_[KERNEL, SESSION, HEAP, SENDER];
426   my $client = $heap->{sessions}->{$sender};
427   print "Client $client->{name} connected to server $_[ARG0]\n" if $heap->{verbose};
428   $kernel->call($session, 'enable_client', $client);
429 }
430
431 sub irc_disconnected {
432   my ($kernel, $session, $heap, $sender, $server) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0];
433   my $client = $heap->{sessions}->{$sender};
434   print "Client $client->{name} disconnected from server $_[ARG0]\n" if $heap->{verbose};
435   if ($client->{quitting}) {
436     $kernel->call($sender, 'unregister', 'all');
437     delete $heap->{sessions}->{$sender};
438     delete $heap->{clients}->{$client->{name}};
439   } else {
440     if ($client->{disconnect_expected}) {
441       delete $client->{disconnect_expected};
442     } else {
443       print "Got unexpected disconnect for $client->{name} (nick $client->{nick})\n";
444     }
445     $kernel->call($session, 'disable_client', $client);
446     $kernel->delay_set('reconnect', $client->{throttled} ? THROTTLED_TIMEOUT : RECONNECT_TIMEOUT, $client);
447     delete $client->{throttled};
448   }
449 }
450
451 sub irc_socketerr {
452   my ($kernel, $session, $heap, $sender, $msg) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0];
453   my $client = $heap->{sessions}->{$sender};
454   print "Client $client->{name} (re-)connect error: $_[ARG0]\n";
455   if ($client->{quitting}) {
456     $kernel->call($sender, 'unregister', 'all');
457     delete $heap->{sessions}->{$sender};
458     delete $heap->{clients}->{$client->{name}};
459   } else {
460     if ($client->{disconnect_expected}) {
461       delete $client->{disconnect_expected};
462     } else {
463       print "Got unexpected disconnect for $client->{name} (nick $client->{nick})\n";
464     }
465     $kernel->call($session, 'disable_client', $client);
466     $kernel->delay_set('reconnect', $client->{throttled} ? THROTTLED_TIMEOUT : RECONNECT_TIMEOUT, $client);
467     delete $client->{throttled};
468   }
469 }
470
471 sub irc_notice {
472   my ($kernel, $session, $heap, $sender, $from, $to, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
473   my $client = $heap->{sessions}->{$sender};
474   if ($client->{sync_wait} and $text eq 'SYNC') {
475     $from =~ s/!.+$//;
476     my $x;
477     # find who sent it..
478     for ($x=0; $x<=$#{$client->{sync_wait}}; $x++) {
479       last if $from eq $client->{sync_wait}->[$x];
480     }
481     # exit if we don't expect them
482     if ($x>$#{$client->{sync_wait}}) {
483       print "Got unexpected SYNC from $from to $client->{name} ($client->{nick})\n";
484       return;
485     }
486     # remove from the list of people we're waiting for
487     splice @{$client->{sync_wait}}, $x, 1;
488     # re-enable client if we're done waiting
489     if ($#{$client->{sync_wait}} == -1) {
490       delete $client->{sync_wait};
491       $kernel->call($session, 'enable_client', $client);
492     }
493   } elsif (@{$client->{expect}}
494            and $client->{expect}->[0]->[1] =~ /notice/i) {
495     check_expect(@_[0..ARG0], $text);
496   }
497 }
498
499 sub irc_msg {
500   my ($kernel, $session, $heap, $sender, $from, $to, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
501   my $client = $heap->{sessions}->{$sender};
502   if (@{$client->{expect}}
503       and $client->{expect}->[0]->[1] =~ /msg/i) {
504     check_expect(@_[0..ARG0], $text);
505   }
506 }
507
508 sub irc_public {
509   my ($kernel, $session, $heap, $sender, $from, $to, $text) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
510   my $client = $heap->{sessions}->{$sender};
511   if (@{$client->{expect}}
512       and $client->{expect}->[0]->[1] =~ /public/i
513       and grep($client->{expect}->[0]->[2], @$to)) {
514     splice @{$client->{expect}->[0]}, 2, 1;
515     check_expect(@_[0..ARG0], $text);
516   }
517 }
518
519 sub irc_invite {
520   my ($kernel, $session, $heap, $sender, $from, $to) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0, ARG1, ARG2];
521   my $client = $heap->{sessions}->{$sender};
522   if (ref $client->{expect} eq 'ARRAY'
523       and $client->{expect}->[0]->[1] =~ /invite/i
524       and $to =~ /$client->{expect}->[0]->[2]/) {
525     check_expect(@_[0..ARG0], $to);
526   }
527 }
528
529 sub irc_error {
530   my ($kernel, $session, $heap, $sender, $what) = @_[KERNEL, SESSION, HEAP, SENDER, ARG0];
531   my $client = $heap->{sessions}->{$sender};
532   if (@{$client->{expect}}
533       and $client->{expect}->[0]->[1] =~ /error/i) {
534     splice @{$client->{expect}->[0]}, 2, 1;
535     unexpect($kernel, $session, $client);
536     $client->{disconnect_expected} = 1;
537   } else {
538     print "ERROR: From server to $client->{name}: $what\n";
539   }
540   $client->{throttled} = 1 if $what =~ /throttled/i;
541 }