Restore testsuite operation under gnuTLS 2.8.5
[exim.git] / test / runtest
1 #! /usr/bin/perl -w
2
3 ###############################################################################
4 # This is the controlling script for the "new" test suite for Exim. It should #
5 # be possible to export this suite for running on a wide variety of hosts, in #
6 # contrast to the old suite, which was very dependent on the environment of   #
7 # Philip Hazel's desktop computer. This implementation inspects the version   #
8 # of Exim that it finds, and tests only those features that are included. The #
9 # surrounding environment is also tested to discover what is available. See   #
10 # the README file for details of how it all works.                            #
11 #                                                                             #
12 # Implementation started: 03 August 2005 by Philip Hazel                      #
13 # Placed in the Exim CVS: 06 February 2006                                    #
14 ###############################################################################
15
16 #use strict;
17 require Cwd;
18 use Errno;
19 use FileHandle;
20 use Socket;
21 use Time::Local;
22
23
24 # Start by initializing some global variables
25
26 $testversion = "4.80 (08-May-12)";
27
28 # This gets embedded in the D-H params filename, and the value comes
29 # from asking GnuTLS for "normal", but there appears to be no way to
30 # use certtool/... to ask what that value currently is.  *sigh*
31 # We also clamp it because of NSS interop, see addition of tls_dh_max_bits.
32 # This value is correct as of GnuTLS 2.12.18 as clamped by tls_dh_max_bits.
33 # normal = 2432   tls_dh_max_bits = 2236
34 $gnutls_dh_bits_normal = 2236;
35
36 $cf = "bin/cf -exact";
37 $cr = "\r";
38 $debug = 0;
39 $force_continue = 0;
40 $force_update = 0;
41 $log_failed_filename = "failed-summary.log";
42 $more = "less -XF";
43 $optargs = "";
44 $save_output = 0;
45 $server_opts = "";
46
47 $have_ipv4 = 1;
48 $have_ipv6 = 1;
49 $have_largefiles = 0;
50
51 $test_start = 1;
52 $test_end = $test_top = 8999;
53 $test_special_top = 9999;
54 @test_list = ();
55 @test_dirs = ();
56
57
58 # Networks to use for DNS tests. We need to choose some networks that will
59 # never be used so that there is no chance that the host on which we are
60 # running is actually in one of the test networks. Private networks such as
61 # the IPv4 10.0.0.0/8 network are no good because hosts may well use them.
62 # Rather than use some unassigned numbers (that might become assigned later),
63 # I have chosen some multicast networks, in the belief that such addresses
64 # won't ever be assigned to hosts. This is the only place where these numbers
65 # are defined, so it is trivially possible to change them should that ever
66 # become necessary.
67
68 $parm_ipv4_test_net = "224";
69 $parm_ipv6_test_net = "ff00";
70
71 # Port numbers are currently hard-wired
72
73 $parm_port_n = 1223;         # Nothing listening on this port
74 $parm_port_s = 1224;         # Used for the "server" command
75 $parm_port_d = 1225;         # Used for the Exim daemon
76 $parm_port_d2 = 1226;        # Additional for daemon
77 $parm_port_d3 = 1227;        # Additional for daemon
78 $parm_port_d4 = 1228;        # Additional for daemon
79
80 # Manually set locale
81 $ENV{'LC_ALL'} = 'C';
82
83
84
85 ###############################################################################
86 ###############################################################################
87
88 # Define a number of subroutines
89
90 ###############################################################################
91 ###############################################################################
92
93
94 ##################################################
95 #              Handle signals                    #
96 ##################################################
97
98 sub pipehandler { $sigpipehappened = 1; }
99
100 sub inthandler { print "\n"; tests_exit(-1, "Caught SIGINT"); }
101
102
103 ##################################################
104 #       Do global macro substitutions            #
105 ##################################################
106
107 # This function is applied to configurations, command lines and data lines in
108 # scripts, and to lines in the files of the aux-var-src and the dnszones-src
109 # directory. It takes one argument: the current test number, or zero when
110 # setting up files before running any tests.
111
112 sub do_substitute{
113 s?\bCALLER\b?$parm_caller?g;
114 s?\bCALLERGROUP\b?$parm_caller_group?g;
115 s?\bCALLER_UID\b?$parm_caller_uid?g;
116 s?\bCALLER_GID\b?$parm_caller_gid?g;
117 s?\bCLAMSOCKET\b?$parm_clamsocket?g;
118 s?\bDIR/?$parm_cwd/?g;
119 s?\bEXIMGROUP\b?$parm_eximgroup?g;
120 s?\bEXIMUSER\b?$parm_eximuser?g;
121 s?\bHOSTIPV4\b?$parm_ipv4?g;
122 s?\bHOSTIPV6\b?$parm_ipv6?g;
123 s?\bHOSTNAME\b?$parm_hostname?g;
124 s?\bPORT_D\b?$parm_port_d?g;
125 s?\bPORT_D2\b?$parm_port_d2?g;
126 s?\bPORT_D3\b?$parm_port_d3?g;
127 s?\bPORT_D4\b?$parm_port_d4?g;
128 s?\bPORT_N\b?$parm_port_n?g;
129 s?\bPORT_S\b?$parm_port_s?g;
130 s?\bTESTNUM\b?$_[0]?g;
131 s?(\b|_)V4NET([\._])?$1$parm_ipv4_test_net$2?g;
132 s?\bV6NET:?$parm_ipv6_test_net:?g;
133 }
134
135
136 ##################################################
137 #     Any state to be preserved across tests     #
138 ##################################################
139
140 my $TEST_STATE = {};
141
142
143 ##################################################
144 #        Subroutine to tidy up and exit          #
145 ##################################################
146
147 # In all cases, we check for any Exim daemons that have been left running, and
148 # kill them. Then remove all the spool data, test output, and the modified Exim
149 # binary if we are ending normally.
150
151 # Arguments:
152 #    $_[0] = 0 for a normal exit; full cleanup done
153 #    $_[0] > 0 for an error exit; no files cleaned up
154 #    $_[0] < 0 for a "die" exit; $_[1] contains a message
155
156 sub tests_exit{
157 my($rc) = $_[0];
158 my($spool);
159
160 # Search for daemon pid files and kill the daemons. We kill with SIGINT rather
161 # than SIGTERM to stop it outputting "Terminated" to the terminal when not in
162 # the background.
163
164 if (exists $TEST_STATE->{exim_pid})
165   {
166   $pid = $TEST_STATE->{exim_pid};
167   print "Tidyup: killing wait-mode daemon pid=$pid\n";
168   system("sudo kill -SIGINT $pid");
169   }
170
171 if (opendir(DIR, "spool"))
172   {
173   my(@spools) = sort readdir(DIR);
174   closedir(DIR);
175   foreach $spool (@spools)
176     {
177     next if $spool !~ /^exim-daemon./;
178     open(PID, "spool/$spool") || die "** Failed to open \"spool/$spool\": $!\n";
179     chomp($pid = <PID>);
180     close(PID);
181     print "Tidyup: killing daemon pid=$pid\n";
182     system("sudo rm -f spool/$spool; sudo kill -SIGINT $pid");
183     }
184   }
185 else
186   { die "** Failed to opendir(\"spool\"): $!\n" unless $!{ENOENT}; }
187
188 # Close the terminal input and remove the test files if all went well, unless
189 # the option to save them is set. Always remove the patched Exim binary. Then
190 # exit normally, or die.
191
192 close(T);
193 system("sudo /bin/rm -rf ./spool test-* ./dnszones/*")
194   if ($rc == 0 && !$save_output);
195
196 system("sudo /bin/rm -rf ./eximdir/*")
197   if (!$save_output);
198
199 print "\nYou were in test $test at the end there.\n\n" if defined $test;
200 exit $rc if ($rc >= 0);
201 die "** runtest error: $_[1]\n";
202 }
203
204
205
206 ##################################################
207 #   Subroutines used by the munging subroutine   #
208 ##################################################
209
210 # This function is used for things like message ids, where we want to generate
211 # more than one value, but keep a consistent mapping throughout.
212 #
213 # Arguments:
214 #   $oldid        the value from the file
215 #   $base         a base string into which we insert a sequence
216 #   $sequence     the address of the current sequence counter
217
218 sub new_value {
219 my($oldid, $base, $sequence) = @_;
220 my($newid) = $cache{$oldid};
221 if (! defined $newid)
222   {
223   $newid = sprintf($base, $$sequence++);
224   $cache{$oldid} = $newid;
225   }
226 return $newid;
227 }
228
229
230 # This is used while munging the output from exim_dumpdb.
231 # May go wrong across DST changes.
232
233 sub date_seconds {
234 my($day,$month,$year,$hour,$min,$sec) =
235   $_[0] =~ /^(\d\d)-(\w\w\w)-(\d{4})\s(\d\d):(\d\d):(\d\d)/;
236 my($mon);
237 if   ($month =~ /Jan/) {$mon = 0;}
238 elsif($month =~ /Feb/) {$mon = 1;}
239 elsif($month =~ /Mar/) {$mon = 2;}
240 elsif($month =~ /Apr/) {$mon = 3;}
241 elsif($month =~ /May/) {$mon = 4;}
242 elsif($month =~ /Jun/) {$mon = 5;}
243 elsif($month =~ /Jul/) {$mon = 6;}
244 elsif($month =~ /Aug/) {$mon = 7;}
245 elsif($month =~ /Sep/) {$mon = 8;}
246 elsif($month =~ /Oct/) {$mon = 9;}
247 elsif($month =~ /Nov/) {$mon = 10;}
248 elsif($month =~ /Dec/) {$mon = 11;}
249 return timelocal($sec,$min,$hour,$day,$mon,$year);
250 }
251
252
253 # This is a subroutine to sort maildir files into time-order. The second field
254 # is the microsecond field, and may vary in length, so must be compared
255 # numerically.
256
257 sub maildirsort {
258 return $a cmp $b if ($a !~ /^\d+\.H\d/ || $b !~ /^\d+\.H\d/);
259 my($x1,$y1) = $a =~ /^(\d+)\.H(\d+)/;
260 my($x2,$y2) = $b =~ /^(\d+)\.H(\d+)/;
261 return ($x1 != $x2)? ($x1 <=> $x2) : ($y1 <=> $y2);
262 }
263
264
265
266 ##################################################
267 #   Subroutine list files below a directory      #
268 ##################################################
269
270 # This is used to build up a list of expected mail files below a certain path
271 # in the directory tree. It has to be recursive in order to deal with multiple
272 # maildir mailboxes.
273
274 sub list_files_below {
275 my($dir) = $_[0];
276 my(@yield) = ();
277 my(@sublist, $file);
278
279 opendir(DIR, $dir) || tests_exit(-1, "Failed to open $dir: $!");
280 @sublist = sort maildirsort readdir(DIR);
281 closedir(DIR);
282
283 foreach $file (@sublist)
284   {
285   next if $file eq "." || $file eq ".." || $file eq "CVS";
286   if (-d "$dir/$file")
287     { @yield = (@yield, list_files_below("$dir/$file")); }
288   else
289     { push @yield, "$dir/$file"; }
290   }
291
292 return @yield;
293 }
294
295
296
297 ##################################################
298 #         Munge a file before comparing          #
299 ##################################################
300
301 # The pre-processing turns all dates, times, Exim versions, message ids, and so
302 # on into standard values, so that the compare works. Perl's substitution with
303 # an expression provides a neat way to do some of these changes.
304
305 # We keep a global associative array for repeatedly turning the same values
306 # into the same standard values throughout the data from a single test.
307 # Message ids get this treatment (can't be made reliable for times), and
308 # times in dumped retry databases are also handled in a special way, as are
309 # incoming port numbers.
310
311 # On entry to the subroutine, the file to write to is already opened with the
312 # name MUNGED. The input file name is the only argument to the subroutine.
313 # Certain actions are taken only when the name contains "stderr", "stdout",
314 # or "log". The yield of the function is 1 if a line matching "*** truncated
315 # ***" is encountered; otherwise it is 0.
316
317 sub munge {
318 my($file) = $_[0];
319 my($extra) = $_[1];
320 my($yield) = 0;
321 my(@saved) = ();
322
323 open(IN, "$file") || tests_exit(-1, "Failed to open $file: $!");
324
325 my($is_log) = $file =~ /log/;
326 my($is_stdout) = $file =~ /stdout/;
327 my($is_stderr) = $file =~ /stderr/;
328
329 # Date pattern
330
331 $date = "\\d{2}-\\w{3}-\\d{4}\\s\\d{2}:\\d{2}:\\d{2}";
332
333 # Pattern for matching pids at start of stderr lines; initially something
334 # that won't match.
335
336 $spid = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
337
338 # Scan the file and make the changes. Near the bottom there are some changes
339 # that are specific to certain file types, though there are also some of those
340 # inline too.
341
342 while(<IN>)
343   {
344 RESET_AFTER_EXTRA_LINE_READ:
345   # Custom munges
346   if ($extra)
347     {
348     next if $extra =~ m%^/%  &&  eval $extra;
349     eval $extra if $extra =~ m/^s/;
350     }
351
352   # Check for "*** truncated ***"
353   $yield = 1 if /\*\*\* truncated \*\*\*/;
354
355   # Replace the name of this host
356   s/\Q$parm_hostname\E/the.local.host.name/g;
357
358   # But convert "name=the.local.host address=127.0.0.1" to use "localhost"
359   s/name=the\.local\.host address=127\.0\.0\.1/name=localhost address=127.0.0.1/g;
360
361   # The name of the shell may vary
362   s/\s\Q$parm_shell\E\b/ ENV_SHELL/;
363
364   # Replace the path to the testsuite directory
365   s?\Q$parm_cwd\E?TESTSUITE?g;
366
367   # Replace the Exim version number (may appear in various places)
368   # patchexim should have fixed this for us
369   #s/(Exim) \d+\.\d+[\w_-]*/$1 x.yz/i;
370
371   # Replace Exim message ids by a unique series
372   s/((?:[^\W_]{6}-){2}[^\W_]{2})
373     /new_value($1, "10Hm%s-0005vi-00", \$next_msgid)/egx;
374
375   # The names of lock files appear in some error and debug messages
376   s/\.lock(\.[-\w]+)+(\.[\da-f]+){2}/.lock.test.ex.dddddddd.pppppppp/;
377
378   # Unless we are in an IPv6 test, replace IPv4 and/or IPv6 in "listening on
379   # port" message, because it is not always the same.
380   s/port (\d+) \([^)]+\)/port $1/g
381     if !$is_ipv6test && m/listening for SMTP(S?) on port/;
382
383   # Challenges in SPA authentication
384   s/TlRMTVNTUAACAAAAAAAAAAAoAAABgg[\w+\/]+/TlRMTVNTUAACAAAAAAAAAAAoAAABggAAAEbBRwqFwwIAAAAAAAAAAAAt1sgAAAAA/;
385
386   # PRVS values
387   s?prvs=([^/]+)/[\da-f]{10}@?prvs=$1/xxxxxxxxxx@?g;    # Old form
388   s?prvs=[\da-f]{10}=([^@]+)@?prvs=xxxxxxxxxx=$1@?g;    # New form
389
390   # Error lines on stdout from SSL contain process id values and file names.
391   # They also contain a source file name and line number, which may vary from
392   # release to release.
393   s/^\d+:error:/pppp:error:/;
394   s/:(?:\/[^\s:]+\/)?([^\/\s]+\.c):\d+:/:$1:dddd:/;
395
396   # There are differences in error messages between OpenSSL versions
397   s/SSL_CTX_set_cipher_list/SSL_connect/;
398
399   # One error test in expansions mentions base 62 or 36
400   s/is not a base (36|62) number/is not a base 36\/62 number/;
401
402   # This message sometimes has a different number of seconds
403   s/forced fail after \d seconds/forced fail after d seconds/;
404
405   # This message may contain a different DBM library name
406   s/Failed to open \S+( \([^\)]+\))? file/Failed to open DBM file/;
407
408   # The message for a non-listening FIFO varies
409   s/:[^:]+: while opening named pipe/: Error: while opening named pipe/;
410
411   # Debugging output of lists of hosts may have different sort keys
412   s/sort=\S+/sort=xx/ if /^\S+ (?:\d+\.){3}\d+ mx=\S+ sort=\S+/;
413
414   # Random local part in callout cache testing
415   s/myhost.test.ex-\d+-testing/myhost.test.ex-dddddddd-testing/;
416
417   # File descriptor numbers may vary
418   s/^writing data block fd=\d+/writing data block fd=dddd/;
419   s/running as transport filter: write=\d+ read=\d+/running as transport filter: write=dddd read=dddd/;
420
421
422   # ======== Dumpdb output ========
423   # This must be before the general date/date munging.
424   # Time data lines, which look like this:
425   # 25-Aug-2000 12:11:37  25-Aug-2000 12:11:37  26-Aug-2000 12:11:37
426   if (/^($date)\s+($date)\s+($date)(\s+\*)?\s*$/)
427     {
428     my($date1,$date2,$date3,$expired) = ($1,$2,$3,$4);
429     $expired = "" if !defined $expired;
430     my($increment) = date_seconds($date3) - date_seconds($date2);
431
432     # We used to use globally unique replacement values, but timing
433     # differences make this impossible. Just show the increment on the
434     # last one.
435
436     printf MUNGED ("first failed = time last try = time2 next try = time2 + %s%s\n",
437       $increment, $expired);
438     next;
439     }
440
441   # more_errno values in exim_dumpdb output which are times
442   s/T:(\S+)\s-22\s(\S+)\s/T:$1 -22 xxxx /;
443
444
445   # ======== Dates and times ========
446
447   # Dates and times are all turned into the same value - trying to turn
448   # them into different ones cannot be done repeatedly because they are
449   # real time stamps generated while running the test. The actual date and
450   # time used was fixed when I first started running automatic Exim tests.
451
452   # Date/time in header lines and SMTP responses
453   s/[A-Z][a-z]{2},\s\d\d?\s[A-Z][a-z]{2}\s\d\d\d\d\s\d\d\:\d\d:\d\d\s[-+]\d{4}
454     /Tue, 2 Mar 1999 09:44:33 +0000/gx;
455
456   # Date/time in logs and in one instance of a filter test
457   s/^\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(\s[+-]\d\d\d\d)?/1999-03-02 09:44:33/gx;
458   s/^Logwrite\s"\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d/Logwrite "1999-03-02 09:44:33/gx;
459
460   # Date/time in message separators
461   s/(?:[A-Z][a-z]{2}\s){2}\d\d\s\d\d:\d\d:\d\d\s\d\d\d\d
462     /Tue Mar 02 09:44:33 1999/gx;
463
464   # Date of message arrival in spool file as shown by -Mvh
465   s/^\d{9,10}\s0$/ddddddddd 0/;
466
467   # Date/time in mbx mailbox files
468   s/\d\d-\w\w\w-\d\d\d\d\s\d\d:\d\d:\d\d\s[-+]\d\d\d\d,/06-Sep-1999 15:52:48 +0100,/gx;
469
470   # Dates/times in debugging output for writing retry records
471   if (/^  first failed=(\d+) last try=(\d+) next try=(\d+) (.*)$/)
472     {
473     my($next) = $3 - $2;
474     $_ = "  first failed=dddd last try=dddd next try=+$next $4\n";
475     }
476   s/^(\s*)now=\d+ first_failed=\d+ next_try=\d+ expired=(\d)/$1now=tttt first_failed=tttt next_try=tttt expired=$2/;
477   s/^(\s*)received_time=\d+ diff=\d+ timeout=(\d+)/$1received_time=tttt diff=tttt timeout=$2/;
478
479   # Time to retry may vary
480   s/time to retry = \S+/time to retry = tttt/;
481   s/retry record exists: age=\S+/retry record exists: age=ttt/;
482   s/failing_interval=\S+ message_age=\S+/failing_interval=ttt message_age=ttt/;
483
484   # Date/time in exim -bV output
485   s/\d\d-[A-Z][a-z]{2}-\d{4}\s\d\d:\d\d:\d\d/07-Mar-2000 12:21:52/g;
486
487   # Time on queue tolerance
488   s/QT=1s/QT=0s/;
489
490   # Eximstats heading
491   s/Exim\sstatistics\sfrom\s\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d\sto\s
492     \d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d/Exim statistics from <time> to <time>/x;
493
494
495   # ======== TLS certificate algorithms ========
496   # Test machines might have various different TLS library versions supporting
497   # different protocols; can't rely upon TLS 1.2's AES256-GCM-SHA384, so we
498   # treat the standard algorithms the same.
499   # So far, have seen:
500   #   TLSv1:AES256-SHA:256
501   #   TLSv1.2:AES256-GCM-SHA384:256
502   #   TLSv1.2:DHE-RSA-AES256-SHA:256
503   #   TLS1.2:DHE_RSA_AES_128_CBC_SHA1:128
504   # We also need to handle the ciphersuite without the TLS part present, for
505   # client-ssl's output.  We also see some older forced ciphersuites, but
506   # negotiating TLS 1.2 instead of 1.0.
507   # Mail headers (...), log-lines X=..., client-ssl output ...
508   # (and \b doesn't match between ' ' and '(' )
509
510   s/( (?: (?:\b|\s) [\(=] ) | \s )TLSv1\.2:/$1TLSv1:/xg;
511   s/\bAES256-GCM-SHA384\b/AES256-SHA/g;
512   s/\bDHE-RSA-AES256-SHA\b/AES256-SHA/g;
513
514   # GnuTLS have seen:
515   #   TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256
516   #   TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128
517   #   TLS1.2:RSA_AES_256_CBC_SHA1:256 (canonical)
518   #   TLS1.2:DHE_RSA_AES_128_CBC_SHA1:128
519   #
520   #   X=TLS1.2:DHE_RSA_AES_256_CBC_SHA256:256
521   #   X=TLS1.2:RSA_AES_256_CBC_SHA1:256
522   #   X=TLS1.1:RSA_AES_256_CBC_SHA1:256
523   #   X=TLS1.0:DHE_RSA_AES_256_CBC_SHA1:256
524   # and as stand-alone cipher:
525   #   ECDHE-RSA-AES256-SHA
526   #   DHE-RSA-AES256-SHA256
527   #   DHE-RSA-AES256-SHA
528   # picking latter as canonical simply because regex easier that way.
529   s/\bDHE_RSA_AES_128_CBC_SHA1:128/RSA_AES_256_CBC_SHA1:256/g;
530   s/TLS1.[012]:((EC)?DHE_)?RSA_AES_(256|128)_(CBC|GCM)_SHA(1|256|384):(256|128)/TLS1.x:xxxxRSA_AES_256_CBC_SHAnnn:256/g;
531   s/\b(ECDHE-RSA-AES256-SHA|DHE-RSA-AES256-SHA256)\b/AES256-SHA/g;
532
533   # GnuTLS library error message changes
534   s/No certificate was found/The peer did not send any certificate/g;
535 #(dodgy test?)  s/\(certificate verification failed\): invalid/\(gnutls_handshake\): The peer did not send any certificate./g;
536   s/\(gnutls_priority_set\): No or insufficient priorities were set/\(gnutls_handshake\): Could not negotiate a supported cipher suite/g;
537
538   # (replace old with new, hoping that old only happens in one situation)
539   s/TLS error on connection to \d{1,3}(.\d{1,3}){3} \[\d{1,3}(.\d{1,3}){3}\] \(gnutls_handshake\): A TLS packet with unexpected length was received./a TLS session is required for ip4.ip4.ip4.ip4 [ip4.ip4.ip4.ip4], but an attempt to start TLS failed/g;
540   s/TLS error on connection from \[127.0.0.1\] \(recv\): A TLS packet with unexpected length was received./TLS error on connection from [127.0.0.1] (recv): The TLS connection was non-properly terminated./g;
541
542
543   # ======== Caller's login, uid, gid, home, gecos ========
544
545   s/\Q$parm_caller_home\E/CALLER_HOME/g;   # NOTE: these must be done
546   s/\b\Q$parm_caller\E\b/CALLER/g;         #       in this order!
547   s/\b\Q$parm_caller_group\E\b/CALLER/g;   # In case group name different
548
549   s/\beuid=$parm_caller_uid\b/euid=CALLER_UID/g;
550   s/\begid=$parm_caller_gid\b/egid=CALLER_GID/g;
551
552   s/\buid=$parm_caller_uid\b/uid=CALLER_UID/g;
553   s/\bgid=$parm_caller_gid\b/gid=CALLER_GID/g;
554
555   s/\bname=$parm_caller_gecos\b/name=CALLER_GECOS/g;
556
557   # When looking at spool files with -Mvh, we will find not only the caller
558   # login, but also the uid and gid. It seems that $) in some Perls gives all
559   # the auxiliary gids as well, so don't bother checking for that.
560
561   s/^CALLER $> \d+$/CALLER UID GID/;
562
563   # There is one case where the caller's login is forced to something else,
564   # in order to test the processing of logins that contain spaces. Weird what
565   # some people do, isn't it?
566
567   s/^spaced user $> \d+$/CALLER UID GID/;
568
569
570   # ======== Exim's login ========
571   # For messages received by the daemon, this is in the -H file, which some
572   # tests inspect. For bounce messages, this will appear on the U= lines in
573   # logs and also after Received: and in addresses. In one pipe test it appears
574   # after "Running as:". It also appears in addresses, and in the names of lock
575   # files.
576
577   s/U=$parm_eximuser/U=EXIMUSER/;
578   s/user=$parm_eximuser/user=EXIMUSER/;
579   s/login=$parm_eximuser/login=EXIMUSER/;
580   s/Received: from $parm_eximuser /Received: from EXIMUSER /;
581   s/Running as: $parm_eximuser/Running as: EXIMUSER/;
582   s/\b$parm_eximuser@/EXIMUSER@/;
583   s/\b$parm_eximuser\.lock\./EXIMUSER.lock./;
584
585   s/\beuid=$parm_exim_uid\b/euid=EXIM_UID/g;
586   s/\begid=$parm_exim_gid\b/egid=EXIM_GID/g;
587
588   s/\buid=$parm_exim_uid\b/uid=EXIM_UID/g;
589   s/\bgid=$parm_exim_gid\b/gid=EXIM_GID/g;
590
591   s/^$parm_eximuser $parm_exim_uid $parm_exim_gid/EXIMUSER EXIM_UID EXIM_GID/;
592
593
594   # ======== General uids, gids, and pids ========
595   # Note: this must come after munges for caller's and exim's uid/gid
596
597   # These are for systems where long int is 64
598   s/\buid=4294967295/uid=-1/;
599   s/\beuid=4294967295/euid=-1/;
600   s/\bgid=4294967295/gid=-1/;
601   s/\begid=4294967295/egid=-1/;
602
603   s/\bgid=\d+/gid=gggg/;
604   s/\begid=\d+/egid=gggg/;
605   s/\bpid=\d+/pid=pppp/;
606   s/\buid=\d+/uid=uuuu/;
607   s/\beuid=\d+/euid=uuuu/;
608   s/set_process_info:\s+\d+/set_process_info: pppp/;
609   s/queue run pid \d+/queue run pid ppppp/;
610   s/process \d+ running as transport filter/process pppp running as transport filter/;
611   s/process \d+ writing to transport filter/process pppp writing to transport filter/;
612   s/reading pipe for subprocess \d+/reading pipe for subprocess pppp/;
613   s/remote delivery process \d+ ended/remote delivery process pppp ended/;
614
615   # Pid in temp file in appendfile transport
616   s"test-mail/temp\.\d+\."test-mail/temp.pppp.";
617
618   # Optional pid in log lines
619   s/^(\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d)(\s[+-]\d\d\d\d|)(\s\[\d+\])/
620     "$1$2 [" . new_value($3, "%s", \$next_pid) . "]"/gxe;
621
622   # Detect a daemon stderr line with a pid and save the pid for subsequent
623   # removal from following lines.
624   $spid = $1 if /^(\s*\d+) (?:listening|LOG: MAIN|(?:daemon_smtp_port|local_interfaces) overridden by)/;
625   s/^$spid //;
626
627   # Queue runner waiting messages
628   s/waiting for children of \d+/waiting for children of pppp/;
629   s/waiting for (\S+) \(\d+\)/waiting for $1 (pppp)/;
630
631   # ======== Port numbers ========
632   # Incoming port numbers may vary, but not in daemon startup line.
633
634   s/^Port: (\d+)/"Port: " . new_value($1, "%s", \$next_port)/e;
635   s/\(port=(\d+)/"(port=" . new_value($1, "%s", \$next_port)/e;
636
637   # This handles "connection from" and the like, when the port is given
638   if (!/listening for SMTP on/ && !/Connecting to/ && !/=>/ && !/->/
639       && !/\*>/ && !/Connection refused/)
640     {
641     s/\[([a-z\d:]+|\d+(?:\.\d+){3})\]:(\d+)/"[".$1."]:".new_value($2,"%s",\$next_port)/ie;
642     }
643
644   # Port in host address in spool file output from -Mvh
645   s/^-host_address (.*)\.\d+/-host_address $1.9999/;
646
647
648   # ======== Local IP addresses ========
649   # The amount of space between "host" and the address in verification output
650   # depends on the length of the host name. We therefore reduce it to one space
651   # for all of them.
652   # Also, the length of space at the end of the host line is dependent
653   # on the length of the longest line, so strip it also on otherwise
654   # un-rewritten lines like localhost
655
656   s/^\s+host\s(\S+)\s+(\S+)/  host $1 $2/;
657   s/^\s+(host\s\S+\s\S+)\s+(port=.*)/  host $1 $2/;
658   s/^\s+(host\s\S+\s\S+)\s+(?=MX=)/  $1 /;
659   s/host\s\Q$parm_ipv4\E\s\[\Q$parm_ipv4\E\]/host ipv4.ipv4.ipv4.ipv4 [ipv4.ipv4.ipv4.ipv4]/;
660   s/host\s\Q$parm_ipv6\E\s\[\Q$parm_ipv6\E\]/host ip6:ip6:ip6:ip6:ip6:ip6:ip6:ip6 [ip6:ip6:ip6:ip6:ip6:ip6:ip6:ip6]/;
661   s/\b\Q$parm_ipv4\E\b/ip4.ip4.ip4.ip4/g;
662   s/(^|\W)\K\Q$parm_ipv6\E/ip6:ip6:ip6:ip6:ip6:ip6:ip6:ip6/g;
663   s/\b\Q$parm_ipv4r\E\b/ip4-reverse/g;
664   s/(^|\W)\K\Q$parm_ipv6r\E/ip6-reverse/g;
665   s/^(\s+host\s\S+\s+\[\S+\]) +$/$1 /;
666
667
668   # ======== Test network IP addresses ========
669   s/(\b|_)\Q$parm_ipv4_test_net\E(?=\.\d+\.\d+\.\d+\b|_|\.rbl|\.in-addr|\.test\.again\.dns)/$1V4NET/g;
670   s/\b\Q$parm_ipv6_test_net\E(?=:[\da-f]+:[\da-f]+:[\da-f]+)/V6NET/gi;
671
672
673   # ======== IP error numbers and messages ========
674   # These vary between operating systems
675   s/Can't assign requested address/Network Error/;
676   s/Cannot assign requested address/Network Error/;
677   s/Operation timed out/Connection timed out/;
678   s/Address family not supported by protocol family/Network Error/;
679   s/Network is unreachable/Network Error/;
680   s/Invalid argument/Network Error/;
681
682   s/\(\d+\): Network/(dd): Network/;
683   s/\(\d+\): Connection refused/(dd): Connection refused/;
684   s/\(\d+\): Connection timed out/(dd): Connection timed out/;
685   s/\d+ 65 Connection refused/dd 65 Connection refused/;
686   s/\d+ 321 Connection timed out/dd 321 Connection timed out/;
687
688
689   # ======== Other error numbers ========
690   s/errno=\d+/errno=dd/g;
691
692
693   # ======== Output from ls ========
694   # Different operating systems use different spacing on long output
695   #s/ +/ /g if /^[-rwd]{10} /;
696   # (Bug 1226) SUSv3 allows a trailing printable char for modified access method control.
697   # Handle only the Gnu and MacOS space, dot, plus and at-sign.  A full [[:graph:]]
698   # unfortunately matches a non-ls linefull of dashes.
699   # Allow the case where we've already picked out the file protection bits.
700   if (s/^([-d](?:[-r][-w][-SsTtx]){3})[.+@]?( +|$)/$1$2/) {
701     s/ +/ /g;
702   }
703
704
705   # ======== Message sizes =========
706   # Message sizes vary, owing to different logins and host names that get
707   # automatically inserted. I can't think of any way of even approximately
708   # comparing these.
709
710   s/([\s,])S=\d+\b/$1S=sss/;
711   s/:S\d+\b/:Ssss/;
712   s/^(\s*\d+m\s+)\d+(\s+[a-z0-9-]{16} <)/$1sss$2/i if $is_stdout;
713   s/\sSIZE=\d+\b/ SIZE=ssss/;
714   s/\ssize=\d+\b/ size=sss/ if $is_stderr;
715   s/old size = \d+\b/old size = sssss/;
716   s/message size = \d+\b/message size = sss/;
717   s/this message = \d+\b/this message = sss/;
718   s/Size of headers = \d+/Size of headers = sss/;
719   s/sum=(?!0)\d+/sum=dddd/;
720   s/(?<=sum=dddd )count=(?!0)\d+\b/count=dd/;
721   s/(?<=sum=0 )count=(?!0)\d+\b/count=dd/;
722   s/,S is \d+\b/,S is ddddd/;
723   s/\+0100,\d+;/+0100,ddd;/;
724   s/\(\d+ bytes written\)/(ddd bytes written)/;
725   s/added '\d+ 1'/added 'ddd 1'/;
726   s/Received\s+\d+/Received               nnn/;
727   s/Delivered\s+\d+/Delivered              nnn/;
728
729
730   # ======== Values in spool space failure message ========
731   s/space=\d+ inodes=[+-]?\d+/space=xxxxx inodes=xxxxx/;
732
733
734   # ======== Filter sizes ========
735   # The sizes of filter files may vary because of the substitution of local
736   # filenames, logins, etc.
737
738   s/^\d+(?= bytes read from )/ssss/;
739
740
741   # ======== OpenSSL error messages ========
742   # Different releases of the OpenSSL libraries seem to give different error
743   # numbers, or handle specific bad conditions in different ways, leading to
744   # different wording in the error messages, so we cannot compare them.
745
746   s/(TLS error on connection (?:from|to) .*? \(SSL_\w+\): error:)(.*)/$1 <<detail omitted>>/;
747
748   # ======== Maildir things ========
749   # timestamp output in maildir processing
750   s/(timestamp=|\(timestamp_only\): )\d+/$1ddddddd/g;
751
752   # maildir delivery files appearing in log lines (in cases of error)
753   s/writing to(?: file)? tmp\/\d+\.[^.]+\.(\S+)/writing to tmp\/MAILDIR.$1/;
754
755   s/renamed tmp\/\d+\.[^.]+\.(\S+) as new\/\d+\.[^.]+\.(\S+)/renamed tmp\/MAILDIR.$1 as new\/MAILDIR.$1/;
756
757   # Maildir file names in general
758   s/\b\d+\.H\d+P\d+\b/dddddddddd.HddddddPddddd/;
759
760   # Maildirsize data
761   while (/^\d+S,\d+C\s*$/)
762     {
763     print MUNGED;
764     while (<IN>)
765       {
766       last if !/^\d+ \d+\s*$/;
767       print MUNGED "ddd d\n";
768       }
769     last if !defined $_;
770     }
771   last if !defined $_;
772
773
774   # ======== Output from the "fd" program about open descriptors ========
775   # The statuses seem to be different on different operating systems, but
776   # at least we'll still be checking the number of open fd's.
777
778   s/max fd = \d+/max fd = dddd/;
779   s/status=0 RDONLY/STATUS/g;
780   s/status=1 WRONLY/STATUS/g;
781   s/status=2 RDWR/STATUS/g;
782
783
784   # ======== Contents of spool files ========
785   # A couple of tests dump the contents of the -H file. The length fields
786   # will be wrong because of different user names, etc.
787   s/^\d\d\d(?=[PFS*])/ddd/;
788
789
790   # ========= Exim lookups ==================
791   # Lookups have a char which depends on the number of lookup types compiled in,
792   # in stderr output.  Replace with a "0".  Recognising this while avoiding
793   # other output is fragile; perhaps the debug output should be revised instead.
794   s%(?<!sqlite)(?<!lsearch\*@)(?<!lsearch\*)(?<!lsearch)[0-?]TESTSUITE/aux-fixed/%0TESTSUITE/aux-fixed/%g;
795
796   # ==========================================================
797   # Some munging is specific to the specific file types
798
799   # ======== stdout ========
800
801   if ($is_stdout)
802     {
803     # Skip translate_ip_address and use_classresources in -bP output because
804     # they aren't always there.
805
806     next if /translate_ip_address =/;
807     next if /use_classresources/;
808
809     # In certain filter tests, remove initial filter lines because they just
810     # clog up by repetition.
811
812     if ($rmfiltertest)
813       {
814       next if /^(Sender\staken\sfrom|
815                  Return-path\scopied\sfrom|
816                  Sender\s+=|
817                  Recipient\s+=)/x;
818       if (/^Testing \S+ filter/)
819         {
820         $_ = <IN>;    # remove blank line
821         next;
822         }
823       }
824     }
825
826   # ======== stderr ========
827
828   elsif ($is_stderr)
829     {
830     # The very first line of debugging output will vary
831
832     s/^Exim version .*/Exim version x.yz ..../;
833
834     # Debugging lines for Exim terminations
835
836     s/(?<=^>>>>>>>>>>>>>>>> Exim pid=)\d+(?= terminating)/pppp/;
837
838     # IP address lookups use gethostbyname() when IPv6 is not supported,
839     # and gethostbyname2() or getipnodebyname() when it is.
840
841     s/\bgethostbyname2?|\bgetipnodebyname/get[host|ipnode]byname[2]/;
842
843     # drop gnutls version strings
844     next if /GnuTLS compile-time version: \d+[\.\d]+$/;
845     next if /GnuTLS runtime version: \d+[\.\d]+$/;
846
847     # drop openssl version strings
848     next if /OpenSSL compile-time version: OpenSSL \d+[\.\da-z]+/;
849     next if /OpenSSL runtime version: OpenSSL \d+[\.\da-z]+/;
850
851     # drop lookups
852     next if /^Lookups \(built-in\):/;
853     next if /^Loading lookup modules from/;
854     next if /^Loaded \d+ lookup modules/;
855     next if /^Total \d+ lookups/;
856
857     # drop compiler information
858     next if /^Compiler:/;
859
860     # and the ugly bit
861     # different libraries will have different numbers (possibly 0) of follow-up
862     # lines, indenting with more data
863     if (/^Library version:/) {
864       while (1) {
865         $_ = <IN>;
866         next if /^\s/;
867         goto RESET_AFTER_EXTRA_LINE_READ;
868       }
869     }
870
871     # drop other build-time controls emitted for debugging
872     next if /^WHITELIST_D_MACROS:/;
873     next if /^TRUSTED_CONFIG_LIST:/;
874
875     # As of Exim 4.74, we log when a setgid fails; because we invoke Exim
876     # with -be, privileges will have been dropped, so this will always
877     # be the case
878     next if /^changing group to \d+ failed: Operation not permitted/;
879
880     # We might not keep this check; rather than change all the tests, just
881     # ignore it as long as it succeeds; then we only need to change the
882     # TLS tests where tls_require_ciphers has been set.
883     if (m{^changed uid/gid: calling tls_validate_require_cipher}) {
884       my $discard = <IN>;
885       next;
886     }
887     next if /^tls_validate_require_cipher child \d+ ended: status=0x0/;
888
889     # We invoke Exim with -D, so we hit this new messag as of Exim 4.73:
890     next if /^macros_trusted overridden to true by whitelisting/;
891
892     # We have to omit the localhost ::1 address so that all is well in
893     # the IPv4-only case.
894
895     print MUNGED "MUNGED: ::1 will be omitted in what follows\n"
896       if (/looked up these IP addresses/);
897     next if /name=localhost address=::1/;
898
899     # drop pdkim debugging header
900     next if /^PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<+$/;
901
902     # Various other IPv6 lines must be omitted too
903
904     next if /using host_fake_gethostbyname for \S+ \(IPv6\)/;
905     next if /get\[host\|ipnode\]byname\[2\]\(af=inet6\)/;
906     next if /DNS lookup of \S+ \(AAAA\) using fakens/;
907     next if / in dns_ipv4_lookup?/;
908
909     if (/DNS lookup of \S+ \(AAAA\) gave NO_DATA/)
910       {
911       $_= <IN>;     # Gets "returning DNS_NODATA"
912       next;
913       }
914
915     # Skip tls_advertise_hosts and hosts_require_tls checks when the options
916     # are unset, because tls ain't always there.
917
918     next if /in\s(?:tls_advertise_hosts\?|hosts_require_tls\?)
919                 \sno\s\(option\sunset\)/x;
920
921     # Skip auxiliary group lists because they will vary.
922
923     next if /auxiliary group list:/;
924
925     # Skip "extracted from gecos field" because the gecos field varies
926
927     next if /extracted from gecos field/;
928
929     # Skip "waiting for data on socket" and "read response data: size=" lines
930     # because some systems pack more stuff into packets than others.
931
932     next if /waiting for data on socket/;
933     next if /read response data: size=/;
934
935     # If Exim is compiled with readline support but it can't find the library
936     # to load, there will be an extra debug line. Omit it.
937
938     next if /failed to load readline:/;
939
940     # Some DBM libraries seem to make DBM files on opening with O_RDWR without
941     # O_CREAT; other's don't. In the latter case there is some debugging output
942     # which is not present in the former. Skip the relevant lines (there are
943     # two of them).
944
945     if (/TESTSUITE\/spool\/db\/\S+ appears not to exist: trying to create/)
946       {
947       $_ = <IN>;
948       next;
949       }
950
951     # Some tests turn on +expand debugging to check on expansions.
952     # Unfortunately, the Received: expansion varies, depending on whether TLS
953     # is compiled or not. So we must remove the relevant debugging if it is.
954
955     if (/^condition: def:tls_cipher/)
956       {
957       while (<IN>) { last if /^condition: def:sender_address/; }
958       }
959     elsif (/^expanding: Received: /)
960       {
961       while (<IN>) { last if !/^\s/; }
962       }
963
964     # When Exim is checking the size of directories for maildir, it uses
965     # the check_dir_size() function to scan directories. Of course, the order
966     # of the files that are obtained using readdir() varies from system to
967     # system. We therefore buffer up debugging lines from check_dir_size()
968     # and sort them before outputting them.
969
970     if (/^check_dir_size:/ || /^skipping TESTSUITE\/test-mail\//)
971       {
972       push @saved, $_;
973       }
974     else
975       {
976       if (@saved > 0)
977         {
978         print MUNGED "MUNGED: the check_dir_size lines have been sorted " .
979           "to ensure consistency\n";
980         @saved = sort(@saved);
981         print MUNGED @saved;
982         @saved = ();
983         }
984
985       # Skip some lines that Exim puts out at the start of debugging output
986       # because they will be different in different binaries.
987
988       print MUNGED
989         unless (/^Berkeley DB: / ||
990                 /^Probably (?:Berkeley DB|ndbm|GDBM)/ ||
991                 /^Authenticators:/ ||
992                 /^Lookups:/ ||
993                 /^Support for:/ ||
994                 /^Routers:/ ||
995                 /^Transports:/ ||
996                 /^log selectors =/ ||
997                 /^cwd=/ ||
998                 /^Fixed never_users:/ ||
999                 /^Size of off_t:/
1000                 );
1001       }
1002
1003     next;
1004     }
1005
1006   # ======== All files other than stderr ========
1007
1008   print MUNGED;
1009   }
1010
1011 close(IN);
1012 return $yield;
1013 }
1014
1015
1016
1017
1018 ##################################################
1019 #        Subroutine to interact with caller      #
1020 ##################################################
1021
1022 # Arguments: [0] the prompt string
1023 #            [1] if there is a U in the prompt and $force_update is true
1024 #            [2] if there is a C in the prompt and $force_continue is true
1025 # Returns:   nothing (it sets $_)
1026
1027 sub interact{
1028 print $_[0];
1029 if ($_[1]) { $_ = "u"; print "... update forced\n"; }
1030   elsif ($_[2]) { $_ = "c"; print "... continue forced\n"; }
1031   else { $_ = <T>; }
1032 }
1033
1034
1035
1036 ##################################################
1037 #    Subroutine to log in force_continue mode    #
1038 ##################################################
1039
1040 # In force_continue mode, we just want a terse output to a statically
1041 # named logfile.  If multiple files in same batch (stdout, stderr, etc)
1042 # all have mismatches, it will log multiple times.
1043 #
1044 # Arguments: [0] the logfile to append to
1045 #            [1] the testno that failed
1046 # Returns:   nothing
1047
1048
1049
1050 sub log_failure {
1051   my $logfile = shift();
1052   my $testno  = shift();
1053   my $detail  = shift() || '';
1054   if ( open(my $fh, ">>", $logfile) ) {
1055     print $fh "Test $testno $detail failed\n";
1056     close $fh;
1057   }
1058 }
1059
1060
1061
1062 ##################################################
1063 #    Subroutine to compare one output file       #
1064 ##################################################
1065
1066 # When an Exim server is part of the test, its output is in separate files from
1067 # an Exim client. The server data is concatenated with the client data as part
1068 # of the munging operation.
1069 #
1070 # Arguments:  [0] the name of the main raw output file
1071 #             [1] the name of the server raw output file or undef
1072 #             [2] where to put the munged copy
1073 #             [3] the name of the saved file
1074 #             [4] TRUE if this is a log file whose deliveries must be sorted
1075 #             [5] optionally, a custom munge command
1076 #
1077 # Returns:    0 comparison succeeded or differences to be ignored
1078 #             1 comparison failed; files may have been updated (=> re-compare)
1079 #
1080 # Does not return if the user replies "Q" to a prompt.
1081
1082 sub check_file{
1083 my($rf,$rsf,$mf,$sf,$sortfile,$extra) = @_;
1084
1085 # If there is no saved file, the raw files must either not exist, or be
1086 # empty. The test ! -s is TRUE if the file does not exist or is empty.
1087
1088 if (! -e $sf)
1089   {
1090   return 0 if (! -s $rf && (! defined $rsf || ! -s $rsf));
1091
1092   print "\n";
1093   print "** $rf is not empty\n" if (-s $rf);
1094   print "** $rsf is not empty\n" if (defined $rsf && -s $rsf);
1095
1096   for (;;)
1097     {
1098     print "Continue, Show, or Quit? [Q] ";
1099     $_ = $force_continue ? "c" : <T>;
1100     tests_exit(1) if /^q?$/i;
1101     log_failure($log_failed_filename, $testno, $rf) if (/^c$/i && $force_continue);
1102     return 0 if /^c$/i;
1103     last if (/^s$/);
1104     }
1105
1106   foreach $f ($rf, $rsf)
1107     {
1108     if (defined $f && -s $f)
1109       {
1110       print "\n";
1111       print "------------ $f -----------\n"
1112         if (defined $rf && -s $rf && defined $rsf && -s $rsf);
1113       system("$more '$f'");
1114       }
1115     }
1116
1117   print "\n";
1118   for (;;)
1119     {
1120     interact("Continue, Update & retry, Quit? [Q] ", $force_update, $force_continue);
1121     tests_exit(1) if /^q?$/i;
1122     log_failure($log_failed_filename, $testno, $rsf) if (/^c$/i && $force_continue);
1123     return 0 if /^c$/i;
1124     last if (/^u$/i);
1125     }
1126   }
1127
1128 # Control reaches here if either (a) there is a saved file ($sf), or (b) there
1129 # was a request to create a saved file. First, create the munged file from any
1130 # data that does exist.
1131
1132 open(MUNGED, ">$mf") || tests_exit(-1, "Failed to open $mf: $!");
1133 my($truncated) = munge($rf, $extra) if -e $rf;
1134 if (defined $rsf && -e $rsf)
1135   {
1136   print MUNGED "\n******** SERVER ********\n";
1137   $truncated |= munge($rsf, $extra);
1138   }
1139 close(MUNGED);
1140
1141 # If a saved file exists, do the comparison. There are two awkward cases:
1142 #
1143 # If "*** truncated ***" was found in the new file, it means that a log line
1144 # was overlong, and truncated. The problem is that it may be truncated at
1145 # different points on different systems, because of different user name
1146 # lengths. We reload the file and the saved file, and remove lines from the new
1147 # file that precede "*** truncated ***" until we reach one that matches the
1148 # line that precedes it in the saved file.
1149 #
1150 # If $sortfile is set, we are dealing with a mainlog file where the deliveries
1151 # for an individual message might vary in their order from system to system, as
1152 # a result of parallel deliveries. We load the munged file and sort sequences
1153 # of delivery lines.
1154
1155 if (-e $sf)
1156   {
1157   # Deal with truncated text items
1158
1159   if ($truncated)
1160     {
1161     my(@munged, @saved, $i, $j, $k);
1162
1163     open(MUNGED, "$mf") || tests_exit(-1, "Failed to open $mf: $!");
1164     @munged = <MUNGED>;
1165     close(MUNGED);
1166     open(SAVED, "$sf") || tests_exit(-1, "Failed to open $sf: $!");
1167     @saved = <SAVED>;
1168     close(SAVED);
1169
1170     $j = 0;
1171     for ($i = 0; $i < @munged; $i++)
1172       {
1173       if ($munged[$i] =~ /\*\*\* truncated \*\*\*/)
1174         {
1175         for (; $j < @saved; $j++)
1176           { last if $saved[$j] =~ /\*\*\* truncated \*\*\*/; }
1177         last if $j >= @saved;     # not found in saved
1178
1179         for ($k = $i - 1; $k >= 0; $k--)
1180           { last if $munged[$k] eq $saved[$j - 1]; }
1181
1182         last if $k <= 0;          # failed to find previous match
1183         splice @munged, $k + 1, $i - $k - 1;
1184         $i = $k + 1;
1185         }
1186       }
1187
1188     open(MUNGED, ">$mf") || tests_exit(-1, "Failed to open $mf: $!");
1189     for ($i = 0; $i < @munged; $i++)
1190       { print MUNGED $munged[$i]; }
1191     close(MUNGED);
1192     }
1193
1194   # Deal with log sorting
1195
1196   if ($sortfile)
1197     {
1198     my(@munged, $i, $j);
1199
1200     open(MUNGED, "$mf") || tests_exit(-1, "Failed to open $mf: $!");
1201     @munged = <MUNGED>;
1202     close(MUNGED);
1203
1204     for ($i = 0; $i < @munged; $i++)
1205       {
1206       if ($munged[$i] =~ /^[-\d]{10}\s[:\d]{8}\s[-A-Za-z\d]{16}\s[-=*]>/)
1207         {
1208         for ($j = $i + 1; $j < @munged; $j++)
1209           {
1210           last if $munged[$j] !~
1211             /^[-\d]{10}\s[:\d]{8}\s[-A-Za-z\d]{16}\s[-=*]>/;
1212           }
1213         @temp = splice(@munged, $i, $j - $i);
1214         @temp = sort(@temp);
1215         splice(@munged, $i, 0, @temp);
1216         }
1217       }
1218
1219     open(MUNGED, ">$mf") || tests_exit(-1, "Failed to open $mf: $!");
1220     print MUNGED "**NOTE: The delivery lines in this file have been sorted.\n";
1221     for ($i = 0; $i < @munged; $i++)
1222       { print MUNGED $munged[$i]; }
1223     close(MUNGED);
1224     }
1225
1226   # Do the comparison
1227
1228   return 0 if (system("$cf '$mf' '$sf' >test-cf") == 0);
1229
1230   # Handle comparison failure
1231
1232   print "** Comparison of $mf with $sf failed";
1233   system("$more test-cf");
1234
1235   print "\n";
1236   for (;;)
1237     {
1238     interact("Continue, Retry, Update & retry, Quit? [Q] ", $force_update, $force_continue);
1239     tests_exit(1) if /^q?$/i;
1240     log_failure($log_failed_filename, $testno, $sf) if (/^c$/i && $force_continue);
1241     return 0 if /^c$/i;
1242     return 1 if /^r$/i;
1243     last if (/^u$/i);
1244     }
1245   }
1246
1247 # Update or delete the saved file, and give the appropriate return code.
1248
1249 if (-s $mf)
1250   { tests_exit(-1, "Failed to cp $mf $sf") if system("cp '$mf' '$sf'") != 0; }
1251 else
1252   { tests_exit(-1, "Failed to unlink $sf") if !unlink($sf); }
1253
1254 return 1;
1255 }
1256
1257
1258
1259 ##################################################
1260 # Custom munges
1261 # keyed by name of munge; value is a ref to a hash
1262 # which is keyed by file, value a string to look for.
1263 # Usable files are:
1264 #  paniclog, rejectlog, mainlog, stdout, stderr, msglog, mail
1265 # Search strings starting with 's' do substitutions;
1266 # with '/' do line-skips.
1267 ##################################################
1268 $munges =
1269   { 'dnssec' =>
1270     { 'stderr' => '/^Reverse DNS security status: unverified\n/', },
1271
1272     'gnutls_unexpected' =>
1273     { 'mainlog' => '/\(recv\): A TLS packet with unexpected length was received./', },
1274
1275     'gnutls_handshake' =>
1276     { 'mainlog' => 's/\(gnutls_handshake\): Error in the push function/\(gnutls_handshake\): A TLS packet with unexpected length was received/', },
1277
1278   };
1279
1280
1281 ##################################################
1282 #    Subroutine to check the output of a test    #
1283 ##################################################
1284
1285 # This function is called when the series of subtests is complete. It makes
1286 # use of check_file(), whose arguments are:
1287 #
1288 #  [0] the name of the main raw output file
1289 #  [1] the name of the server raw output file or undef
1290 #  [2] where to put the munged copy
1291 #  [3] the name of the saved file
1292 #  [4] TRUE if this is a log file whose deliveries must be sorted
1293 #  [5] an optional custom munge command
1294 #
1295 # Arguments: Optionally, name of a custom munge to run.
1296 # Returns:   0 if the output compared equal
1297 #            1 if re-run needed (files may have been updated)
1298
1299 sub check_output{
1300 my($mungename) = $_[0];
1301 my($yield) = 0;
1302 my($munge) = $munges->{$mungename} if defined $mungename;
1303
1304 $yield = 1 if check_file("spool/log/paniclog",
1305                        "spool/log/serverpaniclog",
1306                        "test-paniclog-munged",
1307                        "paniclog/$testno", 0,
1308                        $munge->{'paniclog'});
1309
1310 $yield = 1 if check_file("spool/log/rejectlog",
1311                        "spool/log/serverrejectlog",
1312                        "test-rejectlog-munged",
1313                        "rejectlog/$testno", 0,
1314                        $munge->{'rejectlog'});
1315
1316 $yield = 1 if check_file("spool/log/mainlog",
1317                        "spool/log/servermainlog",
1318                        "test-mainlog-munged",
1319                        "log/$testno", $sortlog,
1320                        $munge->{'mainlog'});
1321
1322 if (!$stdout_skip)
1323   {
1324   $yield = 1 if check_file("test-stdout",
1325                        "test-stdout-server",
1326                        "test-stdout-munged",
1327                        "stdout/$testno", 0,
1328                        $munge->{'stdout'});
1329   }
1330
1331 if (!$stderr_skip)
1332   {
1333   $yield = 1 if check_file("test-stderr",
1334                        "test-stderr-server",
1335                        "test-stderr-munged",
1336                        "stderr/$testno", 0,
1337                        $munge->{'stderr'});
1338   }
1339
1340 # Compare any delivered messages, unless this test is skipped.
1341
1342 if (! $message_skip)
1343   {
1344   my($msgno) = 0;
1345
1346   # Get a list of expected mailbox files for this script. We don't bother with
1347   # directories, just the files within them.
1348
1349   foreach $oldmail (@oldmails)
1350     {
1351     next unless $oldmail =~ /^mail\/$testno\./;
1352     print ">> EXPECT $oldmail\n" if $debug;
1353     $expected_mails{$oldmail} = 1;
1354     }
1355
1356   # If there are any files in test-mail, compare them. Note that "." and
1357   # ".." are automatically omitted by list_files_below().
1358
1359   @mails = list_files_below("test-mail");
1360
1361   foreach $mail (@mails)
1362     {
1363     next if $mail eq "test-mail/oncelog";
1364
1365     $saved_mail = substr($mail, 10);               # Remove "test-mail/"
1366     $saved_mail =~ s/^$parm_caller(\/|$)/CALLER/;  # Convert caller name
1367
1368     if ($saved_mail =~ /(\d+\.[^.]+\.)/)
1369       {
1370       $msgno++;
1371       $saved_mail =~ s/(\d+\.[^.]+\.)/$msgno./gx;
1372       }
1373
1374     print ">> COMPARE $mail mail/$testno.$saved_mail\n" if $debug;
1375     $yield = 1 if check_file($mail, undef, "test-mail-munged",
1376       "mail/$testno.$saved_mail", 0,
1377       $munge->{'mail'});
1378     delete $expected_mails{"mail/$testno.$saved_mail"};
1379     }
1380
1381   # Complain if not all expected mails have been found
1382
1383   if (scalar(keys %expected_mails) != 0)
1384     {
1385     foreach $key (keys %expected_mails)
1386       { print "** no test file found for $key\n"; }
1387
1388     for (;;)
1389       {
1390       interact("Continue, Update & retry, or Quit? [Q] ", $force_update, $force_continue);
1391       tests_exit(1) if /^q?$/i;
1392       log_failure($log_failed_filename, $testno, "missing email") if (/^c$/i && $force_continue);
1393       last if /^c$/i;
1394
1395       # For update, we not only have to unlink the file, but we must also
1396       # remove it from the @oldmails vector, as otherwise it will still be
1397       # checked for when we re-run the test.
1398
1399       if (/^u$/i)
1400         {
1401         foreach $key (keys %expected_mails)
1402           {
1403           my($i);
1404           tests_exit(-1, "Failed to unlink $key") if !unlink("$key");
1405           for ($i = 0; $i < @oldmails; $i++)
1406             {
1407             if ($oldmails[$i] eq $key)
1408               {
1409               splice @oldmails, $i, 1;
1410               last;
1411               }
1412             }
1413           }
1414         last;
1415         }
1416       }
1417     }
1418   }
1419
1420 # Compare any remaining message logs, unless this test is skipped.
1421
1422 if (! $msglog_skip)
1423   {
1424   # Get a list of expected msglog files for this test
1425
1426   foreach $oldmsglog (@oldmsglogs)
1427     {
1428     next unless $oldmsglog =~ /^$testno\./;
1429     $expected_msglogs{$oldmsglog} = 1;
1430     }
1431
1432   # If there are any files in spool/msglog, compare them. However, we have
1433   # to munge the file names because they are message ids, which are
1434   # time dependent.
1435
1436   if (opendir(DIR, "spool/msglog"))
1437     {
1438     @msglogs = sort readdir(DIR);
1439     closedir(DIR);
1440
1441     foreach $msglog (@msglogs)
1442       {
1443       next if ($msglog eq "." || $msglog eq ".." || $msglog eq "CVS");
1444       ($munged_msglog = $msglog) =~
1445         s/((?:[^\W_]{6}-){2}[^\W_]{2})
1446           /new_value($1, "10Hm%s-0005vi-00", \$next_msgid)/egx;
1447       $yield = 1 if check_file("spool/msglog/$msglog", undef,
1448         "test-msglog-munged", "msglog/$testno.$munged_msglog", 0,
1449         $munge->{'msglog'});
1450       delete $expected_msglogs{"$testno.$munged_msglog"};
1451       }
1452     }
1453
1454   # Complain if not all expected msglogs have been found
1455
1456   if (scalar(keys %expected_msglogs) != 0)
1457     {
1458     foreach $key (keys %expected_msglogs)
1459       {
1460       print "** no test msglog found for msglog/$key\n";
1461       ($msgid) = $key =~ /^\d+\.(.*)$/;
1462       foreach $cachekey (keys %cache)
1463         {
1464         if ($cache{$cachekey} eq $msgid)
1465           {
1466           print "** original msgid $cachekey\n";
1467           last;
1468           }
1469         }
1470       }
1471
1472     for (;;)
1473       {
1474       interact("Continue, Update, or Quit? [Q] ", $force_update, $force_continue);
1475       tests_exit(1) if /^q?$/i;
1476       log_failure($log_failed_filename, $testno, "missing msglog") if (/^c$/i && $force_continue);
1477       last if /^c$/i;
1478       if (/^u$/i)
1479         {
1480         foreach $key (keys %expected_msglogs)
1481           {
1482           tests_exit(-1, "Failed to unlink msglog/$key")
1483             if !unlink("msglog/$key");
1484           }
1485         last;
1486         }
1487       }
1488     }
1489   }
1490
1491 return $yield;
1492 }
1493
1494
1495
1496 ##################################################
1497 #     Subroutine to run one "system" command     #
1498 ##################################################
1499
1500 # We put this in a subroutine so that the command can be reflected when
1501 # debugging.
1502 #
1503 # Argument: the command to be run
1504 # Returns:  nothing
1505
1506 sub run_system {
1507 my($cmd) = $_[0];
1508 if ($debug)
1509   {
1510   my($prcmd) = $cmd;
1511   $prcmd =~ s/; /;\n>> /;
1512   print ">> $prcmd\n";
1513   }
1514 system("$cmd");
1515 }
1516
1517
1518
1519 ##################################################
1520 #      Subroutine to run one script command      #
1521 ##################################################
1522
1523 # The <SCRIPT> file is open for us to read an optional return code line,
1524 # followed by the command line and any following data lines for stdin. The
1525 # command line can be continued by the use of \. Data lines are not continued
1526 # in this way. In all lines, the following substutions are made:
1527 #
1528 # DIR    => the current directory
1529 # CALLER => the caller of this script
1530 #
1531 # Arguments: the current test number
1532 #            reference to the subtest number, holding previous value
1533 #            reference to the expected return code value
1534 #            reference to where to put the command name (for messages)
1535 #            auxilliary information returned from a previous run
1536 #
1537 # Returns:   0 the commmand was executed inline, no subprocess was run
1538 #            1 a non-exim command was run and waited for
1539 #            2 an exim command was run and waited for
1540 #            3 a command was run and not waited for (daemon, server, exim_lock)
1541 #            4 EOF was encountered after an initial return code line
1542 # Optionally alse a second parameter, a hash-ref, with auxilliary information:
1543 #            exim_pid: pid of a run process
1544 #            munge: name of a post-script results munger
1545
1546 sub run_command{
1547 my($testno) = $_[0];
1548 my($subtestref) = $_[1];
1549 my($commandnameref) = $_[3];
1550 my($aux_info) = $_[4];
1551 my($yield) = 1;
1552
1553 if (/^(\d+)\s*$/)                # Handle unusual return code
1554   {
1555   my($r) = $_[2];
1556   $$r = $1 << 8;
1557   $_ = <SCRIPT>;
1558   return 4 if !defined $_;       # Missing command
1559   $lineno++;
1560   }
1561
1562 chomp;
1563 $wait_time = 0;
1564
1565 # Handle concatenated command lines
1566
1567 s/\s+$//;
1568 while (substr($_, -1) eq"\\")
1569   {
1570   my($temp);
1571   $_ = substr($_, 0, -1);
1572   chomp($temp = <SCRIPT>);
1573   if (defined $temp)
1574     {
1575     $lineno++;
1576     $temp =~ s/\s+$//;
1577     $temp =~ s/^\s+//;
1578     $_ .= $temp;
1579     }
1580   }
1581
1582 # Do substitutions
1583
1584 do_substitute($testno);
1585 if ($debug) { printf ">> $_\n"; }
1586
1587 # Pass back the command name (for messages)
1588
1589 ($$commandnameref) = /^(\S+)/;
1590
1591 # Here follows code for handling the various different commands that are
1592 # supported by this script. The first group of commands are all freestanding
1593 # in that they share no common code and are not followed by any data lines.
1594
1595
1596 ###################
1597 ###################
1598
1599 # The "dbmbuild" command runs exim_dbmbuild. This is used both to test the
1600 # utility and to make DBM files for testing DBM lookups.
1601
1602 if (/^dbmbuild\s+(\S+)\s+(\S+)/)
1603   {
1604   run_system("(./eximdir/exim_dbmbuild $parm_cwd/$1 $parm_cwd/$2;" .
1605          "echo exim_dbmbuild exit code = \$?)" .
1606          ">>test-stdout");
1607   return 1;
1608   }
1609
1610
1611 # The "dump" command runs exim_dumpdb. On different systems, the output for
1612 # some types of dump may appear in a different order because it's just hauled
1613 # out of the DBM file. We can solve this by sorting. Ignore the leading
1614 # date/time, as it will be flattened later during munging.
1615
1616 if (/^dump\s+(\S+)/)
1617   {
1618   my($which) = $1;
1619   my(@temp);
1620   print ">> ./eximdir/exim_dumpdb $parm_cwd/spool $which\n" if $debug;
1621   open(IN, "./eximdir/exim_dumpdb $parm_cwd/spool $which |");
1622   @temp = <IN>;
1623   close(IN);
1624   if ($which eq "callout")
1625     {
1626     @temp = sort {
1627                  my($aa) = substr $a, 21;
1628                  my($bb) = substr $b, 21;
1629                  return $aa cmp $bb;
1630                  } @temp;
1631     }
1632   open(OUT, ">>test-stdout");
1633   print OUT "+++++++++++++++++++++++++++\n";
1634   print OUT @temp;
1635   close(OUT);
1636   return 1;
1637   }
1638
1639
1640 # The "echo" command is a way of writing comments to the screen.
1641
1642 if (/^echo\s+(.*)$/)
1643   {
1644   print "$1\n";
1645   return 0;
1646   }
1647
1648
1649 # The "exim_lock" command runs exim_lock in the same manner as "server",
1650 # but it doesn't use any input.
1651
1652 if (/^exim_lock\s+(.*)$/)
1653   {
1654   $cmd = "./eximdir/exim_lock $1 >>test-stdout";
1655   $server_pid = open SERVERCMD, "|$cmd" ||
1656     tests_exit(-1, "Failed to run $cmd\n");
1657
1658   # This gives the process time to get started; otherwise the next
1659   # process may not find it there when it expects it.
1660
1661   select(undef, undef, undef, 0.1);
1662   return 3;
1663   }
1664
1665
1666 # The "exinext" command runs exinext
1667
1668 if (/^exinext\s+(.*)/)
1669   {
1670   run_system("(./eximdir/exinext " .
1671     "-DEXIM_PATH=$parm_cwd/eximdir/exim " .
1672     "-C $parm_cwd/test-config $1;" .
1673     "echo exinext exit code = \$?)" .
1674     ">>test-stdout");
1675   return 1;
1676   }
1677
1678
1679 # The "exigrep" command runs exigrep on the current mainlog
1680
1681 if (/^exigrep\s+(.*)/)
1682   {
1683   run_system("(./eximdir/exigrep " .
1684     "$1 $parm_cwd/spool/log/mainlog;" .
1685     "echo exigrep exit code = \$?)" .
1686     ">>test-stdout");
1687   return 1;
1688   }
1689
1690
1691 # The "eximstats" command runs eximstats on the current mainlog
1692
1693 if (/^eximstats\s+(.*)/)
1694   {
1695   run_system("(./eximdir/eximstats " .
1696     "$1 $parm_cwd/spool/log/mainlog;" .
1697     "echo eximstats exit code = \$?)" .
1698     ">>test-stdout");
1699   return 1;
1700   }
1701
1702
1703 # The "gnutls" command makes a copy of saved GnuTLS parameter data in the
1704 # spool directory, to save Exim from re-creating it each time.
1705
1706 if (/^gnutls/)
1707   {
1708   my $gen_fn = "spool/gnutls-params-$gnutls_dh_bits_normal";
1709   run_system "sudo cp -p aux-fixed/gnutls-params $gen_fn;" .
1710          "sudo chown $parm_eximuser:$parm_eximgroup $gen_fn;" .
1711          "sudo chmod 0400 $gen_fn";
1712   return 1;
1713   }
1714
1715
1716 # The "killdaemon" command should ultimately follow the starting of any Exim
1717 # daemon with the -bd option. We kill with SIGINT rather than SIGTERM to stop
1718 # it outputting "Terminated" to the terminal when not in the background.
1719
1720 if (/^killdaemon/)
1721   {
1722   my $return_extra = {};
1723   if (exists $aux_info->{exim_pid})
1724     {
1725     $pid = $aux_info->{exim_pid};
1726     $return_extra->{exim_pid} = undef;
1727     print ">> killdaemon: recovered pid $pid\n" if $debug;
1728     if ($pid)
1729       {
1730       run_system("sudo /bin/kill -SIGINT $pid");
1731       wait;
1732       }
1733     } else {
1734     $pid = `cat $parm_cwd/spool/exim-daemon.*`;
1735     if ($pid)
1736       {
1737       run_system("sudo /bin/kill -SIGINT $pid");
1738       close DAEMONCMD;                                   # Waits for process
1739       }
1740     }
1741     run_system("sudo /bin/rm -f spool/exim-daemon.*");
1742   return (1, $return_extra);
1743   }
1744
1745
1746 # The "millisleep" command is like "sleep" except that its argument is in
1747 # milliseconds, thus allowing for a subsecond sleep, which is, in fact, all it
1748 # is used for.
1749
1750 elsif (/^millisleep\s+(.*)$/)
1751   {
1752   select(undef, undef, undef, $1/1000);
1753   return 0;
1754   }
1755
1756
1757 # The "munge" command selects one of a hardwired set of test-result modifications
1758 # to be made before result compares are run agains the golden set.  This lets
1759 # us account for test-system dependent things which only affect a few, but known,
1760 # test-cases.
1761 # Currently only the last munge takes effect.
1762
1763 if (/^munge\s+(.*)$/)
1764   {
1765   return (0, { munge => $1 });
1766   }
1767
1768
1769 # The "sleep" command does just that. For sleeps longer than 1 second we
1770 # tell the user what's going on.
1771
1772 if (/^sleep\s+(.*)$/)
1773   {
1774   if ($1 == 1)
1775     {
1776     sleep(1);
1777     }
1778   else
1779     {
1780     printf("  Test %d sleep $1 ", $$subtestref);
1781     for (1..$1)
1782       {
1783       print ".";
1784       sleep(1);
1785       }
1786     printf("\r  Test %d                            $cr", $$subtestref);
1787     }
1788   return 0;
1789   }
1790
1791
1792 # Various Unix management commands are recognized
1793
1794 if (/^(ln|ls|du|mkdir|mkfifo|touch|cp|cat)\s/ ||
1795     /^sudo (rmdir|rm|chown|chmod)\s/)
1796   {
1797   run_system("$_ >>test-stdout 2>>test-stderr");
1798   return 1;
1799   }
1800
1801
1802
1803 ###################
1804 ###################
1805
1806 # The next group of commands are also freestanding, but they are all followed
1807 # by data lines.
1808
1809
1810 # The "server" command starts up a script-driven server that runs in parallel
1811 # with the following exim command. Therefore, we want to run a subprocess and
1812 # not yet wait for it to complete. The waiting happens after the next exim
1813 # command, triggered by $server_pid being non-zero. The server sends its output
1814 # to a different file. The variable $server_opts, if not empty, contains
1815 # options to disable IPv4 or IPv6 if necessary.
1816
1817 if (/^server\s+(.*)$/)
1818   {
1819   $cmd = "./bin/server $server_opts $1 >>test-stdout-server";
1820   print ">> $cmd\n" if ($debug);
1821   $server_pid = open SERVERCMD, "|$cmd" || tests_exit(-1, "Failed to run $cmd");
1822   SERVERCMD->autoflush(1);
1823   print ">> Server pid is $server_pid\n" if $debug;
1824   while (<SCRIPT>)
1825     {
1826     $lineno++;
1827     last if /^\*{4}\s*$/;
1828     print SERVERCMD;
1829     }
1830   print SERVERCMD "++++\n"; # Send end to server; can't send EOF yet
1831                             # because close() waits for the process.
1832
1833   # This gives the server time to get started; otherwise the next
1834   # process may not find it there when it expects it.
1835
1836   select(undef, undef, undef, 0.5);
1837   return 3;
1838   }
1839
1840
1841 # The "write" command is a way of creating files of specific sizes for
1842 # buffering tests, or containing specific data lines from within the script
1843 # (rather than hold lots of little files). The "catwrite" command does the
1844 # same, but it also copies the lines to test-stdout.
1845
1846 if (/^(cat)?write\s+(\S+)(?:\s+(.*))?\s*$/)
1847   {
1848   my($cat) = defined $1;
1849   @sizes = ();
1850   @sizes = split /\s+/, $3 if defined $3;
1851   open FILE, ">$2" || tests_exit(-1, "Failed to open \"$2\": $!");
1852
1853   if ($cat)
1854     {
1855     open CAT, ">>test-stdout" ||
1856       tests_exit(-1, "Failed to open test-stdout: $!");
1857     print CAT "==========\n";
1858     }
1859
1860   if (scalar @sizes > 0)
1861     {
1862     # Pre-data
1863
1864     while (<SCRIPT>)
1865       {
1866       $lineno++;
1867       last if /^\+{4}\s*$/;
1868       print FILE;
1869       print CAT if $cat;
1870       }
1871
1872     # Sized data
1873
1874     while (scalar @sizes > 0)
1875       {
1876       ($count,$len,$leadin) = (shift @sizes) =~ /(\d+)x(\d+)(?:=(.*))?/;
1877       $leadin = "" if !defined $leadin;
1878       $leadin =~ s/_/ /g;
1879       $len -= length($leadin) + 1;
1880       while ($count-- > 0)
1881         {
1882         print FILE $leadin, "a" x $len, "\n";
1883         print CAT $leadin, "a" x $len, "\n" if $cat;
1884         }
1885       }
1886     }
1887
1888   # Post data, or only data if no sized data
1889
1890   while (<SCRIPT>)
1891     {
1892     $lineno++;
1893     last if /^\*{4}\s*$/;
1894     print FILE;
1895     print CAT if $cat;
1896     }
1897   close FILE;
1898
1899   if ($cat)
1900     {
1901     print CAT "==========\n";
1902     close CAT;
1903     }
1904
1905   return 0;
1906   }
1907
1908
1909 ###################
1910 ###################
1911
1912 # From this point on, script commands are implemented by setting up a shell
1913 # command in the variable $cmd. Shared code to run this command and handle its
1914 # input and output follows.
1915
1916 # The "client", "client-gnutls", and "client-ssl" commands run a script-driven
1917 # program that plays the part of an email client. We also have the availability
1918 # of running Perl for doing one-off special things. Note that all these
1919 # commands expect stdin data to be supplied.
1920
1921 if (/^client/ || /^(sudo\s+)?perl\b/)
1922   {
1923   s"client"./bin/client";
1924   $cmd = "$_ >>test-stdout 2>>test-stderr";
1925   }
1926
1927 # For the "exim" command, replace the text "exim" with the path for the test
1928 # binary, plus -D options to pass over various parameters, and a -C option for
1929 # the testing configuration file. When running in the test harness, Exim does
1930 # not drop privilege when -C and -D options are present. To run the exim
1931 # command as root, we use sudo.
1932
1933 elsif (/^([A-Z_]+=\S+\s+)?(\d+)?\s*(sudo\s+)?exim(_\S+)?\s+(.*)$/)
1934   {
1935   $args = $5;
1936   my($envset) = (defined $1)? $1      : "";
1937   my($sudo)   = (defined $3)? "sudo " : "";
1938   my($special)= (defined $4)? $4      : "";
1939   $wait_time  = (defined $2)? $2      : 0;
1940
1941   # Return 2 rather than 1 afterwards
1942
1943   $yield = 2;
1944
1945   # Update the test number
1946
1947   $$subtestref = $$subtestref + 1;
1948   printf("  Test %d       $cr", $$subtestref);
1949
1950   # Copy the configuration file, making the usual substitutions.
1951
1952   open (IN, "$parm_cwd/confs/$testno") ||
1953     tests_exit(-1, "Couldn't open $parm_cwd/confs/$testno: $!\n");
1954   open (OUT, ">test-config") ||
1955     tests_exit(-1, "Couldn't open test-config: $!\n");
1956   while (<IN>)
1957     {
1958     do_substitute($testno);
1959     print OUT;
1960     }
1961   close(IN);
1962   close(OUT);
1963
1964   # The string $msg1 in args substitutes the message id of the first
1965   # message on the queue, and so on. */
1966
1967   if ($args =~ /\$msg/)
1968     {
1969     my($listcmd) = "$parm_cwd/eximdir/exim -bp " .
1970                    "-DEXIM_PATH=$parm_cwd/eximdir/exim " .
1971                    "-C $parm_cwd/test-config |";
1972     print ">> Getting queue list from:\n>>    $listcmd\n" if ($debug);
1973     open (QLIST, $listcmd) || tests_exit(-1, "Couldn't run \"exim -bp\": $!\n");
1974     my(@msglist) = ();
1975     while (<QLIST>) { push (@msglist, $1) if /^\s*\d+[smhdw]\s+\S+\s+(\S+)/; }
1976     close(QLIST);
1977
1978     # Done backwards just in case there are more than 9
1979
1980     my($i);
1981     for ($i = @msglist; $i > 0; $i--) { $args =~ s/\$msg$i/$msglist[$i-1]/g; }
1982     if ( $args =~ /\$msg\d/ )
1983       {
1984       tests_exit(-1, "Not enough messages in spool, for test $testno line $lineno\n");
1985       }
1986     }
1987
1988   # If -d is specified in $optargs, remove it from $args; i.e. let
1989   # the command line for runtest override. Then run Exim.
1990
1991   $args =~ s/(?:^|\s)-d\S*// if $optargs =~ /(?:^|\s)-d/;
1992
1993   $cmd = "$envset$sudo$parm_cwd/eximdir/exim$special$optargs " .
1994          "-DEXIM_PATH=$parm_cwd/eximdir/exim$special " .
1995          "-C $parm_cwd/test-config $args " .
1996          ">>test-stdout 2>>test-stderr";
1997
1998   # If the command is starting an Exim daemon, we run it in the same
1999   # way as the "server" command above, that is, we don't want to wait
2000   # for the process to finish. That happens when "killdaemon" is obeyed later
2001   # in the script. We also send the stderr output to test-stderr-server. The
2002   # daemon has its log files put in a different place too (by configuring with
2003   # log_file_path). This requires the  directory to be set up in advance.
2004   #
2005   # There are also times when we want to run a non-daemon version of Exim
2006   # (e.g. a queue runner) with the server configuration. In this case,
2007   # we also define -DNOTDAEMON.
2008
2009   if ($cmd =~ /\s-DSERVER=server\s/ && $cmd !~ /\s-DNOTDAEMON\s/)
2010     {
2011     if ($debug) { printf ">> daemon: $cmd\n"; }
2012     run_system("sudo mkdir spool/log 2>/dev/null");
2013     run_system("sudo chown $parm_eximuser:$parm_eximgroup spool/log");
2014
2015     # Before running the command, convert the -bd option into -bdf so that an
2016     # Exim daemon doesn't double fork. This means that when we wait close
2017     # DAEMONCMD, it waits for the correct process. Also, ensure that the pid
2018     # file is written to the spool directory, in case the Exim binary was
2019     # built with PID_FILE_PATH pointing somewhere else.
2020
2021     $cmd =~ s!\s-bd\s! -bdf -oP $parm_cwd/spool/exim-daemon.pid !;
2022     print ">> |${cmd}-server\n" if ($debug);
2023     open DAEMONCMD, "|${cmd}-server" || tests_exit(-1, "Failed to run $cmd");
2024     DAEMONCMD->autoflush(1);
2025     while (<SCRIPT>) { $lineno++; last if /^\*{4}\s*$/; }   # Ignore any input
2026     select(undef, undef, undef, 0.3);             # Let the daemon get going
2027     return 3;                                     # Don't wait
2028     }
2029   elsif ($cmd =~ /\s-DSERVER=wait:(\d+)\s/)
2030     {
2031     my $listen_port = $1;
2032     my $waitmode_sock = new FileHandle;
2033     if ($debug) { printf ">> wait-mode daemon: $cmd\n"; }
2034     run_system("sudo mkdir spool/log 2>/dev/null");
2035     run_system("sudo chown $parm_eximuser:$parm_eximgroup spool/log");
2036
2037     my ($s_ip,$s_port) = ('127.0.0.1', $listen_port);
2038     my $sin = sockaddr_in($s_port, inet_aton($s_ip))
2039         or die "** Failed packing $s_ip:$s_port\n";
2040     socket($waitmode_sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
2041         or die "** Unable to open socket $s_ip:$s_port: $!\n";
2042     setsockopt($waitmode_sock, SOL_SOCKET, SO_REUSEADDR, 1)
2043         or die "** Unable to setsockopt(SO_REUSEADDR): $!\n";
2044     bind($waitmode_sock, $sin)
2045         or die "** Unable to bind socket ($s_port): $!\n";
2046     listen($waitmode_sock, 5);
2047     my $pid = fork();
2048     if (not defined $pid) { die "** fork failed: $!\n" }
2049     if (not $pid) {
2050       close(STDIN);
2051       open(STDIN, "<&", $waitmode_sock) or die "** dup sock to stdin failed: $!\n";
2052       close($waitmode_sock);
2053       print "[$$]>> ${cmd}-server\n" if ($debug);
2054       exec "exec ${cmd}-server";
2055       exit(1);
2056     }
2057     while (<SCRIPT>) { $lineno++; last if /^\*{4}\s*$/; }   # Ignore any input
2058     select(undef, undef, undef, 0.3);             # Let the daemon get going
2059     return (3, { exim_pid => $pid });             # Don't wait
2060     }
2061   }
2062
2063
2064 # Unknown command
2065
2066 else { tests_exit(-1, "Command unrecognized in line $lineno: $_"); }
2067
2068
2069 # Run the command, with stdin connected to a pipe, and write the stdin data
2070 # to it, with appropriate substitutions. If a line ends with \NONL\, chop off
2071 # the terminating newline (and the \NONL\). If the command contains
2072 # -DSERVER=server add "-server" to the command, where it will adjoin the name
2073 # for the stderr file. See comment above about the use of -DSERVER.
2074
2075 $stderrsuffix = ($cmd =~ /\s-DSERVER=server\s/)? "-server" : "";
2076 print ">> |${cmd}${stderrsuffix}\n" if ($debug);
2077 open CMD, "|${cmd}${stderrsuffix}" || tests_exit(1, "Failed to run $cmd");
2078
2079 CMD->autoflush(1);
2080 while (<SCRIPT>)
2081   {
2082   $lineno++;
2083   last if /^\*{4}\s*$/;
2084   do_substitute($testno);
2085   if (/^(.*)\\NONL\\\s*$/) { print CMD $1; } else { print CMD; }
2086   }
2087
2088 # For timeout tests, wait before closing the pipe; we expect a
2089 # SIGPIPE error in this case.
2090
2091 if ($wait_time > 0)
2092   {
2093   printf("  Test %d sleep $wait_time ", $$subtestref);
2094   while ($wait_time-- > 0)
2095     {
2096     print ".";
2097     sleep(1);
2098     }
2099   printf("\r  Test %d                                       $cr", $$subtestref);
2100   }
2101
2102 $sigpipehappened = 0;
2103 close CMD;                # Waits for command to finish
2104 return $yield;            # Ran command and waited
2105 }
2106
2107
2108
2109
2110 ###############################################################################
2111 ###############################################################################
2112
2113 # Here beginneth the Main Program ...
2114
2115 ###############################################################################
2116 ###############################################################################
2117
2118
2119 autoflush STDOUT 1;
2120 print "Exim tester $testversion\n";
2121
2122
2123 ##################################################
2124 #      Some tests check created file modes       #
2125 ##################################################
2126
2127 umask 022;
2128
2129
2130 ##################################################
2131 #       Check for the "less" command             #
2132 ##################################################
2133
2134 $more = "more" if system("which less >/dev/null 2>&1") != 0;
2135
2136
2137
2138 ##################################################
2139 #        Check for sudo access to root           #
2140 ##################################################
2141
2142 print "You need to have sudo access to root to run these tests. Checking ...\n";
2143 if (system("sudo date >/dev/null") != 0)
2144   {
2145   die "** Test for sudo failed: testing abandoned.\n";
2146   }
2147 else
2148   {
2149   print "Test for sudo OK\n";
2150   }
2151
2152
2153
2154 ##################################################
2155 #      See if an Exim binary has been given      #
2156 ##################################################
2157
2158 # If the first character of the first argument is '/', the argument is taken
2159 # as the path to the binary.
2160
2161 $parm_exim = (@ARGV > 0 && $ARGV[0] =~ m?^/?)? shift @ARGV : "";
2162 print "Exim binary is $parm_exim\n" if $parm_exim ne "";
2163
2164
2165
2166 ##################################################
2167 # Sort out options and which tests are to be run #
2168 ##################################################
2169
2170 # There are a few possible options for the test script itself; after these, any
2171 # options are passed on to Exim calls within the tests. Typically, this is used
2172 # to turn on Exim debugging while setting up a test.
2173
2174 while (@ARGV > 0 && $ARGV[0] =~ /^-/)
2175   {
2176   my($arg) = shift @ARGV;
2177   if ($optargs eq "")
2178     {
2179     if ($arg eq "-DEBUG")  { $debug = 1; $cr = "\n"; next; }
2180     if ($arg eq "-DIFF")   { $cf = "diff -u"; next; }
2181     if ($arg eq "-CONTINUE"){$force_continue = 1;
2182                              $more = "cat";
2183                              next; }
2184     if ($arg eq "-UPDATE") { $force_update = 1; next; }
2185     if ($arg eq "-NOIPV4") { $have_ipv4 = 0; next; }
2186     if ($arg eq "-NOIPV6") { $have_ipv6 = 0; next; }
2187     if ($arg eq "-KEEP")   { $save_output = 1; next; }
2188     }
2189   $optargs .= " $arg";
2190   }
2191
2192 # Any subsequent arguments are a range of test numbers.
2193
2194 if (@ARGV > 0)
2195   {
2196   $test_end = $test_start = $ARGV[0];
2197   $test_end = $ARGV[1] if (@ARGV > 1);
2198   $test_end = ($test_start >= 9000)? $test_special_top : $test_top
2199     if $test_end eq "+";
2200   die "** Test numbers out of order\n" if ($test_end < $test_start);
2201   }
2202
2203
2204 ##################################################
2205 #      Make the command's directory current      #
2206 ##################################################
2207
2208 # After doing so, we find its absolute path name.
2209
2210 $cwd = $0;
2211 $cwd = '.' if ($cwd !~ s|/[^/]+$||);
2212 chdir($cwd) || die "** Failed to chdir to \"$cwd\": $!\n";
2213 $parm_cwd = Cwd::getcwd();
2214
2215
2216 ##################################################
2217 #     Search for an Exim binary to test          #
2218 ##################################################
2219
2220 # If an Exim binary hasn't been provided, try to find one. We can handle the
2221 # case where exim-testsuite is installed alongside Exim source directories. For
2222 # PH's private convenience, if there's a directory just called "exim4", that
2223 # takes precedence; otherwise exim-snapshot takes precedence over any numbered
2224 # releases.
2225
2226 if ($parm_exim eq "")
2227   {
2228   my($use_srcdir) = "";
2229
2230   opendir DIR, ".." || die "** Failed to opendir \"..\": $!\n";
2231   while ($f = readdir(DIR))
2232     {
2233     my($srcdir);
2234
2235     # Try this directory if it is "exim4" or if it is exim-snapshot or exim-n.m
2236     # possibly followed by -RCx where n.m is greater than any previously tried
2237     # directory. Thus, we should choose the highest version of Exim that has
2238     # been compiled.
2239
2240     if ($f eq "exim4" || $f eq "exim-snapshot")
2241       { $srcdir = $f; }
2242     else
2243       { $srcdir = $f
2244         if ($f =~ /^exim-\d+\.\d+(-RC\d+)?$/ && $f gt $use_srcdir); }
2245
2246     # Look for a build directory with a binary in it. If we find a binary,
2247     # accept this source directory.
2248
2249     if ($srcdir)
2250       {
2251       opendir SRCDIR, "../$srcdir" ||
2252         die "** Failed to opendir \"$cwd/../$srcdir\": $!\n";
2253       while ($f = readdir(SRCDIR))
2254         {
2255         if ($f =~ /^build-/ && -e "../$srcdir/$f/exim")
2256           {
2257           $use_srcdir = $srcdir;
2258           $parm_exim = "$cwd/../$srcdir/$f/exim";
2259           $parm_exim =~ s'/[^/]+/\.\./'/';
2260           last;
2261           }
2262         }
2263       closedir(SRCDIR);
2264       }
2265
2266     # If we have found "exim4" or "exim-snapshot", that takes precedence.
2267     # Otherwise, continue to see if there's a later version.
2268
2269     last if $use_srcdir eq "exim4" || $use_srcdir eq "exim-snapshot";
2270     }
2271   closedir(DIR);
2272   print "Exim binary found in $parm_exim\n" if $parm_exim ne "";
2273   }
2274
2275 # If $parm_exim is still empty, ask the caller
2276
2277 if ($parm_exim eq "")
2278   {
2279   print "** Did not find an Exim binary to test\n";
2280   for ($i = 0; $i < 5; $i++)
2281     {
2282     my($trybin);
2283     print "** Enter pathname for Exim binary: ";
2284     chomp($trybin = <STDIN>);
2285     if (-e $trybin)
2286       {
2287       $parm_exim = $trybin;
2288       last;
2289       }
2290     else
2291       {
2292       print "** $trybin does not exist\n";
2293       }
2294     }
2295   die "** Too many tries\n" if $parm_exim eq "";
2296   }
2297
2298
2299
2300 ##################################################
2301 #          Find what is in the binary            #
2302 ##################################################
2303
2304 # deal with TRUSTED_CONFIG_LIST restrictions
2305 unlink("$parm_cwd/test-config") if -e "$parm_cwd/test-config";
2306 symlink("$parm_cwd/confs/0000", "$parm_cwd/test-config")
2307   or die "Unable to link initial config into place: $!\n";
2308
2309 print("Probing with config file: $parm_cwd/test-config\n");
2310 open(EXIMINFO, "$parm_exim -d -C $parm_cwd/test-config -DDIR=$parm_cwd " .
2311                "-bP exim_user exim_group|") ||
2312   die "** Cannot run $parm_exim: $!\n";
2313 while(<EXIMINFO>)
2314   {
2315   $parm_eximuser = $1 if /^exim_user = (.*)$/;
2316   $parm_eximgroup = $1 if /^exim_group = (.*)$/;
2317   }
2318 close(EXIMINFO);
2319
2320 if (defined $parm_eximuser)
2321   {
2322   if ($parm_eximuser =~ /^\d+$/) { $parm_exim_uid = $parm_eximuser; }
2323     else { $parm_exim_uid = getpwnam($parm_eximuser); }
2324   }
2325 else
2326   {
2327   print "Unable to extract exim_user from binary.\n";
2328   print "Check if Exim refused to run; if so, consider:\n";
2329   print "  TRUSTED_CONFIG_LIST ALT_CONFIG_PREFIX WHITELIST_D_MACROS\n";
2330   die "Failing to get information from binary.\n";
2331   }
2332
2333 if (defined $parm_eximgroup)
2334   {
2335   if ($parm_eximgroup =~ /^\d+$/) { $parm_exim_gid = $parm_eximgroup; }
2336     else { $parm_exim_gid = getgrnam($parm_eximgroup); }
2337   }
2338
2339 open(EXIMINFO, "$parm_exim -bV -C $parm_cwd/test-config -DDIR=$parm_cwd |") ||
2340   die "** Cannot run $parm_exim: $!\n";
2341
2342 print "-" x 78, "\n";
2343
2344 while (<EXIMINFO>)
2345   {
2346   my(@temp);
2347
2348   if (/^Exim version/) { print; }
2349
2350   elsif (/^Size of off_t: (\d+)/)
2351     {
2352     print;
2353     $have_largefiles = 1 if $1 > 4;
2354     die "** Size of off_t > 32 which seems improbable, not running tests\n"
2355         if ($1 > 32);
2356     }
2357
2358   elsif (/^Support for: (.*)/)
2359     {
2360     print;
2361     @temp = split /(\s+)/, $1;
2362     push(@temp, ' ');
2363     %parm_support = @temp;
2364     }
2365
2366   elsif (/^Lookups \(built-in\): (.*)/)
2367     {
2368     print;
2369     @temp = split /(\s+)/, $1;
2370     push(@temp, ' ');
2371     %parm_lookups = @temp;
2372     }
2373
2374   elsif (/^Authenticators: (.*)/)
2375     {
2376     print;
2377     @temp = split /(\s+)/, $1;
2378     push(@temp, ' ');
2379     %parm_authenticators = @temp;
2380     }
2381
2382   elsif (/^Routers: (.*)/)
2383     {
2384     print;
2385     @temp = split /(\s+)/, $1;
2386     push(@temp, ' ');
2387     %parm_routers = @temp;
2388     }
2389
2390   # Some transports have options, e.g. appendfile/maildir. For those, ensure
2391   # that the basic transport name is set, and then the name with each of the
2392   # options.
2393
2394   elsif (/^Transports: (.*)/)
2395     {
2396     print;
2397     @temp = split /(\s+)/, $1;
2398     my($i,$k);
2399     push(@temp, ' ');
2400     %parm_transports = @temp;
2401     foreach $k (keys %parm_transports)
2402       {
2403       if ($k =~ "/")
2404         {
2405         @temp = split /\//, $k;
2406         $parm_transports{"$temp[0]"} = " ";
2407         for ($i = 1; $i < @temp; $i++)
2408           { $parm_transports{"$temp[0]/$temp[$i]"} = " "; }
2409         }
2410       }
2411     }
2412   }
2413 close(EXIMINFO);
2414 print "-" x 78, "\n";
2415
2416 unlink("$parm_cwd/test-config");
2417
2418 ##################################################
2419 #    Check for SpamAssassin and ClamAV           #
2420 ##################################################
2421
2422 # These are crude tests. If they aren't good enough, we'll have to improve
2423 # them, for example by actually passing a message through spamc or clamscan.
2424
2425 if (defined $parm_support{'Content_Scanning'})
2426   {
2427   my $sock = new FileHandle;
2428
2429   if (system("spamc -h 2>/dev/null >/dev/null") == 0)
2430     {
2431     print "The spamc command works:\n";
2432
2433     # This test for an active SpamAssassin is courtesy of John Jetmore.
2434     # The tests are hard coded to localhost:783, so no point in making
2435     # this test flexible like the clamav test until the test scripts are
2436     # changed.  spamd doesn't have the nice PING/PONG protoccol that
2437     # clamd does, but it does respond to errors in an informative manner,
2438     # so use that.
2439
2440     my($sint,$sport) = ('127.0.0.1',783);
2441     eval
2442       {
2443       my $sin = sockaddr_in($sport, inet_aton($sint))
2444           or die "** Failed packing $sint:$sport\n";
2445       socket($sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
2446           or die "** Unable to open socket $sint:$sport\n";
2447
2448       local $SIG{ALRM} =
2449           sub { die "** Timeout while connecting to socket $sint:$sport\n"; };
2450       alarm(5);
2451       connect($sock, $sin)
2452           or die "** Unable to connect to socket $sint:$sport\n";
2453       alarm(0);
2454
2455       select((select($sock), $| = 1)[0]);
2456       print $sock "bad command\r\n";
2457
2458       $SIG{ALRM} =
2459           sub { die "** Timeout while reading from socket $sint:$sport\n"; };
2460       alarm(10);
2461       my $res = <$sock>;
2462       alarm(0);
2463
2464       $res =~ m|^SPAMD/|
2465           or die "** Did not get SPAMD from socket $sint:$sport. "
2466                 ."It said: $res\n";
2467       };
2468     alarm(0);
2469     if($@)
2470       {
2471       print "  $@";
2472       print "  Assume SpamAssassin (spamd) is not running\n";
2473       }
2474     else
2475       {
2476       $parm_running{'SpamAssassin'} = ' ';
2477       print "  SpamAssassin (spamd) seems to be running\n";
2478       }
2479     }
2480   else
2481     {
2482     print "The spamc command failed: assume SpamAssassin (spamd) is not running\n";
2483     }
2484
2485   # For ClamAV, we need to find the clamd socket for use in the Exim
2486   # configuration. Search for the clamd configuration file.
2487
2488   if (system("clamscan -h 2>/dev/null >/dev/null") == 0)
2489     {
2490     my($f, $clamconf, $test_prefix);
2491
2492     print "The clamscan command works";
2493
2494     $test_prefix = $ENV{EXIM_TEST_PREFIX};
2495     $test_prefix = "" if !defined $test_prefix;
2496
2497     foreach $f ("$test_prefix/etc/clamd.conf",
2498                 "$test_prefix/usr/local/etc/clamd.conf",
2499                 "$test_prefix/etc/clamav/clamd.conf", "")
2500       {
2501       if (-e $f)
2502         {
2503         $clamconf = $f;
2504         last;
2505         }
2506       }
2507
2508     # Read the ClamAV configuration file and find the socket interface.
2509
2510     if ($clamconf ne "")
2511       {
2512       my $socket_domain;
2513       open(IN, "$clamconf") || die "\n** Unable to open $clamconf: $!\n";
2514       while (<IN>)
2515         {
2516         if (/^LocalSocket\s+(.*)/)
2517           {
2518           $parm_clamsocket = $1;
2519           $socket_domain = AF_UNIX;
2520           last;
2521           }
2522         if (/^TCPSocket\s+(\d+)/)
2523           {
2524           if (defined $parm_clamsocket)
2525             {
2526             $parm_clamsocket .= " $1";
2527             $socket_domain = AF_INET;
2528             last;
2529             }
2530           else
2531             {
2532             $parm_clamsocket = " $1";
2533             }
2534           }
2535         elsif (/^TCPAddr\s+(\S+)/)
2536           {
2537           if (defined $parm_clamsocket)
2538             {
2539             $parm_clamsocket = $1 . $parm_clamsocket;
2540             $socket_domain = AF_INET;
2541             last;
2542             }
2543           else
2544             {
2545             $parm_clamsocket = $1;
2546             }
2547           }
2548         }
2549       close(IN);
2550
2551       if (defined $socket_domain)
2552         {
2553         print ":\n  The clamd socket is $parm_clamsocket\n";
2554         # This test for an active ClamAV is courtesy of Daniel Tiefnig.
2555         eval
2556           {
2557           my $socket;
2558           if ($socket_domain == AF_UNIX)
2559             {
2560             $socket = sockaddr_un($parm_clamsocket) or die "** Failed packing '$parm_clamsocket'\n";
2561             }
2562           elsif ($socket_domain == AF_INET)
2563             {
2564             my ($ca_host, $ca_port) = split(/\s+/,$parm_clamsocket);
2565             my $ca_hostent = gethostbyname($ca_host) or die "** Failed to get raw address for host '$ca_host'\n";
2566             $socket = sockaddr_in($ca_port, $ca_hostent) or die "** Failed packing '$parm_clamsocket'\n";
2567             }
2568           else
2569             {
2570             die "** Unknown socket domain '$socket_domain' (should not happen)\n";
2571             }
2572           socket($sock, $socket_domain, SOCK_STREAM, 0) or die "** Unable to open socket '$parm_clamsocket'\n";
2573           local $SIG{ALRM} = sub { die "** Timeout while connecting to socket '$parm_clamsocket'\n"; };
2574           alarm(5);
2575           connect($sock, $socket) or die "** Unable to connect to socket '$parm_clamsocket'\n";
2576           alarm(0);
2577
2578           my $ofh = select $sock; $| = 1; select $ofh;
2579           print $sock "PING\n";
2580
2581           $SIG{ALRM} = sub { die "** Timeout while reading from socket '$parm_clamsocket'\n"; };
2582           alarm(10);
2583           my $res = <$sock>;
2584           alarm(0);
2585
2586           $res =~ /PONG/ or die "** Did not get PONG from socket '$parm_clamsocket'. It said: $res\n";
2587           };
2588         alarm(0);
2589
2590         if($@)
2591           {
2592           print "  $@";
2593           print "  Assume ClamAV is not running\n";
2594           }
2595         else
2596           {
2597           $parm_running{'ClamAV'} = ' ';
2598           print "  ClamAV seems to be running\n";
2599           }
2600         }
2601       else
2602         {
2603         print ", but the socket for clamd could not be determined\n";
2604         print "Assume ClamAV is not running\n";
2605         }
2606       }
2607
2608     else
2609       {
2610       print ", but I can't find a configuration for clamd\n";
2611       print "Assume ClamAV is not running\n";
2612       }
2613     }
2614   }
2615
2616
2617 ##################################################
2618 #         Test for the basic requirements        #
2619 ##################################################
2620
2621 # This test suite assumes that Exim has been built with at least the "usual"
2622 # set of routers, transports, and lookups. Ensure that this is so.
2623
2624 $missing = "";
2625
2626 $missing .= "     Lookup: lsearch\n" if (!defined $parm_lookups{'lsearch'});
2627
2628 $missing .= "     Router: accept\n" if (!defined $parm_routers{'accept'});
2629 $missing .= "     Router: dnslookup\n" if (!defined $parm_routers{'dnslookup'});
2630 $missing .= "     Router: manualroute\n" if (!defined $parm_routers{'manualroute'});
2631 $missing .= "     Router: redirect\n" if (!defined $parm_routers{'redirect'});
2632
2633 $missing .= "     Transport: appendfile\n" if (!defined $parm_transports{'appendfile'});
2634 $missing .= "     Transport: autoreply\n" if (!defined $parm_transports{'autoreply'});
2635 $missing .= "     Transport: pipe\n" if (!defined $parm_transports{'pipe'});
2636 $missing .= "     Transport: smtp\n" if (!defined $parm_transports{'smtp'});
2637
2638 if ($missing ne "")
2639   {
2640   print "\n";
2641   print "** Many features can be included or excluded from Exim binaries.\n";
2642   print "** This test suite requires that Exim is built to contain a certain\n";
2643   print "** set of basic facilities. It seems that some of these are missing\n";
2644   print "** from the binary that is under test, so the test cannot proceed.\n";
2645   print "** The missing facilities are:\n";
2646   print "$missing";
2647   die "** Test script abandoned\n";
2648   }
2649
2650
2651 ##################################################
2652 #      Check for the auxiliary programs          #
2653 ##################################################
2654
2655 # These are always required:
2656
2657 for $prog ("cf", "checkaccess", "client", "client-ssl", "client-gnutls",
2658            "fakens", "iefbr14", "server")
2659   {
2660   next if ($prog eq "client-ssl" && !defined $parm_support{'OpenSSL'});
2661   next if ($prog eq "client-gnutls" && !defined $parm_support{'GnuTLS'});
2662   if (!-e "bin/$prog")
2663     {
2664     print "\n";
2665     print "** bin/$prog does not exist. Have you run ./configure and make?\n";
2666     die "** Test script abandoned\n";
2667     }
2668   }
2669
2670 # If the "loaded" binary is missing, we cut out tests for ${dlfunc. It isn't
2671 # compiled on systems where we don't know how to. However, if Exim does not
2672 # have that functionality compiled, we needn't bother.
2673
2674 $dlfunc_deleted = 0;
2675 if (defined $parm_support{'Expand_dlfunc'} && !-e "bin/loaded")
2676   {
2677   delete $parm_support{'Expand_dlfunc'};
2678   $dlfunc_deleted = 1;
2679   }
2680
2681
2682 ##################################################
2683 #          Find environmental details            #
2684 ##################################################
2685
2686 # Find the caller of this program.
2687
2688 ($parm_caller,$pwpw,$parm_caller_uid,$parm_caller_gid,$pwquota,$pwcomm,
2689  $parm_caller_gecos, $parm_caller_home) = getpwuid($>);
2690
2691 $pwpw = $pwpw;       # Kill Perl warnings
2692 $pwquota = $pwquota;
2693 $pwcomm = $pwcomm;
2694
2695 $parm_caller_group = getgrgid($parm_caller_gid);
2696
2697 print "Program caller is $parm_caller, whose group is $parm_caller_group\n";
2698 print "Home directory is $parm_caller_home\n";
2699
2700 unless (defined $parm_eximgroup)
2701   {
2702   print "Unable to derive \$parm_eximgroup.\n";
2703   die "** ABANDONING.\n";
2704   }
2705
2706 print "You need to be in the Exim group to run these tests. Checking ...";
2707
2708 if (`groups` =~ /\b\Q$parm_eximgroup\E\b/)
2709   {
2710   print " OK\n";
2711   }
2712 else
2713   {
2714   print "\nOh dear, you are not in the Exim group.\n";
2715   die "** Testing abandoned.\n";
2716   }
2717
2718 # Find this host's IP addresses - there may be many, of course, but we keep
2719 # one of each type (IPv4 and IPv6).
2720
2721 $parm_ipv4 = "";
2722 $parm_ipv6 = "";
2723
2724 $local_ipv4 = "";
2725 $local_ipv6 = "";
2726
2727 open(IFCONFIG, "ifconfig -a|") || die "** Cannot run \"ifconfig\": $!\n";
2728 while (($parm_ipv4 eq "" || $parm_ipv6 eq "") && ($_ = <IFCONFIG>))
2729   {
2730   my($ip);
2731   if ($parm_ipv4 eq "" &&
2732       $_ =~ /^\s*inet(?:\saddr)?:?\s?(\d+\.\d+\.\d+\.\d+)\s/i)
2733     {
2734     $ip = $1;
2735     next if ($ip eq "127.0.0.1");
2736     $parm_ipv4 = $ip;
2737     }
2738
2739   if ($parm_ipv6 eq "" &&
2740       $_ =~ /^\s*inet6(?:\saddr)?:?\s?([abcdef\d:]+)/i)
2741     {
2742     $ip = $1;
2743     next if ($ip eq "::1" || $ip =~ /^fe80/i);
2744     $parm_ipv6 = $ip;
2745     }
2746   }
2747 close(IFCONFIG);
2748
2749 # Use private IP addresses if there are no public ones.
2750
2751 $parm_ipv4 = $local_ipv4 if ($parm_ipv4 eq "");
2752 $parm_ipv6 = $local_ipv6 if ($parm_ipv6 eq "");
2753
2754 # If either type of IP address is missing, we need to set the value to
2755 # something other than empty, because that wrecks the substitutions. The value
2756 # is reflected, so use a meaningful string. Set appropriate options for the
2757 # "server" command. In practice, however, many tests assume 127.0.0.1 is
2758 # available, so things will go wrong if there is no IPv4 address. The lack
2759 # of IPV4 or IPv6 can be simulated by command options, which force $have_ipv4
2760 # and $have_ipv6 false.
2761
2762 if ($parm_ipv4 eq "")
2763   {
2764   $have_ipv4 = 0;
2765   $parm_ipv4 = "<no IPv4 address found>";
2766   $server_opts .= " -noipv4";
2767   }
2768 elsif ($have_ipv4 == 0)
2769   {
2770   $parm_ipv4 = "<IPv4 testing disabled>";
2771   $server_opts .= " -noipv4";
2772   }
2773 else
2774   {
2775   $parm_running{"IPv4"} = " ";
2776   }
2777
2778 if ($parm_ipv6 eq "")
2779   {
2780   $have_ipv6 = 0;
2781   $parm_ipv6 = "<no IPv6 address found>";
2782   $server_opts .= " -noipv6";
2783   delete($parm_support{"IPv6"});
2784   }
2785 elsif ($have_ipv6 == 0)
2786   {
2787   $parm_ipv6 = "<IPv6 testing disabled>";
2788   $server_opts .= " -noipv6";
2789   delete($parm_support{"IPv6"});
2790   }
2791 elsif (!defined $parm_support{'IPv6'})
2792   {
2793   $have_ipv6 = 0;
2794   $parm_ipv6 = "<no IPv6 support in Exim binary>";
2795   $server_opts .= " -noipv6";
2796   }
2797 else
2798   {
2799   $parm_running{"IPv6"} = " ";
2800   }
2801
2802 print "IPv4 address is $parm_ipv4\n";
2803 print "IPv6 address is $parm_ipv6\n";
2804
2805 # For munging test output, we need the reversed IP addresses.
2806
2807 $parm_ipv4r = ($parm_ipv4 !~ /^\d/)? "" :
2808   join(".", reverse(split /\./, $parm_ipv4));
2809
2810 $parm_ipv6r = $parm_ipv6;             # Appropriate if not in use
2811 if ($parm_ipv6 =~ /^[\da-f]/)
2812   {
2813   my(@comps) = split /:/, $parm_ipv6;
2814   my(@nibbles);
2815   foreach $comp (@comps)
2816     {
2817     push @nibbles, sprintf("%lx", hex($comp) >> 8);
2818     push @nibbles, sprintf("%lx", hex($comp) & 0xff);
2819     }
2820   $parm_ipv6r = join(".", reverse(@nibbles));
2821   }
2822
2823 # Find the host name, fully qualified.
2824
2825 chomp($temp = `hostname`);
2826 $parm_hostname = (gethostbyname($temp))[0];
2827 $parm_hostname = "no.host.name.found" if $parm_hostname eq "";
2828 print "Hostname is $parm_hostname\n";
2829
2830 if ($parm_hostname !~ /\./)
2831   {
2832   print "\n*** Host name is not fully qualified: this may cause problems ***\n\n";
2833   }
2834
2835 if ($parm_hostname =~ /[[:upper:]]/)
2836   {
2837   print "\n*** Host name has upper case characters: this may cause problems ***\n\n";
2838   }
2839
2840
2841
2842 ##################################################
2843 #     Create a testing version of Exim           #
2844 ##################################################
2845
2846 # We want to be able to run Exim with a variety of configurations. Normally,
2847 # the use of -C to change configuration causes Exim to give up its root
2848 # privilege (unless the caller is exim or root). For these tests, we do not
2849 # want this to happen. Also, we want Exim to know that it is running in its
2850 # test harness.
2851
2852 # We achieve this by copying the binary and patching it as we go. The new
2853 # binary knows it is a testing copy, and it allows -C and -D without loss of
2854 # privilege. Clearly, this file is dangerous to have lying around on systems
2855 # where there are general users with login accounts. To protect against this,
2856 # we put the new binary in a special directory that is accessible only to the
2857 # caller of this script, who is known to have sudo root privilege from the test
2858 # that was done above. Furthermore, we ensure that the binary is deleted at the
2859 # end of the test. First ensure the directory exists.
2860
2861 if (-d "eximdir")
2862   { unlink "eximdir/exim"; }     # Just in case
2863 else
2864   {
2865   mkdir("eximdir", 0710) || die "** Unable to mkdir $parm_cwd/eximdir: $!\n";
2866   system("sudo chgrp $parm_eximgroup eximdir");
2867   }
2868
2869 # The construction of the patched binary must be done as root, so we use
2870 # a separate script. As well as indicating that this is a test-harness binary,
2871 # the version number is patched to "x.yz" so that its length is always the
2872 # same. Otherwise, when it appears in Received: headers, it affects the length
2873 # of the message, which breaks certain comparisons.
2874
2875 die "** Unable to make patched exim: $!\n"
2876   if (system("sudo ./patchexim $parm_exim") != 0);
2877
2878 # From this point on, exits from the program must go via the subroutine
2879 # tests_exit(), so that suitable cleaning up can be done when required.
2880 # Arrange to catch interrupting signals, to assist with this.
2881
2882 $SIG{'INT'} = \&inthandler;
2883 $SIG{'PIPE'} = \&pipehandler;
2884
2885 # For some tests, we need another copy of the binary that is setuid exim rather
2886 # than root.
2887
2888 system("sudo cp eximdir/exim eximdir/exim_exim;" .
2889        "sudo chown $parm_eximuser eximdir/exim_exim;" .
2890        "sudo chgrp $parm_eximgroup eximdir/exim_exim;" .
2891        "sudo chmod 06755 eximdir/exim_exim");
2892
2893
2894 ##################################################
2895 #     Make copies of utilities we might need     #
2896 ##################################################
2897
2898 # Certain of the tests make use of some of Exim's utilities. We do not need
2899 # to be root to copy these.
2900
2901 ($parm_exim_dir) = $parm_exim =~ m?^(.*)/exim?;
2902
2903 $dbm_build_deleted = 0;
2904 if (defined $parm_lookups{'dbm'} &&
2905     system("cp $parm_exim_dir/exim_dbmbuild eximdir") != 0)
2906   {
2907   delete $parm_lookups{'dbm'};
2908   $dbm_build_deleted = 1;
2909   }
2910
2911 if (system("cp $parm_exim_dir/exim_dumpdb eximdir") != 0)
2912   {
2913   tests_exit(-1, "Failed to make a copy of exim_dumpdb: $!");
2914   }
2915
2916 if (system("cp $parm_exim_dir/exim_lock eximdir") != 0)
2917   {
2918   tests_exit(-1, "Failed to make a copy of exim_lock: $!");
2919   }
2920
2921 if (system("cp $parm_exim_dir/exinext eximdir") != 0)
2922   {
2923   tests_exit(-1, "Failed to make a copy of exinext: $!");
2924   }
2925
2926 if (system("cp $parm_exim_dir/exigrep eximdir") != 0)
2927   {
2928   tests_exit(-1, "Failed to make a copy of exigrep: $!");
2929   }
2930
2931 if (system("cp $parm_exim_dir/eximstats eximdir") != 0)
2932   {
2933   tests_exit(-1, "Failed to make a copy of eximstats: $!");
2934   }
2935
2936
2937 ##################################################
2938 #    Check that the Exim user can access stuff   #
2939 ##################################################
2940
2941 # We delay this test till here so that we can check access to the actual test
2942 # binary. This will be needed when Exim re-exec's itself to do deliveries.
2943
2944 print "Exim user is $parm_eximuser ($parm_exim_uid)\n";
2945 print "Exim group is $parm_eximgroup ($parm_exim_gid)\n";
2946
2947 if ($parm_caller_uid eq $parm_exim_uid) {
2948   tests_exit(-1, "Exim user ($parm_eximuser,$parm_exim_uid) cannot be "
2949                 ."the same as caller ($parm_caller,$parm_caller_uid)");
2950 }
2951
2952 print "The Exim user needs access to the test suite directory. Checking ...";
2953
2954 if (($rc = system("sudo bin/checkaccess $parm_cwd/eximdir/exim $parm_eximuser $parm_eximgroup")) != 0)
2955   {
2956   my($why) = "unknown failure $rc";
2957   $rc >>= 8;
2958   $why = "Couldn't find user \"$parm_eximuser\"" if $rc == 1;
2959   $why = "Couldn't find group \"$parm_eximgroup\"" if $rc == 2;
2960   $why = "Couldn't read auxiliary group list" if $rc == 3;
2961   $why = "Couldn't get rid of auxiliary groups" if $rc == 4;
2962   $why = "Couldn't set gid" if $rc == 5;
2963   $why = "Couldn't set uid" if $rc == 6;
2964   $why = "Couldn't open \"$parm_cwd/eximdir/exim\"" if $rc == 7;
2965   print "\n** $why\n";
2966   tests_exit(-1, "$parm_eximuser cannot access the test suite directory");
2967   }
2968 else
2969   {
2970   print " OK\n";
2971   }
2972
2973
2974 ##################################################
2975 #        Create a list of available tests        #
2976 ##################################################
2977
2978 # The scripts directory contains a number of subdirectories whose names are
2979 # of the form 0000-xxxx, 1100-xxxx, 2000-xxxx, etc. Each set of tests apart
2980 # from the first requires certain optional features to be included in the Exim
2981 # binary. These requirements are contained in a file called "REQUIRES" within
2982 # the directory. We scan all these tests, discarding those that cannot be run
2983 # because the current binary does not support the right facilities, and also
2984 # those that are outside the numerical range selected.
2985
2986 print "\nTest range is $test_start to $test_end\n";
2987 print "Omitting \${dlfunc expansion tests (loadable module not present)\n"
2988   if $dlfunc_deleted;
2989 print "Omitting dbm tests (unable to copy exim_dbmbuild)\n"
2990   if $dbm_build_deleted;
2991
2992 opendir(DIR, "scripts") || tests_exit(-1, "Failed to opendir(\"scripts\"): $!");
2993 @test_dirs = sort readdir(DIR);
2994 closedir(DIR);
2995
2996 # Remove . and .. and CVS from the list.
2997
2998 for ($i = 0; $i < @test_dirs; $i++)
2999   {
3000   my($d) = $test_dirs[$i];
3001   if ($d eq "." || $d eq ".." || $d eq "CVS")
3002     {
3003     splice @test_dirs, $i, 1;
3004     $i--;
3005     }
3006   }
3007
3008 # Scan for relevant tests
3009
3010 for ($i = 0; $i < @test_dirs; $i++)
3011   {
3012   my($testdir) = $test_dirs[$i];
3013   my($wantthis) = 1;
3014
3015   print ">>Checking $testdir\n" if $debug;
3016
3017   # Skip this directory if the first test is equal or greater than the first
3018   # test in the next directory.
3019
3020   next if ($i < @test_dirs - 1) &&
3021           ($test_start >= substr($test_dirs[$i+1], 0, 4));
3022
3023   # No need to carry on if the end test is less than the first test in this
3024   # subdirectory.
3025
3026   last if $test_end < substr($testdir, 0, 4);
3027
3028   # Check requirements, if any.
3029
3030   if (open(REQUIRES, "scripts/$testdir/REQUIRES"))
3031     {
3032     while (<REQUIRES>)
3033       {
3034       next if /^\s*$/;
3035       s/\s+$//;
3036       if (/^support (.*)$/)
3037         {
3038         if (!defined $parm_support{$1}) { $wantthis = 0; last; }
3039         }
3040       elsif (/^running (.*)$/)
3041         {
3042         if (!defined $parm_running{$1}) { $wantthis = 0; last; }
3043         }
3044       elsif (/^lookup (.*)$/)
3045         {
3046         if (!defined $parm_lookups{$1}) { $wantthis = 0; last; }
3047         }
3048       elsif (/^authenticators? (.*)$/)
3049         {
3050         if (!defined $parm_authenticators{$1}) { $wantthis = 0; last; }
3051         }
3052       elsif (/^router (.*)$/)
3053         {
3054         if (!defined $parm_routers{$1}) { $wantthis = 0; last; }
3055         }
3056       elsif (/^transport (.*)$/)
3057         {
3058         if (!defined $parm_transports{$1}) { $wantthis = 0; last; }
3059         }
3060       else
3061         {
3062         tests_exit(-1, "Unknown line in \"scripts/$testdir/REQUIRES\": \"$_\"");
3063         }
3064       }
3065     close(REQUIRES);
3066     }
3067   else
3068     {
3069     tests_exit(-1, "Failed to open \"scripts/$testdir/REQUIRES\": $!")
3070       unless $!{ENOENT};
3071     }
3072
3073   # Loop if we do not want the tests in this subdirectory.
3074
3075   if (!$wantthis)
3076     {
3077     chomp;
3078     print "Omitting tests in $testdir (missing $_)\n";
3079     next;
3080     }
3081
3082   # We want the tests from this subdirectory, provided they are in the
3083   # range that was selected.
3084
3085   opendir(SUBDIR, "scripts/$testdir") ||
3086     tests_exit(-1, "Failed to opendir(\"scripts/$testdir\"): $!");
3087   @testlist = sort readdir(SUBDIR);
3088   close(SUBDIR);
3089
3090   foreach $test (@testlist)
3091     {
3092     next if $test !~ /^\d{4}$/;
3093     next if $test < $test_start || $test > $test_end;
3094     push @test_list, "$testdir/$test";
3095     }
3096   }
3097
3098 print ">>Test List: @test_list\n", if $debug;
3099
3100
3101 ##################################################
3102 #         Munge variable auxiliary data          #
3103 ##################################################
3104
3105 # Some of the auxiliary data files have to refer to the current testing
3106 # directory and other parameter data. The generic versions of these files are
3107 # stored in the aux-var-src directory. At this point, we copy each of them
3108 # to the aux-var directory, making appropriate substitutions. There aren't very
3109 # many of them, so it's easiest just to do this every time. Ensure the mode
3110 # is standardized, as this path is used as a test for the ${stat: expansion.
3111
3112 # A similar job has to be done for the files in the dnszones-src directory, to
3113 # make the fake DNS zones for testing. Most of the zone files are copied to
3114 # files of the same name, but db.ipv4.V4NET and db.ipv6.V6NET use the testing
3115 # networks that are defined by parameter.
3116
3117 foreach $basedir ("aux-var", "dnszones")
3118   {
3119   system("sudo rm -rf $parm_cwd/$basedir");
3120   mkdir("$parm_cwd/$basedir", 0777);
3121   chmod(0755, "$parm_cwd/$basedir");
3122
3123   opendir(AUX, "$parm_cwd/$basedir-src") ||
3124     tests_exit(-1, "Failed to opendir $parm_cwd/$basedir-src: $!");
3125   my(@filelist) = readdir(AUX);
3126   close(AUX);
3127
3128   foreach $file (@filelist)
3129     {
3130     my($outfile) = $file;
3131     next if $file =~ /^\./;
3132
3133     if ($file eq "db.ip4.V4NET")
3134       {
3135       $outfile = "db.ip4.$parm_ipv4_test_net";
3136       }
3137     elsif ($file eq "db.ip6.V6NET")
3138       {
3139       my(@nibbles) = reverse(split /\s*/, $parm_ipv6_test_net);
3140       $" = '.';
3141       $outfile = "db.ip6.@nibbles";
3142       $" = ' ';
3143       }
3144
3145     print ">>Copying $basedir-src/$file to $basedir/$outfile\n" if $debug;
3146     open(IN, "$parm_cwd/$basedir-src/$file") ||
3147       tests_exit(-1, "Failed to open $parm_cwd/$basedir-src/$file: $!");
3148     open(OUT, ">$parm_cwd/$basedir/$outfile") ||
3149       tests_exit(-1, "Failed to open $parm_cwd/$basedir/$outfile: $!");
3150     while (<IN>)
3151       {
3152       do_substitute(0);
3153       print OUT;
3154       }
3155     close(IN);
3156     close(OUT);
3157     }
3158   }
3159
3160 # Set a user's shell, distinguishable from /bin/sh
3161
3162 symlink("/bin/sh","aux-var/sh");
3163 $ENV{'SHELL'} = $parm_shell = $parm_cwd . "/aux-var/sh";
3164
3165 ##################################################
3166 #     Create fake DNS zones for this host        #
3167 ##################################################
3168
3169 # There are fixed zone files for 127.0.0.1 and ::1, but we also want to be
3170 # sure that there are forward and reverse registrations for this host, using
3171 # its real IP addresses. Dynamically created zone files achieve this.
3172
3173 if ($have_ipv4 || $have_ipv6)
3174   {
3175   my($shortname,$domain) = $parm_hostname =~ /^([^.]+)(.*)/;
3176   open(OUT, ">$parm_cwd/dnszones/db$domain") ||
3177     tests_exit(-1, "Failed to open $parm_cwd/dnszones/db$domain: $!");
3178   print OUT "; This is a dynamically constructed fake zone file.\n" .
3179     "; The following line causes fakens to return PASS_ON\n" .
3180     "; for queries that it cannot answer\n\n" .
3181     "PASS ON NOT FOUND\n\n";
3182   print OUT "$shortname  A     $parm_ipv4\n" if $have_ipv4;
3183   print OUT "$shortname  AAAA  $parm_ipv6\n" if $have_ipv6;
3184   print OUT "\n; End\n";
3185   close(OUT);
3186   }
3187
3188 if ($have_ipv4 && $parm_ipv4 ne "127.0.0.1")
3189   {
3190   my(@components) = $parm_ipv4 =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)/;
3191   open(OUT, ">$parm_cwd/dnszones/db.ip4.$components[0]") ||
3192     tests_exit(-1,
3193       "Failed  to open $parm_cwd/dnszones/db.ip4.$components[0]: $!");
3194   print OUT "; This is a dynamically constructed fake zone file.\n" .
3195     "; The zone is $components[0].in-addr.arpa.\n\n" .
3196     "$components[3].$components[2].$components[1]  PTR  $parm_hostname.\n\n" .
3197     "; End\n";
3198   close(OUT);
3199   }
3200
3201 if ($have_ipv6 && $parm_ipv6 ne "::1")
3202   {
3203   my($exp_v6) = $parm_ipv6;
3204   $exp_v6 =~ s/[^:]//g;
3205   if ( $parm_ipv6 =~ /^([^:].+)::$/ ) {
3206     $exp_v6 = $1 . ':0' x (9-length($exp_v6));
3207   } elsif ( $parm_ipv6 =~ /^(.+)::(.+)$/ ) {
3208     $exp_v6 = $1 . ':0' x (8-length($exp_v6)) . ':' . $2;
3209   } elsif ( $parm_ipv6 =~ /^::(.+[^:])$/ ) {
3210     $exp_v6 = '0:' x (9-length($exp_v6)) . $1;
3211   } else {
3212     $exp_v6 = $parm_ipv6;
3213   }
3214   my(@components) = split /:/, $exp_v6;
3215   my(@nibbles) = reverse (split /\s*/, shift @components);
3216   my($sep) =  "";
3217
3218   $" = ".";
3219   open(OUT, ">$parm_cwd/dnszones/db.ip6.@nibbles") ||
3220     tests_exit(-1,
3221       "Failed  to open $parm_cwd/dnszones/db.ip6.@nibbles: $!");
3222   print OUT "; This is a dynamically constructed fake zone file.\n" .
3223     "; The zone is @nibbles.ip6.arpa.\n\n";
3224
3225   @components = reverse @components;
3226   foreach $c (@components)
3227     {
3228     $c = "0$c" until $c =~ /^..../;
3229     @nibbles = reverse(split /\s*/, $c);
3230     print OUT "$sep@nibbles";
3231     $sep = ".";
3232     }
3233
3234   print OUT "  PTR  $parm_hostname.\n\n; End\n";
3235   close(OUT);
3236   $" = " ";
3237   }
3238
3239
3240
3241 ##################################################
3242 #    Create lists of mailboxes and message logs  #
3243 ##################################################
3244
3245 # We use these lists to check that a test has created the expected files. It
3246 # should be faster than looking for the file each time. For mailboxes, we have
3247 # to scan a complete subtree, in order to handle maildirs. For msglogs, there
3248 # is just a flat list of files.
3249
3250 @oldmails = list_files_below("mail");
3251 opendir(DIR, "msglog") || tests_exit(-1, "Failed to opendir msglog: $!");
3252 @oldmsglogs = readdir(DIR);
3253 closedir(DIR);
3254
3255
3256
3257 ##################################################
3258 #         Run the required tests                 #
3259 ##################################################
3260
3261 # Each test script contains a number of tests, separated by a line that
3262 # contains ****. We open input from the terminal so that we can read responses
3263 # to prompts.
3264
3265 open(T, "/dev/tty") || tests_exit(-1, "Failed to open /dev/tty: $!");
3266
3267 print "\nPress RETURN to run the tests: ";
3268 $_ = $force_continue ? "c" : <T>;
3269 print "\n";
3270
3271 $lasttestdir = "";
3272
3273 foreach $test (@test_list)
3274   {
3275   local($lineno) = 0;
3276   local($commandno) = 0;
3277   local($subtestno) = 0;
3278   local($testno) = substr($test, -4);
3279   local($sortlog) = 0;
3280
3281   my($gnutls) = 0;
3282   my($docheck) = 1;
3283   my($thistestdir) = substr($test, 0, -5);
3284
3285   if ($lasttestdir ne $thistestdir)
3286     {
3287     $gnutls = 0;
3288     if (-s "scripts/$thistestdir/REQUIRES")
3289       {
3290       my($indent) = "";
3291       print "\n>>> The following tests require: ";
3292       open(IN, "scripts/$thistestdir/REQUIRES") ||
3293         tests_exit(-1, "Failed to open scripts/$thistestdir/REQUIRES: $1");
3294       while (<IN>)
3295         {
3296         $gnutls = 1 if /^support GnuTLS/;
3297         print $indent, $_;
3298         $indent = ">>>                              ";
3299         }
3300       close(IN);
3301       }
3302     }
3303   $lasttestdir = $thistestdir;
3304
3305   # Remove any debris in the spool directory and the test-mail directory
3306   # and also the files for collecting stdout and stderr. Then put back
3307   # the test-mail directory for appendfile deliveries.
3308
3309   system "sudo /bin/rm -rf spool test-*";
3310   system "mkdir test-mail 2>/dev/null";
3311
3312   # A privileged Exim will normally make its own spool directory, but some of
3313   # the tests run in unprivileged modes that don't always work if the spool
3314   # directory isn't already there. What is more, we want anybody to be able
3315   # to read it in order to find the daemon's pid.
3316
3317   system "mkdir spool; " .
3318          "sudo chown $parm_eximuser:$parm_eximgroup spool; " .
3319          "sudo chmod 0755 spool";
3320
3321   # Empty the cache that keeps track of things like message id mappings, and
3322   # set up the initial sequence strings.
3323
3324   undef %cache;
3325   $next_msgid = "aX";
3326   $next_pid = 1234;
3327   $next_port = 1111;
3328   $message_skip = 0;
3329   $msglog_skip = 0;
3330   $stderr_skip = 0;
3331   $stdout_skip = 0;
3332   $rmfiltertest = 0;
3333   $is_ipv6test = 0;
3334
3335   # Remove the associative arrays used to hold checked mail files and msglogs
3336
3337   undef %expected_mails;
3338   undef %expected_msglogs;
3339
3340   # Open the test's script
3341
3342   open(SCRIPT, "scripts/$test") ||
3343     tests_exit(-1, "Failed to open \"scripts/$test\": $!");
3344
3345   # The first line in the script must be a comment that is used to identify
3346   # the set of tests as a whole.
3347
3348   $_ = <SCRIPT>;
3349   $lineno++;
3350   tests_exit(-1, "Missing identifying comment at start of $test") if (!/^#/);
3351   printf("%s %s", (substr $test, 5), (substr $_, 2));
3352
3353   # Loop for each of the subtests within the script. The variable $server_pid
3354   # is used to remember the pid of a "server" process, for which we do not
3355   # wait until we have waited for a subsequent command.
3356
3357   local($server_pid) = 0;
3358   for ($commandno = 1; !eof SCRIPT; $commandno++)
3359     {
3360     # Skip further leading comments and blank lines, handle the flag setting
3361     # commands, and deal with tests for IP support.
3362
3363     while (<SCRIPT>)
3364       {
3365       $lineno++;
3366       if (/^no_message_check/) { $message_skip = 1; next; }
3367       if (/^no_msglog_check/)  { $msglog_skip = 1; next; }
3368       if (/^no_stderr_check/)  { $stderr_skip = 1; next; }
3369       if (/^no_stdout_check/)  { $stdout_skip = 1; next; }
3370       if (/^rmfiltertest/)     { $rmfiltertest = 1; next; }
3371       if (/^sortlog/)          { $sortlog = 1; next; }
3372
3373       if (/^need_largefiles/)
3374         {
3375         next if $have_largefiles;
3376         print ">>> Large file support is needed for test $testno, but is not available: skipping\n";
3377         $docheck = 0;      # don't check output
3378         undef $_;          # pretend EOF
3379         last;
3380         }
3381
3382       if (/^need_ipv4/)
3383         {
3384         next if $have_ipv4;
3385         print ">>> IPv4 is needed for test $testno, but is not available: skipping\n";
3386         $docheck = 0;      # don't check output
3387         undef $_;          # pretend EOF
3388         last;
3389         }
3390
3391       if (/^need_ipv6/)
3392         {
3393         if ($have_ipv6)
3394           {
3395           $is_ipv6test = 1;
3396           next;
3397           }
3398         print ">>> IPv6 is needed for test $testno, but is not available: skipping\n";
3399         $docheck = 0;      # don't check output
3400         undef $_;          # pretend EOF
3401         last;
3402         }
3403
3404       if (/^need_move_frozen_messages/)
3405         {
3406         next if defined $parm_support{"move_frozen_messages"};
3407         print ">>> move frozen message support is needed for test $testno, " .
3408           "but is not\n>>> available: skipping\n";
3409         $docheck = 0;      # don't check output
3410         undef $_;          # pretend EOF
3411         last;
3412         }
3413
3414       last unless /^(#|\s*$)/;
3415       }
3416     last if !defined $_;  # Hit EOF
3417
3418     my($subtest_startline) = $lineno;
3419
3420     # Now run the command. The function returns 0 if exim was run and waited
3421     # for, 1 if any other command was run and waited for, and 2 if a command
3422     # was run and not waited for (usually a daemon or server startup).
3423
3424     my($commandname) = "";
3425     my($expectrc) = 0;
3426     my($rc, $run_extra) = run_command($testno, \$subtestno, \$expectrc, \$commandname, $TEST_STATE);
3427     my($cmdrc) = $?;
3428
3429     if ($debug) {
3430       print ">> rc=$rc cmdrc=$cmdrc\n";
3431       if (defined $run_extra) {
3432         foreach my $k (keys %$run_extra) {
3433           my $v = defined $run_extra->{$k} ? qq!"$run_extra->{$k}"! : '<undef>';
3434           print ">>   $k -> $v\n";
3435         }
3436       }
3437     }
3438     $run_extra = {} unless defined $run_extra;
3439     foreach my $k (keys %$run_extra) {
3440       if (exists $TEST_STATE->{$k}) {
3441         my $nv = defined $run_extra->{$k} ? qq!"$run_extra->{$k}"! : 'removed';
3442         print ">> override of $k; was $TEST_STATE->{$k}, now $nv\n" if $debug;
3443       }
3444       if (defined $run_extra->{$k}) {
3445         $TEST_STATE->{$k} = $run_extra->{$k};
3446       } elsif (exists $TEST_STATE->{$k}) {
3447         delete $TEST_STATE->{$k};
3448       }
3449     }
3450
3451     # Hit EOF after an initial return code number
3452
3453     tests_exit(-1, "Unexpected EOF in script") if ($rc == 4);
3454
3455     # Carry on with the next command if we did not wait for this one. $rc == 0
3456     # if no subprocess was run; $rc == 3 if we started a process but did not
3457     # wait for it.
3458
3459     next if ($rc == 0 || $rc == 3);
3460
3461     # We ran and waited for a command. Check for the expected result unless
3462     # it died.
3463
3464     if ($cmdrc != $expectrc && !$sigpipehappened)
3465       {
3466       printf("** Command $commandno (\"$commandname\", starting at line $subtest_startline)\n");
3467       if (($cmdrc & 0xff) == 0)
3468         {
3469         printf("** Return code %d (expected %d)", $cmdrc/256, $expectrc/256);
3470         }
3471       elsif (($cmdrc & 0xff00) == 0)
3472         { printf("** Killed by signal %d", $cmdrc & 255); }
3473       else
3474         { printf("** Status %x", $cmdrc); }
3475
3476       for (;;)
3477         {
3478         print "\nshow stdErr, show stdOut, Retry, Continue (without file comparison), or Quit? [Q] ";
3479         $_ = $force_continue ? "c" : <T>;
3480         tests_exit(1) if /^q?$/i;
3481         log_failure($log_failed_filename, $testno, "exit code unexpected") if (/^c$/i && $force_continue);
3482         print "... continue forced\n" if $force_continue;
3483         last if /^[rc]$/i;
3484         if (/^e$/i)
3485           {
3486           system("$more test-stderr");
3487           }
3488         elsif (/^o$/i)
3489           {
3490           system("$more test-stdout");
3491           }
3492         }
3493
3494       $retry = 1 if /^r$/i;
3495       $docheck = 0;
3496       }
3497
3498     # If the command was exim, and a listening server is running, we can now
3499     # close its input, which causes us to wait for it to finish, which is why
3500     # we didn't close it earlier.
3501
3502     if ($rc == 2 && $server_pid != 0)
3503       {
3504       close SERVERCMD;
3505       $server_pid = 0;
3506       if ($? != 0)
3507         {
3508         if (($? & 0xff) == 0)
3509           { printf("Server return code %d", $?/256); }
3510         elsif (($? & 0xff00) == 0)
3511           { printf("Server killed by signal %d", $? & 255); }
3512         else
3513           { printf("Server status %x", $?); }
3514
3515         for (;;)
3516           {
3517           print "\nShow server stdout, Retry, Continue, or Quit? [Q] ";
3518           $_ = $force_continue ? "c" : <T>;
3519           tests_exit(1) if /^q?$/i;
3520           log_failure($log_failed_filename, $testno, "exit code unexpected") if (/^c$/i && $force_continue);
3521           print "... continue forced\n" if $force_continue;
3522           last if /^[rc]$/i;
3523
3524           if (/^s$/i)
3525             {
3526             open(S, "test-stdout-server") ||
3527               tests_exit(-1, "Failed to open test-stdout-server: $!");
3528             print while <S>;
3529             close(S);
3530             }
3531           }
3532         $retry = 1 if /^r$/i;
3533         }
3534       }
3535     }
3536
3537   close SCRIPT;
3538
3539   # The script has finished. Check the all the output that was generated. The
3540   # function returns 0 if all is well, 1 if we should rerun the test (the files
3541   # have been updated). It does not return if the user responds Q to a prompt.
3542
3543   if ($retry)
3544     {
3545     $retry = '0';
3546     print (("#" x 79) . "\n");
3547     redo;
3548     }
3549
3550   if ($docheck)
3551     {
3552     if (check_output($TEST_STATE->{munge}) != 0)
3553       {
3554       print (("#" x 79) . "\n");
3555       redo;
3556       }
3557     else
3558       {
3559       print ("  Script completed\n");
3560       }
3561     }
3562   }
3563
3564
3565 ##################################################
3566 #         Exit from the test script              #
3567 ##################################################
3568
3569 tests_exit(-1, "No runnable tests selected") if @test_list == 0;
3570 tests_exit(0);
3571
3572 # End of runtest script
3573 # vim: set sw=2 et :