#! /usr/bin/perl -w

###############################################################################
# This is the controlling script for the "new" test suite for Exim. It should #
# be possible to export this suite for running on a wide variety of hosts, in #
# contrast to the old suite, which was very dependent on the environment of   #
# Philip Hazel's desktop computer. This implementation inspects the version   #
# of Exim that it finds, and tests only those features that are included. The #
# surrounding environment is also tested to discover what is available. See   #
# the README file for details of how it all works.                            #
#                                                                             #
# Implementation started: 03 August 2005 by Philip Hazel                      #
# Placed in the Exim CVS: 06 February 2006                                    #
###############################################################################

#use strict;
require Cwd;
use Errno;
use FileHandle;
use Socket;
use Time::Local;


# Start by initializing some global variables

$testversion = "4.80 (08-May-12)";

# This gets embedded in the D-H params filename, and the value comes
# from asking GnuTLS for "normal", but there appears to be no way to
# use certtool/... to ask what that value currently is.  *sigh*
# We also clamp it because of NSS interop, see addition of tls_dh_max_bits.
# This value is correct as of GnuTLS 2.12.18 as clamped by tls_dh_max_bits.
# normal = 2432   tls_dh_max_bits = 2236
$gnutls_dh_bits_normal = 2236;

$cf = "bin/cf -exact";
$cr = "\r";
$debug = 0;
$force_continue = 0;
$force_update = 0;
$log_failed_filename = "failed-summary.log";
$more = "less -XF";
$optargs = "";
$save_output = 0;
$server_opts = "";

$have_ipv4 = 1;
$have_ipv6 = 1;
$have_largefiles = 0;

$test_start = 1;
$test_end = $test_top = 8999;
$test_special_top = 9999;
@test_list = ();
@test_dirs = ();


# Networks to use for DNS tests. We need to choose some networks that will
# never be used so that there is no chance that the host on which we are
# running is actually in one of the test networks. Private networks such as
# the IPv4 10.0.0.0/8 network are no good because hosts may well use them.
# Rather than use some unassigned numbers (that might become assigned later),
# I have chosen some multicast networks, in the belief that such addresses
# won't ever be assigned to hosts. This is the only place where these numbers
# are defined, so it is trivially possible to change them should that ever
# become necessary.

$parm_ipv4_test_net = "224";
$parm_ipv6_test_net = "ff00";

# Port numbers are currently hard-wired

$parm_port_n = 1223;         # Nothing listening on this port
$parm_port_s = 1224;         # Used for the "server" command
$parm_port_d = 1225;         # Used for the Exim daemon
$parm_port_d2 = 1226;        # Additional for daemon
$parm_port_d3 = 1227;        # Additional for daemon
$parm_port_d4 = 1228;        # Additional for daemon

# Manually set locale
$ENV{'LC_ALL'} = 'C';



###############################################################################
###############################################################################

# Define a number of subroutines

###############################################################################
###############################################################################


##################################################
#              Handle signals                    #
##################################################

sub pipehandler { $sigpipehappened = 1; }

sub inthandler { print "\n"; tests_exit(-1, "Caught SIGINT"); }


##################################################
#       Do global macro substitutions            #
##################################################

# This function is applied to configurations, command lines and data lines in
# scripts, and to lines in the files of the aux-var-src and the dnszones-src
# directory. It takes one argument: the current test number, or zero when
# setting up files before running any tests.

sub do_substitute{
s?\bCALLER\b?$parm_caller?g;
s?\bCALLERGROUP\b?$parm_caller_group?g;
s?\bCALLER_UID\b?$parm_caller_uid?g;
s?\bCALLER_GID\b?$parm_caller_gid?g;
s?\bCLAMSOCKET\b?$parm_clamsocket?g;
s?\bDIR/?$parm_cwd/?g;
s?\bEXIMGROUP\b?$parm_eximgroup?g;
s?\bEXIMUSER\b?$parm_eximuser?g;
s?\bHOSTIPV4\b?$parm_ipv4?g;
s?\bHOSTIPV6\b?$parm_ipv6?g;
s?\bHOSTNAME\b?$parm_hostname?g;
s?\bPORT_D\b?$parm_port_d?g;
s?\bPORT_D2\b?$parm_port_d2?g;
s?\bPORT_D3\b?$parm_port_d3?g;
s?\bPORT_D4\b?$parm_port_d4?g;
s?\bPORT_N\b?$parm_port_n?g;
s?\bPORT_S\b?$parm_port_s?g;
s?\bTESTNUM\b?$_[0]?g;
s?(\b|_)V4NET([\._])?$1$parm_ipv4_test_net$2?g;
s?\bV6NET:?$parm_ipv6_test_net:?g;
}


##################################################
#     Any state to be preserved across tests     #
##################################################

my $TEST_STATE = {};


##################################################
#        Subroutine to tidy up and exit          #
##################################################

# In all cases, we check for any Exim daemons that have been left running, and
# kill them. Then remove all the spool data, test output, and the modified Exim
# binary if we are ending normally.

# Arguments:
#    $_[0] = 0 for a normal exit; full cleanup done
#    $_[0] > 0 for an error exit; no files cleaned up
#    $_[0] < 0 for a "die" exit; $_[1] contains a message

sub tests_exit{
my($rc) = $_[0];
my($spool);

# Search for daemon pid files and kill the daemons. We kill with SIGINT rather
# than SIGTERM to stop it outputting "Terminated" to the terminal when not in
# the background.

if (exists $TEST_STATE->{exim_pid})
  {
  $pid = $TEST_STATE->{exim_pid};
  print "Tidyup: killing wait-mode daemon pid=$pid\n";
  system("sudo kill -INT $pid");
  }

if (opendir(DIR, "spool"))
  {
  my(@spools) = sort readdir(DIR);
  closedir(DIR);
  foreach $spool (@spools)
    {
    next if $spool !~ /^exim-daemon./;
    open(PID, "spool/$spool") || die "** Failed to open \"spool/$spool\": $!\n";
    chomp($pid = <PID>);
    close(PID);
    print "Tidyup: killing daemon pid=$pid\n";
    system("sudo rm -f spool/$spool; sudo kill -INT $pid");
    }
  }
else
  { die "** Failed to opendir(\"spool\"): $!\n" unless $!{ENOENT}; }

# Close the terminal input and remove the test files if all went well, unless
# the option to save them is set. Always remove the patched Exim binary. Then
# exit normally, or die.

close(T);
system("sudo /bin/rm -rf ./spool test-* ./dnszones/*")
  if ($rc == 0 && !$save_output);

system("sudo /bin/rm -rf ./eximdir/*")
  if (!$save_output);

print "\nYou were in test $test at the end there.\n\n" if defined $test;
exit $rc if ($rc >= 0);
die "** runtest error: $_[1]\n";
}



##################################################
#   Subroutines used by the munging subroutine   #
##################################################

# This function is used for things like message ids, where we want to generate
# more than one value, but keep a consistent mapping throughout.
#
# Arguments:
#   $oldid        the value from the file
#   $base         a base string into which we insert a sequence
#   $sequence     the address of the current sequence counter

sub new_value {
my($oldid, $base, $sequence) = @_;
my($newid) = $cache{$oldid};
if (! defined $newid)
  {
  $newid = sprintf($base, $$sequence++);
  $cache{$oldid} = $newid;
  }
return $newid;
}


# This is used while munging the output from exim_dumpdb.
# May go wrong across DST changes.

sub date_seconds {
my($day,$month,$year,$hour,$min,$sec) =
  $_[0] =~ /^(\d\d)-(\w\w\w)-(\d{4})\s(\d\d):(\d\d):(\d\d)/;
my($mon);
if   ($month =~ /Jan/) {$mon = 0;}
elsif($month =~ /Feb/) {$mon = 1;}
elsif($month =~ /Mar/) {$mon = 2;}
elsif($month =~ /Apr/) {$mon = 3;}
elsif($month =~ /May/) {$mon = 4;}
elsif($month =~ /Jun/) {$mon = 5;}
elsif($month =~ /Jul/) {$mon = 6;}
elsif($month =~ /Aug/) {$mon = 7;}
elsif($month =~ /Sep/) {$mon = 8;}
elsif($month =~ /Oct/) {$mon = 9;}
elsif($month =~ /Nov/) {$mon = 10;}
elsif($month =~ /Dec/) {$mon = 11;}
return timelocal($sec,$min,$hour,$day,$mon,$year);
}


# This is a subroutine to sort maildir files into time-order. The second field
# is the microsecond field, and may vary in length, so must be compared
# numerically.

sub maildirsort {
return $a cmp $b if ($a !~ /^\d+\.H\d/ || $b !~ /^\d+\.H\d/);
my($x1,$y1) = $a =~ /^(\d+)\.H(\d+)/;
my($x2,$y2) = $b =~ /^(\d+)\.H(\d+)/;
return ($x1 != $x2)? ($x1 <=> $x2) : ($y1 <=> $y2);
}



##################################################
#   Subroutine list files below a directory      #
##################################################

# This is used to build up a list of expected mail files below a certain path
# in the directory tree. It has to be recursive in order to deal with multiple
# maildir mailboxes.

sub list_files_below {
my($dir) = $_[0];
my(@yield) = ();
my(@sublist, $file);

opendir(DIR, $dir) || tests_exit(-1, "Failed to open $dir: $!");
@sublist = sort maildirsort readdir(DIR);
closedir(DIR);

foreach $file (@sublist)
  {
  next if $file eq "." || $file eq ".." || $file eq "CVS";
  if (-d "$dir/$file")
    { @yield = (@yield, list_files_below("$dir/$file")); }
  else
    { push @yield, "$dir/$file"; }
  }

return @yield;
}



##################################################
#         Munge a file before comparing          #
##################################################

# The pre-processing turns all dates, times, Exim versions, message ids, and so
# on into standard values, so that the compare works. Perl's substitution with
# an expression provides a neat way to do some of these changes.

# We keep a global associative array for repeatedly turning the same values
# into the same standard values throughout the data from a single test.
# Message ids get this treatment (can't be made reliable for times), and
# times in dumped retry databases are also handled in a special way, as are
# incoming port numbers.

# On entry to the subroutine, the file to write to is already opened with the
# name MUNGED. The input file name is the only argument to the subroutine.
# Certain actions are taken only when the name contains "stderr", "stdout",
# or "log". The yield of the function is 1 if a line matching "*** truncated
# ***" is encountered; otherwise it is 0.

sub munge {
my($file) = $_[0];
my($extra) = $_[1];
my($yield) = 0;
my(@saved) = ();

open(IN, "$file") || tests_exit(-1, "Failed to open $file: $!");

my($is_log) = $file =~ /log/;
my($is_stdout) = $file =~ /stdout/;
my($is_stderr) = $file =~ /stderr/;

# Date pattern

$date = "\\d{2}-\\w{3}-\\d{4}\\s\\d{2}:\\d{2}:\\d{2}";

# Pattern for matching pids at start of stderr lines; initially something
# that won't match.

$spid = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

# Scan the file and make the changes. Near the bottom there are some changes
# that are specific to certain file types, though there are also some of those
# inline too.

while(<IN>)
  {
RESET_AFTER_EXTRA_LINE_READ:
  # Custom munges
  if ($extra)
    {
    next if $extra =~ m%^/%  &&  eval $extra;
    eval $extra if $extra =~ m/^s/;
    }

  # Check for "*** truncated ***"
  $yield = 1 if /\*\*\* truncated \*\*\*/;

  # Replace the name of this host
  s/\Q$parm_hostname\E/the.local.host.name/g;

  # But convert "name=the.local.host address=127.0.0.1" to use "localhost"
  s/name=the\.local\.host address=127\.0\.0\.1/name=localhost address=127.0.0.1/g;

  # The name of the shell may vary
  s/\s\Q$parm_shell\E\b/ ENV_SHELL/;

  # Replace the path to the testsuite directory
  s?\Q$parm_cwd\E?TESTSUITE?g;

  # Replace the Exim version number (may appear in various places)
  # patchexim should have fixed this for us
  #s/(Exim) \d+\.\d+[\w_-]*/$1 x.yz/i;

  # Replace Exim message ids by a unique series
  s/((?:[^\W_]{6}-){2}[^\W_]{2})
    /new_value($1, "10Hm%s-0005vi-00", \$next_msgid)/egx;

  # The names of lock files appear in some error and debug messages
  s/\.lock(\.[-\w]+)+(\.[\da-f]+){2}/.lock.test.ex.dddddddd.pppppppp/;

  # Unless we are in an IPv6 test, replace IPv4 and/or IPv6 in "listening on
  # port" message, because it is not always the same.
  s/port (\d+) \([^)]+\)/port $1/g
    if !$is_ipv6test && m/listening for SMTP(S?) on port/;

  # Challenges in SPA authentication
  s/TlRMTVNTUAACAAAAAAAAAAAoAAABgg[\w+\/]+/TlRMTVNTUAACAAAAAAAAAAAoAAABggAAAEbBRwqFwwIAAAAAAAAAAAAt1sgAAAAA/;

  # PRVS values
  s?prvs=([^/]+)/[\da-f]{10}@?prvs=$1/xxxxxxxxxx@?g;    # Old form
  s?prvs=[\da-f]{10}=([^@]+)@?prvs=xxxxxxxxxx=$1@?g;    # New form

  # Error lines on stdout from SSL contain process id values and file names.
  # They also contain a source file name and line number, which may vary from
  # release to release.
  s/^\d+:error:/pppp:error:/;
  s/:(?:\/[^\s:]+\/)?([^\/\s]+\.c):\d+:/:$1:dddd:/;

  # There are differences in error messages between OpenSSL versions
  s/SSL_CTX_set_cipher_list/SSL_connect/;

  # One error test in expansions mentions base 62 or 36
  s/is not a base (36|62) number/is not a base 36\/62 number/;

  # This message sometimes has a different number of seconds
  s/forced fail after \d seconds/forced fail after d seconds/;

  # This message may contain a different DBM library name
  s/Failed to open \S+( \([^\)]+\))? file/Failed to open DBM file/;

  # The message for a non-listening FIFO varies
  s/:[^:]+: while opening named pipe/: Error: while opening named pipe/;

  # Debugging output of lists of hosts may have different sort keys
  s/sort=\S+/sort=xx/ if /^\S+ (?:\d+\.){3}\d+ mx=\S+ sort=\S+/;

  # Random local part in callout cache testing
  s/myhost.test.ex-\d+-testing/myhost.test.ex-dddddddd-testing/;

  # File descriptor numbers may vary
  s/^writing data block fd=\d+/writing data block fd=dddd/;
  s/running as transport filter: write=\d+ read=\d+/running as transport filter: write=dddd read=dddd/;


  # ======== Dumpdb output ========
  # This must be before the general date/date munging.
  # Time data lines, which look like this:
  # 25-Aug-2000 12:11:37  25-Aug-2000 12:11:37  26-Aug-2000 12:11:37
  if (/^($date)\s+($date)\s+($date)(\s+\*)?\s*$/)
    {
    my($date1,$date2,$date3,$expired) = ($1,$2,$3,$4);
    $expired = "" if !defined $expired;
    my($increment) = date_seconds($date3) - date_seconds($date2);

    # We used to use globally unique replacement values, but timing
    # differences make this impossible. Just show the increment on the
    # last one.

    printf MUNGED ("first failed = time last try = time2 next try = time2 + %s%s\n",
      $increment, $expired);
    next;
    }

  # more_errno values in exim_dumpdb output which are times
  s/T:(\S+)\s-22\s(\S+)\s/T:$1 -22 xxxx /;


  # ======== Dates and times ========

  # Dates and times are all turned into the same value - trying to turn
  # them into different ones cannot be done repeatedly because they are
  # real time stamps generated while running the test. The actual date and
  # time used was fixed when I first started running automatic Exim tests.

  # Date/time in header lines and SMTP responses
  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}
    /Tue, 2 Mar 1999 09:44:33 +0000/gx;

  # Date/time in logs and in one instance of a filter test
  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;
  s/^Logwrite\s"\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d/Logwrite "1999-03-02 09:44:33/gx;

  # Date/time in message separators
  s/(?:[A-Z][a-z]{2}\s){2}\d\d\s\d\d:\d\d:\d\d\s\d\d\d\d
    /Tue Mar 02 09:44:33 1999/gx;

  # Date of message arrival in spool file as shown by -Mvh
  s/^\d{9,10}\s0$/ddddddddd 0/;

  # Date/time in mbx mailbox files
  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;

  # Dates/times in debugging output for writing retry records
  if (/^  first failed=(\d+) last try=(\d+) next try=(\d+) (.*)$/)
    {
    my($next) = $3 - $2;
    $_ = "  first failed=dddd last try=dddd next try=+$next $4\n";
    }
  s/^(\s*)now=\d+ first_failed=\d+ next_try=\d+ expired=(\d)/$1now=tttt first_failed=tttt next_try=tttt expired=$2/;
  s/^(\s*)received_time=\d+ diff=\d+ timeout=(\d+)/$1received_time=tttt diff=tttt timeout=$2/;

  # Time to retry may vary
  s/time to retry = \S+/time to retry = tttt/;
  s/retry record exists: age=\S+/retry record exists: age=ttt/;
  s/failing_interval=\S+ message_age=\S+/failing_interval=ttt message_age=ttt/;

  # Date/time in exim -bV output
  s/\d\d-[A-Z][a-z]{2}-\d{4}\s\d\d:\d\d:\d\d/07-Mar-2000 12:21:52/g;

  # Time on queue tolerance
  s/(QT|D)=1s/$1=0s/;

  # Eximstats heading
  s/Exim\sstatistics\sfrom\s\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d\sto\s
    \d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d/Exim statistics from <time> to <time>/x;

  # Treat ECONNRESET the same as ECONNREFUSED.  At least some systems give
  # us the former on a new connection.
  s/(could not connect to .*: Connection) reset by peer$/$1 refused/;

  # ======== TLS certificate algorithms ========
  # Test machines might have various different TLS library versions supporting
  # different protocols; can't rely upon TLS 1.2's AES256-GCM-SHA384, so we
  # treat the standard algorithms the same.
  # So far, have seen:
  #   TLSv1:AES128-GCM-SHA256:128
  #   TLSv1:AES256-SHA:256
  #   TLSv1.1:AES256-SHA:256
  #   TLSv1.2:AES256-GCM-SHA384:256
  #   TLSv1.2:DHE-RSA-AES256-SHA:256
  #   TLS1.2:DHE_RSA_AES_128_CBC_SHA1:128
  # We also need to handle the ciphersuite without the TLS part present, for
  # client-ssl's output.  We also see some older forced ciphersuites, but
  # negotiating TLS 1.2 instead of 1.0.
  # Mail headers (...), log-lines X=..., client-ssl output ...
  # (and \b doesn't match between ' ' and '(' )

  s/( (?: (?:\b|\s) [\(=] ) | \s )TLSv1\.[12]:/$1TLSv1:/xg;
  s/\bAES128-GCM-SHA256:128\b/AES256-SHA:256/g;
  s/\bAES128-GCM-SHA256\b/AES256-SHA/g;
  s/\bAES256-GCM-SHA384\b/AES256-SHA/g;
  s/\bDHE-RSA-AES256-SHA\b/AES256-SHA/g;

  # GnuTLS have seen:
  #   TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256
  #   TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128
  #   TLS1.2:RSA_AES_256_CBC_SHA1:256 (canonical)
  #   TLS1.2:DHE_RSA_AES_128_CBC_SHA1:128
  #
  #   X=TLS1.2:DHE_RSA_AES_256_CBC_SHA256:256
  #   X=TLS1.2:RSA_AES_256_CBC_SHA1:256
  #   X=TLS1.1:RSA_AES_256_CBC_SHA1:256
  #   X=TLS1.0:DHE_RSA_AES_256_CBC_SHA1:256
  # and as stand-alone cipher:
  #   ECDHE-RSA-AES256-SHA
  #   DHE-RSA-AES256-SHA256
  #   DHE-RSA-AES256-SHA
  # picking latter as canonical simply because regex easier that way.
  s/\bDHE_RSA_AES_128_CBC_SHA1:128/RSA_AES_256_CBC_SHA1:256/g;
  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;
  s/\b(ECDHE-RSA-AES256-SHA|DHE-RSA-AES256-SHA256)\b/AES256-SHA/g;

  # GnuTLS library error message changes
  s/No certificate was found/The peer did not send any certificate/g;
#(dodgy test?)  s/\(certificate verification failed\): invalid/\(gnutls_handshake\): The peer did not send any certificate./g;
  s/\(gnutls_priority_set\): No or insufficient priorities were set/\(gnutls_handshake\): Could not negotiate a supported cipher suite/g;

  # (this new one is a generic channel-read error, but the testsuite
  # only hits it in one place)
  s/TLS error on connection \(gnutls_handshake\): Error in the pull function\./a TLS session is required but an attempt to start TLS failed/g;

  # (replace old with new, hoping that old only happens in one situation)
  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;
  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;

  # signature algorithm names
  s/RSA-SHA1/RSA-SHA/;


  # ======== Caller's login, uid, gid, home, gecos ========

  s/\Q$parm_caller_home\E/CALLER_HOME/g;   # NOTE: these must be done
  s/\b\Q$parm_caller\E\b/CALLER/g;         #       in this order!
  s/\b\Q$parm_caller_group\E\b/CALLER/g;   # In case group name different

  s/\beuid=$parm_caller_uid\b/euid=CALLER_UID/g;
  s/\begid=$parm_caller_gid\b/egid=CALLER_GID/g;

  s/\buid=$parm_caller_uid\b/uid=CALLER_UID/g;
  s/\bgid=$parm_caller_gid\b/gid=CALLER_GID/g;

  s/\bname="?$parm_caller_gecos"?/name=CALLER_GECOS/g;

  # When looking at spool files with -Mvh, we will find not only the caller
  # login, but also the uid and gid. It seems that $) in some Perls gives all
  # the auxiliary gids as well, so don't bother checking for that.

  s/^CALLER $> \d+$/CALLER UID GID/;

  # There is one case where the caller's login is forced to something else,
  # in order to test the processing of logins that contain spaces. Weird what
  # some people do, isn't it?

  s/^spaced user $> \d+$/CALLER UID GID/;


  # ======== Exim's login ========
  # For messages received by the daemon, this is in the -H file, which some
  # tests inspect. For bounce messages, this will appear on the U= lines in
  # logs and also after Received: and in addresses. In one pipe test it appears
  # after "Running as:". It also appears in addresses, and in the names of lock
  # files.

  s/U=$parm_eximuser/U=EXIMUSER/;
  s/user=$parm_eximuser/user=EXIMUSER/;
  s/login=$parm_eximuser/login=EXIMUSER/;
  s/Received: from $parm_eximuser /Received: from EXIMUSER /;
  s/Running as: $parm_eximuser/Running as: EXIMUSER/;
  s/\b$parm_eximuser@/EXIMUSER@/;
  s/\b$parm_eximuser\.lock\./EXIMUSER.lock./;

  s/\beuid=$parm_exim_uid\b/euid=EXIM_UID/g;
  s/\begid=$parm_exim_gid\b/egid=EXIM_GID/g;

  s/\buid=$parm_exim_uid\b/uid=EXIM_UID/g;
  s/\bgid=$parm_exim_gid\b/gid=EXIM_GID/g;

  s/^$parm_eximuser $parm_exim_uid $parm_exim_gid/EXIMUSER EXIM_UID EXIM_GID/;


  # ======== General uids, gids, and pids ========
  # Note: this must come after munges for caller's and exim's uid/gid

  # These are for systems where long int is 64
  s/\buid=4294967295/uid=-1/;
  s/\beuid=4294967295/euid=-1/;
  s/\bgid=4294967295/gid=-1/;
  s/\begid=4294967295/egid=-1/;

  s/\bgid=\d+/gid=gggg/;
  s/\begid=\d+/egid=gggg/;
  s/\bpid=\d+/pid=pppp/;
  s/\buid=\d+/uid=uuuu/;
  s/\beuid=\d+/euid=uuuu/;
  s/set_process_info:\s+\d+/set_process_info: pppp/;
  s/queue run pid \d+/queue run pid ppppp/;
  s/process \d+ running as transport filter/process pppp running as transport filter/;
  s/process \d+ writing to transport filter/process pppp writing to transport filter/;
  s/reading pipe for subprocess \d+/reading pipe for subprocess pppp/;
  s/remote delivery process \d+ ended/remote delivery process pppp ended/;

  # Pid in temp file in appendfile transport
  s"test-mail/temp\.\d+\."test-mail/temp.pppp.";

  # Optional pid in log lines
  s/^(\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d)(\s[+-]\d\d\d\d|)(\s\[\d+\])/
    "$1$2 [" . new_value($3, "%s", \$next_pid) . "]"/gxe;

  # Detect a daemon stderr line with a pid and save the pid for subsequent
  # removal from following lines.
  $spid = $1 if /^(\s*\d+) (?:listening|LOG: MAIN|(?:daemon_smtp_port|local_interfaces) overridden by)/;
  s/^$spid //;

  # Queue runner waiting messages
  s/waiting for children of \d+/waiting for children of pppp/;
  s/waiting for (\S+) \(\d+\)/waiting for $1 (pppp)/;

  # ======== Port numbers ========
  # Incoming port numbers may vary, but not in daemon startup line.

  s/^Port: (\d+)/"Port: " . new_value($1, "%s", \$next_port)/e;
  s/\(port=(\d+)/"(port=" . new_value($1, "%s", \$next_port)/e;

  # This handles "connection from" and the like, when the port is given
  if (!/listening for SMTP on/ && !/Connecting to/ && !/=>/ && !/->/
      && !/\*>/ && !/Connection refused/)
    {
    s/\[([a-z\d:]+|\d+(?:\.\d+){3})\]:(\d+)/"[".$1."]:".new_value($2,"%s",\$next_port)/ie;
    }

  # Port in host address in spool file output from -Mvh
  s/^-host_address (.*)\.\d+/-host_address $1.9999/;


  # ======== Local IP addresses ========
  # The amount of space between "host" and the address in verification output
  # depends on the length of the host name. We therefore reduce it to one space
  # for all of them.
  # Also, the length of space at the end of the host line is dependent
  # on the length of the longest line, so strip it also on otherwise
  # un-rewritten lines like localhost

  s/^\s+host\s(\S+)\s+(\S+)/  host $1 $2/;
  s/^\s+(host\s\S+\s\S+)\s+(port=.*)/  host $1 $2/;
  s/^\s+(host\s\S+\s\S+)\s+(?=MX=)/  $1 /;
  s/host\s\Q$parm_ipv4\E\s\[\Q$parm_ipv4\E\]/host ipv4.ipv4.ipv4.ipv4 [ipv4.ipv4.ipv4.ipv4]/;
  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]/;
  s/\b\Q$parm_ipv4\E\b/ip4.ip4.ip4.ip4/g;
  s/(^|\W)\K\Q$parm_ipv6\E/ip6:ip6:ip6:ip6:ip6:ip6:ip6:ip6/g;
  s/\b\Q$parm_ipv4r\E\b/ip4-reverse/g;
  s/(^|\W)\K\Q$parm_ipv6r\E/ip6-reverse/g;
  s/^(\s+host\s\S+\s+\[\S+\]) +$/$1 /;


  # ======== Test network IP addresses ========
  s/(\b|_)\Q$parm_ipv4_test_net\E(?=\.\d+\.\d+\.\d+\b|_|\.rbl|\.in-addr|\.test\.again\.dns)/$1V4NET/g;
  s/\b\Q$parm_ipv6_test_net\E(?=:[\da-f]+:[\da-f]+:[\da-f]+)/V6NET/gi;


  # ======== IP error numbers and messages ========
  # These vary between operating systems
  s/Can't assign requested address/Network Error/;
  s/Cannot assign requested address/Network Error/;
  s/Operation timed out/Connection timed out/;
  s/Address family not supported by protocol family/Network Error/;
  s/Network is unreachable/Network Error/;
  s/Invalid argument/Network Error/;

  s/\(\d+\): Network/(dd): Network/;
  s/\(\d+\): Connection refused/(dd): Connection refused/;
  s/\(\d+\): Connection timed out/(dd): Connection timed out/;
  s/\d+ 65 Connection refused/dd 65 Connection refused/;
  s/\d+ 321 Connection timed out/dd 321 Connection timed out/;


  # ======== Other error numbers ========
  s/errno=\d+/errno=dd/g;


  # ======== Output from ls ========
  # Different operating systems use different spacing on long output
  #s/ +/ /g if /^[-rwd]{10} /;
  # (Bug 1226) SUSv3 allows a trailing printable char for modified access method control.
  # Handle only the Gnu and MacOS space, dot, plus and at-sign.  A full [[:graph:]]
  # unfortunately matches a non-ls linefull of dashes.
  # Allow the case where we've already picked out the file protection bits.
  if (s/^([-d](?:[-r][-w][-SsTtx]){3})[.+@]?( +|$)/$1$2/) {
    s/ +/ /g;
  }


  # ======== Message sizes =========
  # Message sizes vary, owing to different logins and host names that get
  # automatically inserted. I can't think of any way of even approximately
  # comparing these.

  s/([\s,])S=\d+\b/$1S=sss/;
  s/:S\d+\b/:Ssss/;
  s/^(\s*\d+m\s+)\d+(\s+[a-z0-9-]{16} <)/$1sss$2/i if $is_stdout;
  s/\sSIZE=\d+\b/ SIZE=ssss/;
  s/\ssize=\d+\b/ size=sss/ if $is_stderr;
  s/old size = \d+\b/old size = sssss/;
  s/message size = \d+\b/message size = sss/;
  s/this message = \d+\b/this message = sss/;
  s/Size of headers = \d+/Size of headers = sss/;
  s/sum=(?!0)\d+/sum=dddd/;
  s/(?<=sum=dddd )count=(?!0)\d+\b/count=dd/;
  s/(?<=sum=0 )count=(?!0)\d+\b/count=dd/;
  s/,S is \d+\b/,S is ddddd/;
  s/\+0100,\d+;/+0100,ddd;/;
  s/\(\d+ bytes written\)/(ddd bytes written)/;
  s/added '\d+ 1'/added 'ddd 1'/;
  s/Received\s+\d+/Received               nnn/;
  s/Delivered\s+\d+/Delivered              nnn/;


  # ======== Values in spool space failure message ========
  s/space=\d+ inodes=[+-]?\d+/space=xxxxx inodes=xxxxx/;


  # ======== Filter sizes ========
  # The sizes of filter files may vary because of the substitution of local
  # filenames, logins, etc.

  s/^\d+(?= bytes read from )/ssss/;


  # ======== OpenSSL error messages ========
  # Different releases of the OpenSSL libraries seem to give different error
  # numbers, or handle specific bad conditions in different ways, leading to
  # different wording in the error messages, so we cannot compare them.

  s/(TLS error on connection (?:from .* )?\(SSL_\w+\): error:)(.*)/$1 <<detail omitted>>/;

  # ======== Maildir things ========
  # timestamp output in maildir processing
  s/(timestamp=|\(timestamp_only\): )\d+/$1ddddddd/g;

  # maildir delivery files appearing in log lines (in cases of error)
  s/writing to(?: file)? tmp\/\d+\.[^.]+\.(\S+)/writing to tmp\/MAILDIR.$1/;

  s/renamed tmp\/\d+\.[^.]+\.(\S+) as new\/\d+\.[^.]+\.(\S+)/renamed tmp\/MAILDIR.$1 as new\/MAILDIR.$1/;

  # Maildir file names in general
  s/\b\d+\.H\d+P\d+\b/dddddddddd.HddddddPddddd/;

  # Maildirsize data
  while (/^\d+S,\d+C\s*$/)
    {
    print MUNGED;
    while (<IN>)
      {
      last if !/^\d+ \d+\s*$/;
      print MUNGED "ddd d\n";
      }
    last if !defined $_;
    }
  last if !defined $_;


  # ======== Output from the "fd" program about open descriptors ========
  # The statuses seem to be different on different operating systems, but
  # at least we'll still be checking the number of open fd's.

  s/max fd = \d+/max fd = dddd/;
  s/status=0 RDONLY/STATUS/g;
  s/status=1 WRONLY/STATUS/g;
  s/status=2 RDWR/STATUS/g;


  # ======== Contents of spool files ========
  # A couple of tests dump the contents of the -H file. The length fields
  # will be wrong because of different user names, etc.
  s/^\d\d\d(?=[PFS*])/ddd/;


  # ========= Exim lookups ==================
  # Lookups have a char which depends on the number of lookup types compiled in,
  # in stderr output.  Replace with a "0".  Recognising this while avoiding
  # other output is fragile; perhaps the debug output should be revised instead.
  s%(?<!sqlite)(?<!lsearch\*@)(?<!lsearch\*)(?<!lsearch)[0-?]TESTSUITE/aux-fixed/%0TESTSUITE/aux-fixed/%g;

  # ==========================================================
  # MIME boundaries in RFC3461 DSN messages
  s/\d{8,10}-eximdsn-\d+/NNNNNNNNNN-eximdsn-MMMMMMMMMM/;

  # ==========================================================
  # Some munging is specific to the specific file types

  # ======== stdout ========

  if ($is_stdout)
    {
    # Skip translate_ip_address and use_classresources in -bP output because
    # they aren't always there.

    next if /translate_ip_address =/;
    next if /use_classresources/;

    # In certain filter tests, remove initial filter lines because they just
    # clog up by repetition.

    if ($rmfiltertest)
      {
      next if /^(Sender\staken\sfrom|
                 Return-path\scopied\sfrom|
                 Sender\s+=|
                 Recipient\s+=)/x;
      if (/^Testing \S+ filter/)
        {
        $_ = <IN>;    # remove blank line
        next;
        }
      }

    # openssl version variances
    next if /^SSL info: unknown state/;
    next if /^SSL info: SSLv2\/v3 write client hello A/;
    next if /^SSL info: SSLv3 read server key exchange A/;

    }

  # ======== stderr ========

  elsif ($is_stderr)
    {
    # The very first line of debugging output will vary

    s/^Exim version .*/Exim version x.yz ..../;

    # Debugging lines for Exim terminations

    s/(?<=^>>>>>>>>>>>>>>>> Exim pid=)\d+(?= terminating)/pppp/;

    # IP address lookups use gethostbyname() when IPv6 is not supported,
    # and gethostbyname2() or getipnodebyname() when it is.

    s/\bgethostbyname2?|\bgetipnodebyname/get[host|ipnode]byname[2]/;

    # drop gnutls version strings
    next if /GnuTLS compile-time version: \d+[\.\d]+$/;
    next if /GnuTLS runtime version: \d+[\.\d]+$/;

    # drop openssl version strings
    next if /OpenSSL compile-time version: OpenSSL \d+[\.\da-z]+/;
    next if /OpenSSL runtime version: OpenSSL \d+[\.\da-z]+/;

    # drop lookups
    next if /^Lookups \(built-in\):/;
    next if /^Loading lookup modules from/;
    next if /^Loaded \d+ lookup modules/;
    next if /^Total \d+ lookups/;

    # drop compiler information
    next if /^Compiler:/;

    # and the ugly bit
    # different libraries will have different numbers (possibly 0) of follow-up
    # lines, indenting with more data
    if (/^Library version:/) {
      while (1) {
	$_ = <IN>;
	next if /^\s/;
	goto RESET_AFTER_EXTRA_LINE_READ;
      }
    }

    # drop other build-time controls emitted for debugging
    next if /^WHITELIST_D_MACROS:/;
    next if /^TRUSTED_CONFIG_LIST:/;

    # As of Exim 4.74, we log when a setgid fails; because we invoke Exim
    # with -be, privileges will have been dropped, so this will always
    # be the case
    next if /^changing group to \d+ failed: (Operation not permitted|Not owner)/;

    # We might not keep this check; rather than change all the tests, just
    # ignore it as long as it succeeds; then we only need to change the
    # TLS tests where tls_require_ciphers has been set.
    if (m{^changed uid/gid: calling tls_validate_require_cipher}) {
      my $discard = <IN>;
      next;
    }
    next if /^tls_validate_require_cipher child \d+ ended: status=0x0/;

    # We invoke Exim with -D, so we hit this new messag as of Exim 4.73:
    next if /^macros_trusted overridden to true by whitelisting/;

    # We have to omit the localhost ::1 address so that all is well in
    # the IPv4-only case.

    print MUNGED "MUNGED: ::1 will be omitted in what follows\n"
      if (/looked up these IP addresses/);
    next if /name=localhost address=::1/;

    # drop pdkim debugging header
    next if /^PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<+$/;

    # Various other IPv6 lines must be omitted too

    next if /using host_fake_gethostbyname for \S+ \(IPv6\)/;
    next if /get\[host\|ipnode\]byname\[2\]\(af=inet6\)/;
    next if /DNS lookup of \S+ \(AAAA\) using fakens/;
    next if / in dns_ipv4_lookup?/;

    if (/DNS lookup of \S+ \(AAAA\) gave NO_DATA/)
      {
      $_= <IN>;     # Gets "returning DNS_NODATA"
      next;
      }

    # Skip tls_advertise_hosts and hosts_require_tls checks when the options
    # are unset, because tls ain't always there.

    next if /in\s(?:tls_advertise_hosts\?|hosts_require_tls\?)
                \sno\s\(option\sunset\)/x;

    # Skip auxiliary group lists because they will vary.

    next if /auxiliary group list:/;

    # Skip "extracted from gecos field" because the gecos field varies

    next if /extracted from gecos field/;

    # Skip "waiting for data on socket" and "read response data: size=" lines
    # because some systems pack more stuff into packets than others.

    next if /waiting for data on socket/;
    next if /read response data: size=/;

    # If Exim is compiled with readline support but it can't find the library
    # to load, there will be an extra debug line. Omit it.

    next if /failed to load readline:/;

    # Some DBM libraries seem to make DBM files on opening with O_RDWR without
    # O_CREAT; other's don't. In the latter case there is some debugging output
    # which is not present in the former. Skip the relevant lines (there are
    # two of them).

    if (/TESTSUITE\/spool\/db\/\S+ appears not to exist: trying to create/)
      {
      $_ = <IN>;
      next;
      }

    # Some tests turn on +expand debugging to check on expansions.
    # Unfortunately, the Received: expansion varies, depending on whether TLS
    # is compiled or not. So we must remove the relevant debugging if it is.

    if (/^condition: def:tls_cipher/)
      {
      while (<IN>) { last if /^condition: def:sender_address/; }
      }
    elsif (/^expanding: Received: /)
      {
      while (<IN>) { last if !/^\s/; }
      }

    # When Exim is checking the size of directories for maildir, it uses
    # the check_dir_size() function to scan directories. Of course, the order
    # of the files that are obtained using readdir() varies from system to
    # system. We therefore buffer up debugging lines from check_dir_size()
    # and sort them before outputting them.

    if (/^check_dir_size:/ || /^skipping TESTSUITE\/test-mail\//)
      {
      push @saved, $_;
      }
    else
      {
      if (@saved > 0)
        {
        print MUNGED "MUNGED: the check_dir_size lines have been sorted " .
          "to ensure consistency\n";
        @saved = sort(@saved);
        print MUNGED @saved;
        @saved = ();
        }

    # Skip hosts_require_dane checks when the options
    # are unset, because dane ain't always there.

    next if /in\shosts_require_dane\?\sno\s\(option\sunset\)/x;

      # Skip some lines that Exim puts out at the start of debugging output
      # because they will be different in different binaries.

      print MUNGED
        unless (/^Berkeley DB: / ||
                /^Probably (?:Berkeley DB|ndbm|GDBM)/ ||
                /^Authenticators:/ ||
                /^Lookups:/ ||
                /^Support for:/ ||
                /^Routers:/ ||
                /^Transports:/ ||
                /^log selectors =/ ||
                /^cwd=/ ||
                /^Fixed never_users:/ ||
                /^Size of off_t:/
                );
      }

    next;
    }

  # ======== log ========

  elsif ($is_log)
    {
    # Berkeley DB version differences
    next if / Berkeley DB error: /;
    }

  # ======== All files other than stderr ========

  print MUNGED;
  }

close(IN);
return $yield;
}




##################################################
#        Subroutine to interact with caller      #
##################################################

# Arguments: [0] the prompt string
#            [1] if there is a U in the prompt and $force_update is true
#            [2] if there is a C in the prompt and $force_continue is true
# Returns:   nothing (it sets $_)

sub interact{
print $_[0];
if ($_[1]) { $_ = "u"; print "... update forced\n"; }
  elsif ($_[2]) { $_ = "c"; print "... continue forced\n"; }
  else { $_ = <T>; }
}



##################################################
#    Subroutine to log in force_continue mode    #
##################################################

# In force_continue mode, we just want a terse output to a statically
# named logfile.  If multiple files in same batch (stdout, stderr, etc)
# all have mismatches, it will log multiple times.
#
# Arguments: [0] the logfile to append to
#            [1] the testno that failed
# Returns:   nothing



sub log_failure {
  my $logfile = shift();
  my $testno  = shift();
  my $detail  = shift() || '';
  if ( open(my $fh, ">>", $logfile) ) {
    print $fh "Test $testno $detail failed\n";
    close $fh;
  }
}



##################################################
#    Subroutine to compare one output file       #
##################################################

# When an Exim server is part of the test, its output is in separate files from
# an Exim client. The server data is concatenated with the client data as part
# of the munging operation.
#
# Arguments:  [0] the name of the main raw output file
#             [1] the name of the server raw output file or undef
#             [2] where to put the munged copy
#             [3] the name of the saved file
#             [4] TRUE if this is a log file whose deliveries must be sorted
#             [5] optionally, a custom munge command
#
# Returns:    0 comparison succeeded or differences to be ignored
#             1 comparison failed; files may have been updated (=> re-compare)
#
# Does not return if the user replies "Q" to a prompt.

sub check_file{
my($rf,$rsf,$mf,$sf,$sortfile,$extra) = @_;

# If there is no saved file, the raw files must either not exist, or be
# empty. The test ! -s is TRUE if the file does not exist or is empty.

if (! -e $sf)
  {
  return 0 if (! -s $rf && (! defined $rsf || ! -s $rsf));

  print "\n";
  print "** $rf is not empty\n" if (-s $rf);
  print "** $rsf is not empty\n" if (defined $rsf && -s $rsf);

  for (;;)
    {
    print "Continue, Show, or Quit? [Q] ";
    $_ = $force_continue ? "c" : <T>;
    tests_exit(1) if /^q?$/i;
    log_failure($log_failed_filename, $testno, $rf) if (/^c$/i && $force_continue);
    return 0 if /^c$/i;
    last if (/^s$/);
    }

  foreach $f ($rf, $rsf)
    {
    if (defined $f && -s $f)
      {
      print "\n";
      print "------------ $f -----------\n"
        if (defined $rf && -s $rf && defined $rsf && -s $rsf);
      system("$more '$f'");
      }
    }

  print "\n";
  for (;;)
    {
    interact("Continue, Update & retry, Quit? [Q] ", $force_update, $force_continue);
    tests_exit(1) if /^q?$/i;
    log_failure($log_failed_filename, $testno, $rsf) if (/^c$/i && $force_continue);
    return 0 if /^c$/i;
    last if (/^u$/i);
    }
  }

# Control reaches here if either (a) there is a saved file ($sf), or (b) there
# was a request to create a saved file. First, create the munged file from any
# data that does exist.

open(MUNGED, ">$mf") || tests_exit(-1, "Failed to open $mf: $!");
my($truncated) = munge($rf, $extra) if -e $rf;
if (defined $rsf && -e $rsf)
  {
  print MUNGED "\n******** SERVER ********\n";
  $truncated |= munge($rsf, $extra);
  }
close(MUNGED);

# If a saved file exists, do the comparison. There are two awkward cases:
#
# If "*** truncated ***" was found in the new file, it means that a log line
# was overlong, and truncated. The problem is that it may be truncated at
# different points on different systems, because of different user name
# lengths. We reload the file and the saved file, and remove lines from the new
# file that precede "*** truncated ***" until we reach one that matches the
# line that precedes it in the saved file.
#
# If $sortfile is set, we are dealing with a mainlog file where the deliveries
# for an individual message might vary in their order from system to system, as
# a result of parallel deliveries. We load the munged file and sort sequences
# of delivery lines.

if (-e $sf)
  {
  # Deal with truncated text items

  if ($truncated)
    {
    my(@munged, @saved, $i, $j, $k);

    open(MUNGED, "$mf") || tests_exit(-1, "Failed to open $mf: $!");
    @munged = <MUNGED>;
    close(MUNGED);
    open(SAVED, "$sf") || tests_exit(-1, "Failed to open $sf: $!");
    @saved = <SAVED>;
    close(SAVED);

    $j = 0;
    for ($i = 0; $i < @munged; $i++)
      {
      if ($munged[$i] =~ /\*\*\* truncated \*\*\*/)
        {
        for (; $j < @saved; $j++)
          { last if $saved[$j] =~ /\*\*\* truncated \*\*\*/; }
        last if $j >= @saved;     # not found in saved

        for ($k = $i - 1; $k >= 0; $k--)
          { last if $munged[$k] eq $saved[$j - 1]; }

        last if $k <= 0;          # failed to find previous match
        splice @munged, $k + 1, $i - $k - 1;
        $i = $k + 1;
        }
      }

    open(MUNGED, ">$mf") || tests_exit(-1, "Failed to open $mf: $!");
    for ($i = 0; $i < @munged; $i++)
      { print MUNGED $munged[$i]; }
    close(MUNGED);
    }

  # Deal with log sorting

  if ($sortfile)
    {
    my(@munged, $i, $j);

    open(MUNGED, "$mf") || tests_exit(-1, "Failed to open $mf: $!");
    @munged = <MUNGED>;
    close(MUNGED);

    for ($i = 0; $i < @munged; $i++)
      {
      if ($munged[$i] =~ /^[-\d]{10}\s[:\d]{8}\s[-A-Za-z\d]{16}\s[-=*]>/)
        {
        for ($j = $i + 1; $j < @munged; $j++)
          {
          last if $munged[$j] !~
            /^[-\d]{10}\s[:\d]{8}\s[-A-Za-z\d]{16}\s[-=*]>/;
          }
        @temp = splice(@munged, $i, $j - $i);
        @temp = sort(@temp);
        splice(@munged, $i, 0, @temp);
        }
      }

    open(MUNGED, ">$mf") || tests_exit(-1, "Failed to open $mf: $!");
    print MUNGED "**NOTE: The delivery lines in this file have been sorted.\n";
    for ($i = 0; $i < @munged; $i++)
      { print MUNGED $munged[$i]; }
    close(MUNGED);
    }

  # Do the comparison

  return 0 if (system("$cf '$mf' '$sf' >test-cf") == 0);

  # Handle comparison failure

  print "** Comparison of $mf with $sf failed";
  system("$more test-cf");

  print "\n";
  for (;;)
    {
    interact("Continue, Retry, Update & retry, Quit? [Q] ", $force_update, $force_continue);
    tests_exit(1) if /^q?$/i;
    log_failure($log_failed_filename, $testno, $sf) if (/^c$/i && $force_continue);
    return 0 if /^c$/i;
    return 1 if /^r$/i;
    last if (/^u$/i);
    }
  }

# Update or delete the saved file, and give the appropriate return code.

if (-s $mf)
  { tests_exit(-1, "Failed to cp $mf $sf") if system("cp '$mf' '$sf'") != 0; }
else
  { tests_exit(-1, "Failed to unlink $sf") if !unlink($sf); }

return 1;
}



##################################################
# Custom munges
# keyed by name of munge; value is a ref to a hash
# which is keyed by file, value a string to look for.
# Usable files are:
#  paniclog, rejectlog, mainlog, stdout, stderr, msglog, mail
# Search strings starting with 's' do substitutions;
# with '/' do line-skips.
# Triggered by a scriptfile line "munge <name>"
##################################################
$munges =
  { 'dnssec' =>
    { 'stderr' => '/^Reverse DNS security status: unverified\n/' },

    'gnutls_unexpected' =>
    { 'mainlog' => '/\(recv\): A TLS packet with unexpected length was received./' },

    'gnutls_handshake' =>
    { 'mainlog' => 's/\(gnutls_handshake\): Error in the push function/\(gnutls_handshake\): A TLS packet with unexpected length was received/' },

    'optional_events' =>
    { 'stdout' => '/event_action =/' },

    'optional_ocsp' =>
    { 'stderr' => '/127.0.0.1 in hosts_requ(ire|est)_ocsp/' },

    'no_tpt_filter_epipe' =>
    { 'stderr' => '/^writing error 32: Broken pipe$/' },

    'optional_cert_hostnames' =>
    { 'stderr' => '/in tls_verify_cert_hostnames\? no/' },

  };


##################################################
#    Subroutine to check the output of a test    #
##################################################

# This function is called when the series of subtests is complete. It makes
# use of check_file(), whose arguments are:
#
#  [0] the name of the main raw output file
#  [1] the name of the server raw output file or undef
#  [2] where to put the munged copy
#  [3] the name of the saved file
#  [4] TRUE if this is a log file whose deliveries must be sorted
#  [5] an optional custom munge command
#
# Arguments: Optionally, name of a custom munge to run.
# Returns:   0 if the output compared equal
#            1 if re-run needed (files may have been updated)

sub check_output{
my($mungename) = $_[0];
my($yield) = 0;
my($munge) = $munges->{$mungename} if defined $mungename;

$yield = 1 if check_file("spool/log/paniclog",
                       "spool/log/serverpaniclog",
                       "test-paniclog-munged",
                       "paniclog/$testno", 0,
		       $munge->{'paniclog'});

$yield = 1 if check_file("spool/log/rejectlog",
                       "spool/log/serverrejectlog",
                       "test-rejectlog-munged",
                       "rejectlog/$testno", 0,
		       $munge->{'rejectlog'});

$yield = 1 if check_file("spool/log/mainlog",
                       "spool/log/servermainlog",
                       "test-mainlog-munged",
                       "log/$testno", $sortlog,
		       $munge->{'mainlog'});

if (!$stdout_skip)
  {
  $yield = 1 if check_file("test-stdout",
                       "test-stdout-server",
                       "test-stdout-munged",
                       "stdout/$testno", 0,
		       $munge->{'stdout'});
  }

if (!$stderr_skip)
  {
  $yield = 1 if check_file("test-stderr",
                       "test-stderr-server",
                       "test-stderr-munged",
                       "stderr/$testno", 0,
		       $munge->{'stderr'});
  }

# Compare any delivered messages, unless this test is skipped.

if (! $message_skip)
  {
  my($msgno) = 0;

  # Get a list of expected mailbox files for this script. We don't bother with
  # directories, just the files within them.

  foreach $oldmail (@oldmails)
    {
    next unless $oldmail =~ /^mail\/$testno\./;
    print ">> EXPECT $oldmail\n" if $debug;
    $expected_mails{$oldmail} = 1;
    }

  # If there are any files in test-mail, compare them. Note that "." and
  # ".." are automatically omitted by list_files_below().

  @mails = list_files_below("test-mail");

  foreach $mail (@mails)
    {
    next if $mail eq "test-mail/oncelog";

    $saved_mail = substr($mail, 10);               # Remove "test-mail/"
    $saved_mail =~ s/^$parm_caller(\/|$)/CALLER/;  # Convert caller name

    if ($saved_mail =~ /(\d+\.[^.]+\.)/)
      {
      $msgno++;
      $saved_mail =~ s/(\d+\.[^.]+\.)/$msgno./gx;
      }

    print ">> COMPARE $mail mail/$testno.$saved_mail\n" if $debug;
    $yield = 1 if check_file($mail, undef, "test-mail-munged",
      "mail/$testno.$saved_mail", 0,
      $munge->{'mail'});
    delete $expected_mails{"mail/$testno.$saved_mail"};
    }

  # Complain if not all expected mails have been found

  if (scalar(keys %expected_mails) != 0)
    {
    foreach $key (keys %expected_mails)
      { print "** no test file found for $key\n"; }

    for (;;)
      {
      interact("Continue, Update & retry, or Quit? [Q] ", $force_update, $force_continue);
      tests_exit(1) if /^q?$/i;
      log_failure($log_failed_filename, $testno, "missing email") if (/^c$/i && $force_continue);
      last if /^c$/i;

      # For update, we not only have to unlink the file, but we must also
      # remove it from the @oldmails vector, as otherwise it will still be
      # checked for when we re-run the test.

      if (/^u$/i)
        {
        foreach $key (keys %expected_mails)
          {
          my($i);
          tests_exit(-1, "Failed to unlink $key") if !unlink("$key");
          for ($i = 0; $i < @oldmails; $i++)
            {
            if ($oldmails[$i] eq $key)
              {
              splice @oldmails, $i, 1;
              last;
              }
            }
          }
        last;
        }
      }
    }
  }

# Compare any remaining message logs, unless this test is skipped.

if (! $msglog_skip)
  {
  # Get a list of expected msglog files for this test

  foreach $oldmsglog (@oldmsglogs)
    {
    next unless $oldmsglog =~ /^$testno\./;
    $expected_msglogs{$oldmsglog} = 1;
    }

  # If there are any files in spool/msglog, compare them. However, we have
  # to munge the file names because they are message ids, which are
  # time dependent.

  if (opendir(DIR, "spool/msglog"))
    {
    @msglogs = sort readdir(DIR);
    closedir(DIR);

    foreach $msglog (@msglogs)
      {
      next if ($msglog eq "." || $msglog eq ".." || $msglog eq "CVS");
      ($munged_msglog = $msglog) =~
        s/((?:[^\W_]{6}-){2}[^\W_]{2})
          /new_value($1, "10Hm%s-0005vi-00", \$next_msgid)/egx;
      $yield = 1 if check_file("spool/msglog/$msglog", undef,
        "test-msglog-munged", "msglog/$testno.$munged_msglog", 0,
        $munge->{'msglog'});
      delete $expected_msglogs{"$testno.$munged_msglog"};
      }
    }

  # Complain if not all expected msglogs have been found

  if (scalar(keys %expected_msglogs) != 0)
    {
    foreach $key (keys %expected_msglogs)
      {
      print "** no test msglog found for msglog/$key\n";
      ($msgid) = $key =~ /^\d+\.(.*)$/;
      foreach $cachekey (keys %cache)
        {
        if ($cache{$cachekey} eq $msgid)
          {
          print "** original msgid $cachekey\n";
          last;
          }
        }
      }

    for (;;)
      {
      interact("Continue, Update, or Quit? [Q] ", $force_update, $force_continue);
      tests_exit(1) if /^q?$/i;
      log_failure($log_failed_filename, $testno, "missing msglog") if (/^c$/i && $force_continue);
      last if /^c$/i;
      if (/^u$/i)
        {
        foreach $key (keys %expected_msglogs)
          {
          tests_exit(-1, "Failed to unlink msglog/$key")
            if !unlink("msglog/$key");
          }
        last;
        }
      }
    }
  }

return $yield;
}



##################################################
#     Subroutine to run one "system" command     #
##################################################

# We put this in a subroutine so that the command can be reflected when
# debugging.
#
# Argument: the command to be run
# Returns:  nothing

sub run_system {
my($cmd) = $_[0];
if ($debug)
  {
  my($prcmd) = $cmd;
  $prcmd =~ s/; /;\n>> /;
  print ">> $prcmd\n";
  }
system("$cmd");
}



##################################################
#      Subroutine to run one script command      #
##################################################

# The <SCRIPT> file is open for us to read an optional return code line,
# followed by the command line and any following data lines for stdin. The
# command line can be continued by the use of \. Data lines are not continued
# in this way. In all lines, the following substutions are made:
#
# DIR    => the current directory
# CALLER => the caller of this script
#
# Arguments: the current test number
#            reference to the subtest number, holding previous value
#            reference to the expected return code value
#            reference to where to put the command name (for messages)
#            auxilliary information returned from a previous run
#
# Returns:   0 the commmand was executed inline, no subprocess was run
#            1 a non-exim command was run and waited for
#            2 an exim command was run and waited for
#            3 a command was run and not waited for (daemon, server, exim_lock)
#            4 EOF was encountered after an initial return code line
# Optionally alse a second parameter, a hash-ref, with auxilliary information:
#            exim_pid: pid of a run process
#            munge: name of a post-script results munger

sub run_command{
my($testno) = $_[0];
my($subtestref) = $_[1];
my($commandnameref) = $_[3];
my($aux_info) = $_[4];
my($yield) = 1;

if (/^(\d+)\s*$/)                # Handle unusual return code
  {
  my($r) = $_[2];
  $$r = $1 << 8;
  $_ = <SCRIPT>;
  return 4 if !defined $_;       # Missing command
  $lineno++;
  }

chomp;
$wait_time = 0;

# Handle concatenated command lines

s/\s+$//;
while (substr($_, -1) eq"\\")
  {
  my($temp);
  $_ = substr($_, 0, -1);
  chomp($temp = <SCRIPT>);
  if (defined $temp)
    {
    $lineno++;
    $temp =~ s/\s+$//;
    $temp =~ s/^\s+//;
    $_ .= $temp;
    }
  }

# Do substitutions

do_substitute($testno);
if ($debug) { printf ">> $_\n"; }

# Pass back the command name (for messages)

($$commandnameref) = /^(\S+)/;

# Here follows code for handling the various different commands that are
# supported by this script. The first group of commands are all freestanding
# in that they share no common code and are not followed by any data lines.


###################
###################

# The "dbmbuild" command runs exim_dbmbuild. This is used both to test the
# utility and to make DBM files for testing DBM lookups.

if (/^dbmbuild\s+(\S+)\s+(\S+)/)
  {
  run_system("(./eximdir/exim_dbmbuild $parm_cwd/$1 $parm_cwd/$2;" .
         "echo exim_dbmbuild exit code = \$?)" .
         ">>test-stdout");
  return 1;
  }


# The "dump" command runs exim_dumpdb. On different systems, the output for
# some types of dump may appear in a different order because it's just hauled
# out of the DBM file. We can solve this by sorting. Ignore the leading
# date/time, as it will be flattened later during munging.

if (/^dump\s+(\S+)/)
  {
  my($which) = $1;
  my(@temp);
  print ">> ./eximdir/exim_dumpdb $parm_cwd/spool $which\n" if $debug;
  open(IN, "./eximdir/exim_dumpdb $parm_cwd/spool $which |");
  open(OUT, ">>test-stdout");
  print OUT "+++++++++++++++++++++++++++\n";

  if ($which eq "retry")
    {
    $/ = "\n  ";
    @temp = <IN>;
    $/ = "\n";

    @temp = sort {
                   my($aa) = split(' ', $a);
                   my($bb) = split(' ', $b);
                   return $aa cmp $bb;
                 } @temp;

    foreach $item (@temp)
      {
      $item =~ s/^\s*(.*)\n(.*)\n?\s*$/$1\n$2/m;
      print OUT "  $item\n";
      }
    }
  else
    {
    @temp = <IN>;
    if ($which eq "callout")
      {
      @temp = sort {
                   my($aa) = substr $a, 21;
                   my($bb) = substr $b, 21;
                   return $aa cmp $bb;
                   } @temp;
      }
    print OUT @temp;
    }

  close(IN);
  close(OUT);
  return 1;
  }


# The "echo" command is a way of writing comments to the screen.

if (/^echo\s+(.*)$/)
  {
  print "$1\n";
  return 0;
  }


# The "exim_lock" command runs exim_lock in the same manner as "server",
# but it doesn't use any input.

if (/^exim_lock\s+(.*)$/)
  {
  $cmd = "./eximdir/exim_lock $1 >>test-stdout";
  $server_pid = open SERVERCMD, "|$cmd" ||
    tests_exit(-1, "Failed to run $cmd\n");

  # This gives the process time to get started; otherwise the next
  # process may not find it there when it expects it.

  select(undef, undef, undef, 0.1);
  return 3;
  }


# The "exinext" command runs exinext

if (/^exinext\s+(.*)/)
  {
  run_system("(./eximdir/exinext " .
    "-DEXIM_PATH=$parm_cwd/eximdir/exim " .
    "-C $parm_cwd/test-config $1;" .
    "echo exinext exit code = \$?)" .
    ">>test-stdout");
  return 1;
  }


# The "exigrep" command runs exigrep on the current mainlog

if (/^exigrep\s+(.*)/)
  {
  run_system("(./eximdir/exigrep " .
    "$1 $parm_cwd/spool/log/mainlog;" .
    "echo exigrep exit code = \$?)" .
    ">>test-stdout");
  return 1;
  }


# The "eximstats" command runs eximstats on the current mainlog

if (/^eximstats\s+(.*)/)
  {
  run_system("(./eximdir/eximstats " .
    "$1 $parm_cwd/spool/log/mainlog;" .
    "echo eximstats exit code = \$?)" .
    ">>test-stdout");
  return 1;
  }


# The "gnutls" command makes a copy of saved GnuTLS parameter data in the
# spool directory, to save Exim from re-creating it each time.

if (/^gnutls/)
  {
  my $gen_fn = "spool/gnutls-params-$gnutls_dh_bits_normal";
  run_system "sudo cp -p aux-fixed/gnutls-params $gen_fn;" .
         "sudo chown $parm_eximuser:$parm_eximgroup $gen_fn;" .
         "sudo chmod 0400 $gen_fn";
  return 1;
  }


# The "killdaemon" command should ultimately follow the starting of any Exim
# daemon with the -bd option. We kill with SIGINT rather than SIGTERM to stop
# it outputting "Terminated" to the terminal when not in the background.

if (/^killdaemon/)
  {
  my $return_extra = {};
  if (exists $aux_info->{exim_pid})
    {
    $pid = $aux_info->{exim_pid};
    $return_extra->{exim_pid} = undef;
    print ">> killdaemon: recovered pid $pid\n" if $debug;
    if ($pid)
      {
      run_system("sudo /bin/kill -INT $pid");
      wait;
      }
    } else {
    $pid = `cat $parm_cwd/spool/exim-daemon.*`;
    if ($pid)
      {
      run_system("sudo /bin/kill -INT $pid");
      close DAEMONCMD;                                   # Waits for process
      }
    }
    run_system("sudo /bin/rm -f spool/exim-daemon.*");
  return (1, $return_extra);
  }


# The "millisleep" command is like "sleep" except that its argument is in
# milliseconds, thus allowing for a subsecond sleep, which is, in fact, all it
# is used for.

elsif (/^millisleep\s+(.*)$/)
  {
  select(undef, undef, undef, $1/1000);
  return 0;
  }


# The "munge" command selects one of a hardwired set of test-result modifications
# to be made before result compares are run agains the golden set.  This lets
# us account for test-system dependent things which only affect a few, but known,
# test-cases.
# Currently only the last munge takes effect.

if (/^munge\s+(.*)$/)
  {
  return (0, { munge => $1 });
  }


# The "sleep" command does just that. For sleeps longer than 1 second we
# tell the user what's going on.

if (/^sleep\s+(.*)$/)
  {
  if ($1 == 1)
    {
    sleep(1);
    }
  else
    {
    printf("  Test %d sleep $1 ", $$subtestref);
    for (1..$1)
      {
      print ".";
      sleep(1);
      }
    printf("\r  Test %d                            $cr", $$subtestref);
    }
  return 0;
  }


# Various Unix management commands are recognized

if (/^(ln|ls|du|mkdir|mkfifo|touch|cp|cat)\s/ ||
    /^sudo (rmdir|rm|chown|chmod)\s/)
  {
  run_system("$_ >>test-stdout 2>>test-stderr");
  return 1;
  }



###################
###################

# The next group of commands are also freestanding, but they are all followed
# by data lines.


# The "server" command starts up a script-driven server that runs in parallel
# with the following exim command. Therefore, we want to run a subprocess and
# not yet wait for it to complete. The waiting happens after the next exim
# command, triggered by $server_pid being non-zero. The server sends its output
# to a different file. The variable $server_opts, if not empty, contains
# options to disable IPv4 or IPv6 if necessary.

if (/^server\s+(.*)$/)
  {
  $cmd = "./bin/server $server_opts $1 >>test-stdout-server";
  print ">> $cmd\n" if ($debug);
  $server_pid = open SERVERCMD, "|$cmd" || tests_exit(-1, "Failed to run $cmd");
  SERVERCMD->autoflush(1);
  print ">> Server pid is $server_pid\n" if $debug;
  while (<SCRIPT>)
    {
    $lineno++;
    last if /^\*{4}\s*$/;
    print SERVERCMD;
    }
  print SERVERCMD "++++\n"; # Send end to server; can't send EOF yet
                            # because close() waits for the process.

  # This gives the server time to get started; otherwise the next
  # process may not find it there when it expects it.

  select(undef, undef, undef, 0.5);
  return 3;
  }


# The "write" command is a way of creating files of specific sizes for
# buffering tests, or containing specific data lines from within the script
# (rather than hold lots of little files). The "catwrite" command does the
# same, but it also copies the lines to test-stdout.

if (/^(cat)?write\s+(\S+)(?:\s+(.*))?\s*$/)
  {
  my($cat) = defined $1;
  @sizes = ();
  @sizes = split /\s+/, $3 if defined $3;
  open FILE, ">$2" || tests_exit(-1, "Failed to open \"$2\": $!");

  if ($cat)
    {
    open CAT, ">>test-stdout" ||
      tests_exit(-1, "Failed to open test-stdout: $!");
    print CAT "==========\n";
    }

  if (scalar @sizes > 0)
    {
    # Pre-data

    while (<SCRIPT>)
      {
      $lineno++;
      last if /^\+{4}\s*$/;
      print FILE;
      print CAT if $cat;
      }

    # Sized data

    while (scalar @sizes > 0)
      {
      ($count,$len,$leadin) = (shift @sizes) =~ /(\d+)x(\d+)(?:=(.*))?/;
      $leadin = "" if !defined $leadin;
      $leadin =~ s/_/ /g;
      $len -= length($leadin) + 1;
      while ($count-- > 0)
        {
        print FILE $leadin, "a" x $len, "\n";
        print CAT $leadin, "a" x $len, "\n" if $cat;
        }
      }
    }

  # Post data, or only data if no sized data

  while (<SCRIPT>)
    {
    $lineno++;
    last if /^\*{4}\s*$/;
    print FILE;
    print CAT if $cat;
    }
  close FILE;

  if ($cat)
    {
    print CAT "==========\n";
    close CAT;
    }

  return 0;
  }


###################
###################

# From this point on, script commands are implemented by setting up a shell
# command in the variable $cmd. Shared code to run this command and handle its
# input and output follows.

# The "client", "client-gnutls", and "client-ssl" commands run a script-driven
# program that plays the part of an email client. We also have the availability
# of running Perl for doing one-off special things. Note that all these
# commands expect stdin data to be supplied.

if (/^client/ || /^(sudo\s+)?perl\b/)
  {
  s"client"./bin/client";
  $cmd = "$_ >>test-stdout 2>>test-stderr";
  }

# For the "exim" command, replace the text "exim" with the path for the test
# binary, plus -D options to pass over various parameters, and a -C option for
# the testing configuration file. When running in the test harness, Exim does
# not drop privilege when -C and -D options are present. To run the exim
# command as root, we use sudo.

elsif (/^([A-Z_]+=\S+\s+)?(\d+)?\s*(sudo\s+)?exim(_\S+)?\s+(.*)$/)
  {
  $args = $5;
  my($envset) = (defined $1)? $1      : "";
  my($sudo)   = (defined $3)? "sudo " : "";
  my($special)= (defined $4)? $4      : "";
  $wait_time  = (defined $2)? $2      : 0;

  # Return 2 rather than 1 afterwards

  $yield = 2;

  # Update the test number

  $$subtestref = $$subtestref + 1;
  printf("  Test %d       $cr", $$subtestref);

  # Copy the configuration file, making the usual substitutions.

  open (IN, "$parm_cwd/confs/$testno") ||
    tests_exit(-1, "Couldn't open $parm_cwd/confs/$testno: $!\n");
  open (OUT, ">test-config") ||
    tests_exit(-1, "Couldn't open test-config: $!\n");
  while (<IN>)
    {
    do_substitute($testno);
    print OUT;
    }
  close(IN);
  close(OUT);

  # The string $msg1 in args substitutes the message id of the first
  # message on the queue, and so on. */

  if ($args =~ /\$msg/)
    {
    my($listcmd) = "$parm_cwd/eximdir/exim -bp " .
                   "-DEXIM_PATH=$parm_cwd/eximdir/exim " .
                   "-C $parm_cwd/test-config |";
    print ">> Getting queue list from:\n>>    $listcmd\n" if ($debug);
    open (QLIST, $listcmd) || tests_exit(-1, "Couldn't run \"exim -bp\": $!\n");
    my(@msglist) = ();
    while (<QLIST>) { push (@msglist, $1) if /^\s*\d+[smhdw]\s+\S+\s+(\S+)/; }
    close(QLIST);

    # Done backwards just in case there are more than 9

    my($i);
    for ($i = @msglist; $i > 0; $i--) { $args =~ s/\$msg$i/$msglist[$i-1]/g; }
    if ( $args =~ /\$msg\d/ )
      {
      tests_exit(-1, "Not enough messages in spool, for test $testno line $lineno\n")
        unless $force_continue;
      }
    }

  # If -d is specified in $optargs, remove it from $args; i.e. let
  # the command line for runtest override. Then run Exim.

  $args =~ s/(?:^|\s)-d\S*// if $optargs =~ /(?:^|\s)-d/;

  $cmd = "$envset$sudo$parm_cwd/eximdir/exim$special$optargs " .
         "-DEXIM_PATH=$parm_cwd/eximdir/exim$special " .
         "-C $parm_cwd/test-config $args " .
         ">>test-stdout 2>>test-stderr";

  # If the command is starting an Exim daemon, we run it in the same
  # way as the "server" command above, that is, we don't want to wait
  # for the process to finish. That happens when "killdaemon" is obeyed later
  # in the script. We also send the stderr output to test-stderr-server. The
  # daemon has its log files put in a different place too (by configuring with
  # log_file_path). This requires the  directory to be set up in advance.
  #
  # There are also times when we want to run a non-daemon version of Exim
  # (e.g. a queue runner) with the server configuration. In this case,
  # we also define -DNOTDAEMON.

  if ($cmd =~ /\s-DSERVER=server\s/ && $cmd !~ /\s-DNOTDAEMON\s/)
    {
    if ($debug) { printf ">> daemon: $cmd\n"; }
    run_system("sudo mkdir spool/log 2>/dev/null");
    run_system("sudo chown $parm_eximuser:$parm_eximgroup spool/log");

    # Before running the command, convert the -bd option into -bdf so that an
    # Exim daemon doesn't double fork. This means that when we wait close
    # DAEMONCMD, it waits for the correct process. Also, ensure that the pid
    # file is written to the spool directory, in case the Exim binary was
    # built with PID_FILE_PATH pointing somewhere else.

    $cmd =~ s!\s-bd\s! -bdf -oP $parm_cwd/spool/exim-daemon.pid !;
    print ">> |${cmd}-server\n" if ($debug);
    open DAEMONCMD, "|${cmd}-server" || tests_exit(-1, "Failed to run $cmd");
    DAEMONCMD->autoflush(1);
    while (<SCRIPT>) { $lineno++; last if /^\*{4}\s*$/; }   # Ignore any input
    select(undef, undef, undef, 0.3);             # Let the daemon get going
    return 3;                                     # Don't wait
    }
  elsif ($cmd =~ /\s-DSERVER=wait:(\d+)\s/)
    {
    my $listen_port = $1;
    my $waitmode_sock = new FileHandle;
    if ($debug) { printf ">> wait-mode daemon: $cmd\n"; }
    run_system("sudo mkdir spool/log 2>/dev/null");
    run_system("sudo chown $parm_eximuser:$parm_eximgroup spool/log");

    my ($s_ip,$s_port) = ('127.0.0.1', $listen_port);
    my $sin = sockaddr_in($s_port, inet_aton($s_ip))
        or die "** Failed packing $s_ip:$s_port\n";
    socket($waitmode_sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
        or die "** Unable to open socket $s_ip:$s_port: $!\n";
    setsockopt($waitmode_sock, SOL_SOCKET, SO_REUSEADDR, 1)
        or die "** Unable to setsockopt(SO_REUSEADDR): $!\n";
    bind($waitmode_sock, $sin)
        or die "** Unable to bind socket ($s_port): $!\n";
    listen($waitmode_sock, 5);
    my $pid = fork();
    if (not defined $pid) { die "** fork failed: $!\n" }
    if (not $pid) {
      close(STDIN);
      open(STDIN, "<&", $waitmode_sock) or die "** dup sock to stdin failed: $!\n";
      close($waitmode_sock);
      print "[$$]>> ${cmd}-server\n" if ($debug);
      exec "exec ${cmd}-server";
      exit(1);
    }
    while (<SCRIPT>) { $lineno++; last if /^\*{4}\s*$/; }   # Ignore any input
    select(undef, undef, undef, 0.3);             # Let the daemon get going
    return (3, { exim_pid => $pid });             # Don't wait
    }
  }


# Unknown command

else { tests_exit(-1, "Command unrecognized in line $lineno: $_"); }


# Run the command, with stdin connected to a pipe, and write the stdin data
# to it, with appropriate substitutions. If a line ends with \NONL\, chop off
# the terminating newline (and the \NONL\). If the command contains
# -DSERVER=server add "-server" to the command, where it will adjoin the name
# for the stderr file. See comment above about the use of -DSERVER.

$stderrsuffix = ($cmd =~ /\s-DSERVER=server\s/)? "-server" : "";
print ">> |${cmd}${stderrsuffix}\n" if ($debug);
open CMD, "|${cmd}${stderrsuffix}" || tests_exit(1, "Failed to run $cmd");

CMD->autoflush(1);
while (<SCRIPT>)
  {
  $lineno++;
  last if /^\*{4}\s*$/;
  do_substitute($testno);
  if (/^(.*)\\NONL\\\s*$/) { print CMD $1; } else { print CMD; }
  }

# For timeout tests, wait before closing the pipe; we expect a
# SIGPIPE error in this case.

if ($wait_time > 0)
  {
  printf("  Test %d sleep $wait_time ", $$subtestref);
  while ($wait_time-- > 0)
    {
    print ".";
    sleep(1);
    }
  printf("\r  Test %d                                       $cr", $$subtestref);
  }

$sigpipehappened = 0;
close CMD;                # Waits for command to finish
return $yield;            # Ran command and waited
}




###############################################################################
###############################################################################

# Here beginneth the Main Program ...

###############################################################################
###############################################################################


autoflush STDOUT 1;
print "Exim tester $testversion\n";


##################################################
#      Some tests check created file modes       #
##################################################

umask 022;


##################################################
#       Check for the "less" command             #
##################################################

$more = "more" if system("which less >/dev/null 2>&1") != 0;



##################################################
#        Check for sudo access to root           #
##################################################

print "You need to have sudo access to root to run these tests. Checking ...\n";
if (system("sudo date >/dev/null") != 0)
  {
  die "** Test for sudo failed: testing abandoned.\n";
  }
else
  {
  print "Test for sudo OK\n";
  }



##################################################
#      See if an Exim binary has been given      #
##################################################

# If the first character of the first argument is '/', the argument is taken
# as the path to the binary.

$parm_exim = (@ARGV > 0 && $ARGV[0] =~ m?^/?)? shift @ARGV : "";
print "Exim binary is $parm_exim\n" if $parm_exim ne "";



##################################################
# Sort out options and which tests are to be run #
##################################################

# There are a few possible options for the test script itself; after these, any
# options are passed on to Exim calls within the tests. Typically, this is used
# to turn on Exim debugging while setting up a test.

while (@ARGV > 0 && $ARGV[0] =~ /^-/)
  {
  my($arg) = shift @ARGV;
  if ($optargs eq "")
    {
    if ($arg eq "-DEBUG")  { $debug = 1; $cr = "\n"; next; }
    if ($arg eq "-DIFF")   { $cf = "diff -u"; next; }
    if ($arg eq "-CONTINUE"){$force_continue = 1;
                             $more = "cat";
                             next; }
    if ($arg eq "-UPDATE") { $force_update = 1; next; }
    if ($arg eq "-NOIPV4") { $have_ipv4 = 0; next; }
    if ($arg eq "-NOIPV6") { $have_ipv6 = 0; next; }
    if ($arg eq "-KEEP")   { $save_output = 1; next; }
    }
  $optargs .= " $arg";
  }

# Any subsequent arguments are a range of test numbers.

if (@ARGV > 0)
  {
  $test_end = $test_start = $ARGV[0];
  $test_end = $ARGV[1] if (@ARGV > 1);
  $test_end = ($test_start >= 9000)? $test_special_top : $test_top
    if $test_end eq "+";
  die "** Test numbers out of order\n" if ($test_end < $test_start);
  }


##################################################
#      Make the command's directory current      #
##################################################

# After doing so, we find its absolute path name.

$cwd = $0;
$cwd = '.' if ($cwd !~ s|/[^/]+$||);
chdir($cwd) || die "** Failed to chdir to \"$cwd\": $!\n";
$parm_cwd = Cwd::getcwd();


##################################################
#     Search for an Exim binary to test          #
##################################################

# If an Exim binary hasn't been provided, try to find one. We can handle the
# case where exim-testsuite is installed alongside Exim source directories. For
# PH's private convenience, if there's a directory just called "exim4", that
# takes precedence; otherwise exim-snapshot takes precedence over any numbered
# releases.

if ($parm_exim eq "")
  {
  my($use_srcdir) = "";

  opendir DIR, ".." || die "** Failed to opendir \"..\": $!\n";
  while ($f = readdir(DIR))
    {
    my($srcdir);

    # Try this directory if it is "exim4" or if it is exim-snapshot or exim-n.m
    # possibly followed by -RCx where n.m is greater than any previously tried
    # directory. Thus, we should choose the highest version of Exim that has
    # been compiled.

    if ($f eq "exim4" || $f eq "exim-snapshot")
      { $srcdir = $f; }
    else
      { $srcdir = $f
        if ($f =~ /^exim-\d+\.\d+(-RC\d+)?$/ && $f gt $use_srcdir); }

    # Look for a build directory with a binary in it. If we find a binary,
    # accept this source directory.

    if ($srcdir)
      {
      opendir SRCDIR, "../$srcdir" ||
        die "** Failed to opendir \"$cwd/../$srcdir\": $!\n";
      while ($f = readdir(SRCDIR))
        {
        if ($f =~ /^build-/ && -e "../$srcdir/$f/exim")
          {
          $use_srcdir = $srcdir;
          $parm_exim = "$cwd/../$srcdir/$f/exim";
          $parm_exim =~ s'/[^/]+/\.\./'/';
          last;
          }
        }
      closedir(SRCDIR);
      }

    # If we have found "exim4" or "exim-snapshot", that takes precedence.
    # Otherwise, continue to see if there's a later version.

    last if $use_srcdir eq "exim4" || $use_srcdir eq "exim-snapshot";
    }
  closedir(DIR);
  print "Exim binary found in $parm_exim\n" if $parm_exim ne "";
  }

# If $parm_exim is still empty, ask the caller

if ($parm_exim eq "")
  {
  print "** Did not find an Exim binary to test\n";
  for ($i = 0; $i < 5; $i++)
    {
    my($trybin);
    print "** Enter pathname for Exim binary: ";
    chomp($trybin = <STDIN>);
    if (-e $trybin)
      {
      $parm_exim = $trybin;
      last;
      }
    else
      {
      print "** $trybin does not exist\n";
      }
    }
  die "** Too many tries\n" if $parm_exim eq "";
  }



##################################################
#          Find what is in the binary            #
##################################################

# deal with TRUSTED_CONFIG_LIST restrictions
unlink("$parm_cwd/test-config") if -e "$parm_cwd/test-config";
symlink("$parm_cwd/confs/0000", "$parm_cwd/test-config")
  or die "Unable to link initial config into place: $!\n";

print("Probing with config file: $parm_cwd/test-config\n");
open(EXIMINFO, "$parm_exim -d -C $parm_cwd/test-config -DDIR=$parm_cwd " .
               "-bP exim_user exim_group|") ||
  die "** Cannot run $parm_exim: $!\n";
while(<EXIMINFO>)
  {
  $parm_eximuser = $1 if /^exim_user = (.*)$/;
  $parm_eximgroup = $1 if /^exim_group = (.*)$/;
  }
close(EXIMINFO);

if (defined $parm_eximuser)
  {
  if ($parm_eximuser =~ /^\d+$/) { $parm_exim_uid = $parm_eximuser; }
    else { $parm_exim_uid = getpwnam($parm_eximuser); }
  }
else
  {
  print "Unable to extract exim_user from binary.\n";
  print "Check if Exim refused to run; if so, consider:\n";
  print "  TRUSTED_CONFIG_LIST ALT_CONFIG_PREFIX WHITELIST_D_MACROS\n";
  die "Failing to get information from binary.\n";
  }

if (defined $parm_eximgroup)
  {
  if ($parm_eximgroup =~ /^\d+$/) { $parm_exim_gid = $parm_eximgroup; }
    else { $parm_exim_gid = getgrnam($parm_eximgroup); }
  }

open(EXIMINFO, "$parm_exim -bV -C $parm_cwd/test-config -DDIR=$parm_cwd |") ||
  die "** Cannot run $parm_exim: $!\n";

print "-" x 78, "\n";

while (<EXIMINFO>)
  {
  my(@temp);

  if (/^Exim version/) { print; }

  elsif (/^Size of off_t: (\d+)/)
    {
    print;
    $have_largefiles = 1 if $1 > 4;
    die "** Size of off_t > 32 which seems improbable, not running tests\n"
        if ($1 > 32);
    }

  elsif (/^Support for: (.*)/)
    {
    print;
    @temp = split /(\s+)/, $1;
    push(@temp, ' ');
    %parm_support = @temp;
    }

  elsif (/^Lookups \(built-in\): (.*)/)
    {
    print;
    @temp = split /(\s+)/, $1;
    push(@temp, ' ');
    %parm_lookups = @temp;
    }

  elsif (/^Authenticators: (.*)/)
    {
    print;
    @temp = split /(\s+)/, $1;
    push(@temp, ' ');
    %parm_authenticators = @temp;
    }

  elsif (/^Routers: (.*)/)
    {
    print;
    @temp = split /(\s+)/, $1;
    push(@temp, ' ');
    %parm_routers = @temp;
    }

  # Some transports have options, e.g. appendfile/maildir. For those, ensure
  # that the basic transport name is set, and then the name with each of the
  # options.

  elsif (/^Transports: (.*)/)
    {
    print;
    @temp = split /(\s+)/, $1;
    my($i,$k);
    push(@temp, ' ');
    %parm_transports = @temp;
    foreach $k (keys %parm_transports)
      {
      if ($k =~ "/")
        {
        @temp = split /\//, $k;
        $parm_transports{"$temp[0]"} = " ";
        for ($i = 1; $i < @temp; $i++)
          { $parm_transports{"$temp[0]/$temp[$i]"} = " "; }
        }
      }
    }
  }
close(EXIMINFO);
print "-" x 78, "\n";

unlink("$parm_cwd/test-config");

##################################################
#    Check for SpamAssassin and ClamAV           #
##################################################

# These are crude tests. If they aren't good enough, we'll have to improve
# them, for example by actually passing a message through spamc or clamscan.

if (defined $parm_support{'Content_Scanning'})
  {
  my $sock = new FileHandle;

  if (system("spamc -h 2>/dev/null >/dev/null") == 0)
    {
    print "The spamc command works:\n";

    # This test for an active SpamAssassin is courtesy of John Jetmore.
    # The tests are hard coded to localhost:783, so no point in making
    # this test flexible like the clamav test until the test scripts are
    # changed.  spamd doesn't have the nice PING/PONG protoccol that
    # clamd does, but it does respond to errors in an informative manner,
    # so use that.

    my($sint,$sport) = ('127.0.0.1',783);
    eval
      {
      my $sin = sockaddr_in($sport, inet_aton($sint))
          or die "** Failed packing $sint:$sport\n";
      socket($sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
          or die "** Unable to open socket $sint:$sport\n";

      local $SIG{ALRM} =
          sub { die "** Timeout while connecting to socket $sint:$sport\n"; };
      alarm(5);
      connect($sock, $sin)
          or die "** Unable to connect to socket $sint:$sport\n";
      alarm(0);

      select((select($sock), $| = 1)[0]);
      print $sock "bad command\r\n";

      $SIG{ALRM} =
          sub { die "** Timeout while reading from socket $sint:$sport\n"; };
      alarm(10);
      my $res = <$sock>;
      alarm(0);

      $res =~ m|^SPAMD/|
          or die "** Did not get SPAMD from socket $sint:$sport. "
                ."It said: $res\n";
      };
    alarm(0);
    if($@)
      {
      print "  $@";
      print "  Assume SpamAssassin (spamd) is not running\n";
      }
    else
      {
      $parm_running{'SpamAssassin'} = ' ';
      print "  SpamAssassin (spamd) seems to be running\n";
      }
    }
  else
    {
    print "The spamc command failed: assume SpamAssassin (spamd) is not running\n";
    }

  # For ClamAV, we need to find the clamd socket for use in the Exim
  # configuration. Search for the clamd configuration file.

  if (system("clamscan -h 2>/dev/null >/dev/null") == 0)
    {
    my($f, $clamconf, $test_prefix);

    print "The clamscan command works";

    $test_prefix = $ENV{EXIM_TEST_PREFIX};
    $test_prefix = "" if !defined $test_prefix;

    foreach $f ("$test_prefix/etc/clamd.conf",
                "$test_prefix/usr/local/etc/clamd.conf",
                "$test_prefix/etc/clamav/clamd.conf", "")
      {
      if (-e $f)
        {
        $clamconf = $f;
        last;
        }
      }

    # Read the ClamAV configuration file and find the socket interface.

    if ($clamconf ne "")
      {
      my $socket_domain;
      open(IN, "$clamconf") || die "\n** Unable to open $clamconf: $!\n";
      while (<IN>)
        {
        if (/^LocalSocket\s+(.*)/)
          {
          $parm_clamsocket = $1;
          $socket_domain = AF_UNIX;
          last;
          }
        if (/^TCPSocket\s+(\d+)/)
          {
          if (defined $parm_clamsocket)
            {
            $parm_clamsocket .= " $1";
            $socket_domain = AF_INET;
            last;
            }
          else
            {
            $parm_clamsocket = " $1";
            }
          }
        elsif (/^TCPAddr\s+(\S+)/)
          {
          if (defined $parm_clamsocket)
            {
            $parm_clamsocket = $1 . $parm_clamsocket;
            $socket_domain = AF_INET;
            last;
            }
          else
            {
            $parm_clamsocket = $1;
            }
          }
        }
      close(IN);

      if (defined $socket_domain)
        {
        print ":\n  The clamd socket is $parm_clamsocket\n";
        # This test for an active ClamAV is courtesy of Daniel Tiefnig.
        eval
          {
          my $socket;
          if ($socket_domain == AF_UNIX)
            {
            $socket = sockaddr_un($parm_clamsocket) or die "** Failed packing '$parm_clamsocket'\n";
            }
          elsif ($socket_domain == AF_INET)
            {
            my ($ca_host, $ca_port) = split(/\s+/,$parm_clamsocket);
            my $ca_hostent = gethostbyname($ca_host) or die "** Failed to get raw address for host '$ca_host'\n";
            $socket = sockaddr_in($ca_port, $ca_hostent) or die "** Failed packing '$parm_clamsocket'\n";
            }
          else
            {
            die "** Unknown socket domain '$socket_domain' (should not happen)\n";
            }
          socket($sock, $socket_domain, SOCK_STREAM, 0) or die "** Unable to open socket '$parm_clamsocket'\n";
          local $SIG{ALRM} = sub { die "** Timeout while connecting to socket '$parm_clamsocket'\n"; };
          alarm(5);
          connect($sock, $socket) or die "** Unable to connect to socket '$parm_clamsocket'\n";
          alarm(0);

          my $ofh = select $sock; $| = 1; select $ofh;
          print $sock "PING\n";

          $SIG{ALRM} = sub { die "** Timeout while reading from socket '$parm_clamsocket'\n"; };
          alarm(10);
          my $res = <$sock>;
          alarm(0);

          $res =~ /PONG/ or die "** Did not get PONG from socket '$parm_clamsocket'. It said: $res\n";
          };
        alarm(0);

        if($@)
          {
          print "  $@";
          print "  Assume ClamAV is not running\n";
          }
        else
          {
          $parm_running{'ClamAV'} = ' ';
          print "  ClamAV seems to be running\n";
          }
        }
      else
        {
        print ", but the socket for clamd could not be determined\n";
        print "Assume ClamAV is not running\n";
        }
      }

    else
      {
      print ", but I can't find a configuration for clamd\n";
      print "Assume ClamAV is not running\n";
      }
    }
  }


##################################################
#         Test for the basic requirements        #
##################################################

# This test suite assumes that Exim has been built with at least the "usual"
# set of routers, transports, and lookups. Ensure that this is so.

$missing = "";

$missing .= "     Lookup: lsearch\n" if (!defined $parm_lookups{'lsearch'});

$missing .= "     Router: accept\n" if (!defined $parm_routers{'accept'});
$missing .= "     Router: dnslookup\n" if (!defined $parm_routers{'dnslookup'});
$missing .= "     Router: manualroute\n" if (!defined $parm_routers{'manualroute'});
$missing .= "     Router: redirect\n" if (!defined $parm_routers{'redirect'});

$missing .= "     Transport: appendfile\n" if (!defined $parm_transports{'appendfile'});
$missing .= "     Transport: autoreply\n" if (!defined $parm_transports{'autoreply'});
$missing .= "     Transport: pipe\n" if (!defined $parm_transports{'pipe'});
$missing .= "     Transport: smtp\n" if (!defined $parm_transports{'smtp'});

if ($missing ne "")
  {
  print "\n";
  print "** Many features can be included or excluded from Exim binaries.\n";
  print "** This test suite requires that Exim is built to contain a certain\n";
  print "** set of basic facilities. It seems that some of these are missing\n";
  print "** from the binary that is under test, so the test cannot proceed.\n";
  print "** The missing facilities are:\n";
  print "$missing";
  die "** Test script abandoned\n";
  }


##################################################
#      Check for the auxiliary programs          #
##################################################

# These are always required:

for $prog ("cf", "checkaccess", "client", "client-ssl", "client-gnutls",
           "fakens", "iefbr14", "server")
  {
  next if ($prog eq "client-ssl" && !defined $parm_support{'OpenSSL'});
  next if ($prog eq "client-gnutls" && !defined $parm_support{'GnuTLS'});
  if (!-e "bin/$prog")
    {
    print "\n";
    print "** bin/$prog does not exist. Have you run ./configure and make?\n";
    die "** Test script abandoned\n";
    }
  }

# If the "loaded" binary is missing, we cut out tests for ${dlfunc. It isn't
# compiled on systems where we don't know how to. However, if Exim does not
# have that functionality compiled, we needn't bother.

$dlfunc_deleted = 0;
if (defined $parm_support{'Expand_dlfunc'} && !-e "bin/loaded")
  {
  delete $parm_support{'Expand_dlfunc'};
  $dlfunc_deleted = 1;
  }


##################################################
#          Find environmental details            #
##################################################

# Find the caller of this program.

($parm_caller,$pwpw,$parm_caller_uid,$parm_caller_gid,$pwquota,$pwcomm,
 $parm_caller_gecos, $parm_caller_home) = getpwuid($>);

$pwpw = $pwpw;       # Kill Perl warnings
$pwquota = $pwquota;
$pwcomm = $pwcomm;

$parm_caller_group = getgrgid($parm_caller_gid);

print "Program caller is $parm_caller ($parm_caller_uid), whose group is $parm_caller_group ($parm_caller_gid)\n";
print "Home directory is $parm_caller_home\n";

unless (defined $parm_eximgroup)
  {
  print "Unable to derive \$parm_eximgroup.\n";
  die "** ABANDONING.\n";
  }

print "You need to be in the Exim group to run these tests. Checking ...";

if (`groups` =~ /\b\Q$parm_eximgroup\E\b/)
  {
  print " OK\n";
  }
else
  {
  print "\nOh dear, you are not in the Exim group.\n";
  die "** Testing abandoned.\n";
  }

# Find this host's IP addresses - there may be many, of course, but we keep
# one of each type (IPv4 and IPv6).

$parm_ipv4 = "";
$parm_ipv6 = "";

$local_ipv4 = "";
$local_ipv6 = "";

open(IFCONFIG, "ifconfig -a|") || die "** Cannot run \"ifconfig\": $!\n";
while (($parm_ipv4 eq "" || $parm_ipv6 eq "") && ($_ = <IFCONFIG>))
  {
  my($ip);
  if ($parm_ipv4 eq "" &&
      $_ =~ /^\s*inet(?:\saddr)?:?\s?(\d+\.\d+\.\d+\.\d+)\s/i)
    {
    $ip = $1;
    next if ($ip =~ /^127\./);
    $parm_ipv4 = $ip;
    }

  if ($parm_ipv6 eq "" &&
      $_ =~ /^\s*inet6(?:\saddr)?:?\s?([abcdef\d:]+)/i)
    {
    $ip = $1;
    next if ($ip eq "::1" || $ip =~ /^fe80/i);
    $parm_ipv6 = $ip;
    }
  }
close(IFCONFIG);

# Use private IP addresses if there are no public ones.

$parm_ipv4 = $local_ipv4 if ($parm_ipv4 eq "");
$parm_ipv6 = $local_ipv6 if ($parm_ipv6 eq "");

# If either type of IP address is missing, we need to set the value to
# something other than empty, because that wrecks the substitutions. The value
# is reflected, so use a meaningful string. Set appropriate options for the
# "server" command. In practice, however, many tests assume 127.0.0.1 is
# available, so things will go wrong if there is no IPv4 address. The lack
# of IPV4 or IPv6 can be simulated by command options, which force $have_ipv4
# and $have_ipv6 false.

if ($parm_ipv4 eq "")
  {
  $have_ipv4 = 0;
  $parm_ipv4 = "<no IPv4 address found>";
  $server_opts .= " -noipv4";
  }
elsif ($have_ipv4 == 0)
  {
  $parm_ipv4 = "<IPv4 testing disabled>";
  $server_opts .= " -noipv4";
  }
else
  {
  $parm_running{"IPv4"} = " ";
  }

if ($parm_ipv6 eq "")
  {
  $have_ipv6 = 0;
  $parm_ipv6 = "<no IPv6 address found>";
  $server_opts .= " -noipv6";
  delete($parm_support{"IPv6"});
  }
elsif ($have_ipv6 == 0)
  {
  $parm_ipv6 = "<IPv6 testing disabled>";
  $server_opts .= " -noipv6";
  delete($parm_support{"IPv6"});
  }
elsif (!defined $parm_support{'IPv6'})
  {
  $have_ipv6 = 0;
  $parm_ipv6 = "<no IPv6 support in Exim binary>";
  $server_opts .= " -noipv6";
  }
else
  {
  $parm_running{"IPv6"} = " ";
  }

print "IPv4 address is $parm_ipv4\n";
print "IPv6 address is $parm_ipv6\n";

# For munging test output, we need the reversed IP addresses.

$parm_ipv4r = ($parm_ipv4 !~ /^\d/)? "" :
  join(".", reverse(split /\./, $parm_ipv4));

$parm_ipv6r = $parm_ipv6;             # Appropriate if not in use
if ($parm_ipv6 =~ /^[\da-f]/)
  {
  my(@comps) = split /:/, $parm_ipv6;
  my(@nibbles);
  foreach $comp (@comps)
    {
    push @nibbles, sprintf("%lx", hex($comp) >> 8);
    push @nibbles, sprintf("%lx", hex($comp) & 0xff);
    }
  $parm_ipv6r = join(".", reverse(@nibbles));
  }

# Find the host name, fully qualified.

chomp($temp = `hostname`);
$parm_hostname = (gethostbyname($temp))[0];
$parm_hostname = "no.host.name.found" if $parm_hostname eq "";
print "Hostname is $parm_hostname\n";

if ($parm_hostname !~ /\./)
  {
  print "\n*** Host name is not fully qualified: this may cause problems ***\n\n";
  }

if ($parm_hostname =~ /[[:upper:]]/)
  {
  print "\n*** Host name has upper case characters: this may cause problems ***\n\n";
  }



##################################################
#     Create a testing version of Exim           #
##################################################

# We want to be able to run Exim with a variety of configurations. Normally,
# the use of -C to change configuration causes Exim to give up its root
# privilege (unless the caller is exim or root). For these tests, we do not
# want this to happen. Also, we want Exim to know that it is running in its
# test harness.

# We achieve this by copying the binary and patching it as we go. The new
# binary knows it is a testing copy, and it allows -C and -D without loss of
# privilege. Clearly, this file is dangerous to have lying around on systems
# where there are general users with login accounts. To protect against this,
# we put the new binary in a special directory that is accessible only to the
# caller of this script, who is known to have sudo root privilege from the test
# that was done above. Furthermore, we ensure that the binary is deleted at the
# end of the test. First ensure the directory exists.

if (-d "eximdir")
  { unlink "eximdir/exim"; }     # Just in case
else
  {
  mkdir("eximdir", 0710) || die "** Unable to mkdir $parm_cwd/eximdir: $!\n";
  system("sudo chgrp $parm_eximgroup eximdir");
  }

# The construction of the patched binary must be done as root, so we use
# a separate script. As well as indicating that this is a test-harness binary,
# the version number is patched to "x.yz" so that its length is always the
# same. Otherwise, when it appears in Received: headers, it affects the length
# of the message, which breaks certain comparisons.

die "** Unable to make patched exim: $!\n"
  if (system("sudo ./patchexim $parm_exim") != 0);

# From this point on, exits from the program must go via the subroutine
# tests_exit(), so that suitable cleaning up can be done when required.
# Arrange to catch interrupting signals, to assist with this.

$SIG{'INT'} = \&inthandler;
$SIG{'PIPE'} = \&pipehandler;

# For some tests, we need another copy of the binary that is setuid exim rather
# than root.

system("sudo cp eximdir/exim eximdir/exim_exim;" .
       "sudo chown $parm_eximuser eximdir/exim_exim;" .
       "sudo chgrp $parm_eximgroup eximdir/exim_exim;" .
       "sudo chmod 06755 eximdir/exim_exim");


##################################################
#     Make copies of utilities we might need     #
##################################################

# Certain of the tests make use of some of Exim's utilities. We do not need
# to be root to copy these.

($parm_exim_dir) = $parm_exim =~ m?^(.*)/exim?;

$dbm_build_deleted = 0;
if (defined $parm_lookups{'dbm'} &&
    system("cp $parm_exim_dir/exim_dbmbuild eximdir") != 0)
  {
  delete $parm_lookups{'dbm'};
  $dbm_build_deleted = 1;
  }

if (system("cp $parm_exim_dir/exim_dumpdb eximdir") != 0)
  {
  tests_exit(-1, "Failed to make a copy of exim_dumpdb: $!");
  }

if (system("cp $parm_exim_dir/exim_lock eximdir") != 0)
  {
  tests_exit(-1, "Failed to make a copy of exim_lock: $!");
  }

if (system("cp $parm_exim_dir/exinext eximdir") != 0)
  {
  tests_exit(-1, "Failed to make a copy of exinext: $!");
  }

if (system("cp $parm_exim_dir/exigrep eximdir") != 0)
  {
  tests_exit(-1, "Failed to make a copy of exigrep: $!");
  }

if (system("cp $parm_exim_dir/eximstats eximdir") != 0)
  {
  tests_exit(-1, "Failed to make a copy of eximstats: $!");
  }


##################################################
#    Check that the Exim user can access stuff   #
##################################################

# We delay this test till here so that we can check access to the actual test
# binary. This will be needed when Exim re-exec's itself to do deliveries.

print "Exim user is $parm_eximuser ($parm_exim_uid)\n";
print "Exim group is $parm_eximgroup ($parm_exim_gid)\n";

if ($parm_caller_uid eq $parm_exim_uid) {
  tests_exit(-1, "Exim user ($parm_eximuser,$parm_exim_uid) cannot be "
                ."the same as caller ($parm_caller,$parm_caller_uid)");
}

print "The Exim user needs access to the test suite directory. Checking ...";

if (($rc = system("sudo bin/checkaccess $parm_cwd/eximdir/exim $parm_eximuser $parm_eximgroup")) != 0)
  {
  my($why) = "unknown failure $rc";
  $rc >>= 8;
  $why = "Couldn't find user \"$parm_eximuser\"" if $rc == 1;
  $why = "Couldn't find group \"$parm_eximgroup\"" if $rc == 2;
  $why = "Couldn't read auxiliary group list" if $rc == 3;
  $why = "Couldn't get rid of auxiliary groups" if $rc == 4;
  $why = "Couldn't set gid" if $rc == 5;
  $why = "Couldn't set uid" if $rc == 6;
  $why = "Couldn't open \"$parm_cwd/eximdir/exim\"" if $rc == 7;
  print "\n** $why\n";
  tests_exit(-1, "$parm_eximuser cannot access the test suite directory");
  }
else
  {
  print " OK\n";
  }


##################################################
#        Create a list of available tests        #
##################################################

# The scripts directory contains a number of subdirectories whose names are
# of the form 0000-xxxx, 1100-xxxx, 2000-xxxx, etc. Each set of tests apart
# from the first requires certain optional features to be included in the Exim
# binary. These requirements are contained in a file called "REQUIRES" within
# the directory. We scan all these tests, discarding those that cannot be run
# because the current binary does not support the right facilities, and also
# those that are outside the numerical range selected.

print "\nTest range is $test_start to $test_end\n";
print "Omitting \${dlfunc expansion tests (loadable module not present)\n"
  if $dlfunc_deleted;
print "Omitting dbm tests (unable to copy exim_dbmbuild)\n"
  if $dbm_build_deleted;

opendir(DIR, "scripts") || tests_exit(-1, "Failed to opendir(\"scripts\"): $!");
@test_dirs = sort readdir(DIR);
closedir(DIR);

# Remove . and .. and CVS from the list.

for ($i = 0; $i < @test_dirs; $i++)
  {
  my($d) = $test_dirs[$i];
  if ($d eq "." || $d eq ".." || $d eq "CVS")
    {
    splice @test_dirs, $i, 1;
    $i--;
    }
  }

# Scan for relevant tests

for ($i = 0; $i < @test_dirs; $i++)
  {
  my($testdir) = $test_dirs[$i];
  my($wantthis) = 1;

  print ">>Checking $testdir\n" if $debug;

  # Skip this directory if the first test is equal or greater than the first
  # test in the next directory.

  next if ($i < @test_dirs - 1) &&
          ($test_start >= substr($test_dirs[$i+1], 0, 4));

  # No need to carry on if the end test is less than the first test in this
  # subdirectory.

  last if $test_end < substr($testdir, 0, 4);

  # Check requirements, if any.

  if (open(REQUIRES, "scripts/$testdir/REQUIRES"))
    {
    while (<REQUIRES>)
      {
      next if /^\s*$/;
      s/\s+$//;
      if (/^support (.*)$/)
        {
        if (!defined $parm_support{$1}) { $wantthis = 0; last; }
        }
      elsif (/^running (.*)$/)
        {
        if (!defined $parm_running{$1}) { $wantthis = 0; last; }
        }
      elsif (/^lookup (.*)$/)
        {
        if (!defined $parm_lookups{$1}) { $wantthis = 0; last; }
        }
      elsif (/^authenticators? (.*)$/)
        {
        if (!defined $parm_authenticators{$1}) { $wantthis = 0; last; }
        }
      elsif (/^router (.*)$/)
        {
        if (!defined $parm_routers{$1}) { $wantthis = 0; last; }
        }
      elsif (/^transport (.*)$/)
        {
        if (!defined $parm_transports{$1}) { $wantthis = 0; last; }
        }
      else
        {
        tests_exit(-1, "Unknown line in \"scripts/$testdir/REQUIRES\": \"$_\"");
        }
      }
    close(REQUIRES);
    }
  else
    {
    tests_exit(-1, "Failed to open \"scripts/$testdir/REQUIRES\": $!")
      unless $!{ENOENT};
    }

  # Loop if we do not want the tests in this subdirectory.

  if (!$wantthis)
    {
    chomp;
    print "Omitting tests in $testdir (missing $_)\n";
    next;
    }

  # We want the tests from this subdirectory, provided they are in the
  # range that was selected.

  opendir(SUBDIR, "scripts/$testdir") ||
    tests_exit(-1, "Failed to opendir(\"scripts/$testdir\"): $!");
  @testlist = sort readdir(SUBDIR);
  close(SUBDIR);

  foreach $test (@testlist)
    {
    next if $test !~ /^\d{4}$/;
    next if $test < $test_start || $test > $test_end;
    push @test_list, "$testdir/$test";
    }
  }

print ">>Test List: @test_list\n", if $debug;


##################################################
#         Munge variable auxiliary data          #
##################################################

# Some of the auxiliary data files have to refer to the current testing
# directory and other parameter data. The generic versions of these files are
# stored in the aux-var-src directory. At this point, we copy each of them
# to the aux-var directory, making appropriate substitutions. There aren't very
# many of them, so it's easiest just to do this every time. Ensure the mode
# is standardized, as this path is used as a test for the ${stat: expansion.

# A similar job has to be done for the files in the dnszones-src directory, to
# make the fake DNS zones for testing. Most of the zone files are copied to
# files of the same name, but db.ipv4.V4NET and db.ipv6.V6NET use the testing
# networks that are defined by parameter.

foreach $basedir ("aux-var", "dnszones")
  {
  system("sudo rm -rf $parm_cwd/$basedir");
  mkdir("$parm_cwd/$basedir", 0777);
  chmod(0755, "$parm_cwd/$basedir");

  opendir(AUX, "$parm_cwd/$basedir-src") ||
    tests_exit(-1, "Failed to opendir $parm_cwd/$basedir-src: $!");
  my(@filelist) = readdir(AUX);
  close(AUX);

  foreach $file (@filelist)
    {
    my($outfile) = $file;
    next if $file =~ /^\./;

    if ($file eq "db.ip4.V4NET")
      {
      $outfile = "db.ip4.$parm_ipv4_test_net";
      }
    elsif ($file eq "db.ip6.V6NET")
      {
      my(@nibbles) = reverse(split /\s*/, $parm_ipv6_test_net);
      $" = '.';
      $outfile = "db.ip6.@nibbles";
      $" = ' ';
      }

    print ">>Copying $basedir-src/$file to $basedir/$outfile\n" if $debug;
    open(IN, "$parm_cwd/$basedir-src/$file") ||
      tests_exit(-1, "Failed to open $parm_cwd/$basedir-src/$file: $!");
    open(OUT, ">$parm_cwd/$basedir/$outfile") ||
      tests_exit(-1, "Failed to open $parm_cwd/$basedir/$outfile: $!");
    while (<IN>)
      {
      do_substitute(0);
      print OUT;
      }
    close(IN);
    close(OUT);
    }
  }

# Set a user's shell, distinguishable from /bin/sh

symlink("/bin/sh","aux-var/sh");
$ENV{'SHELL'} = $parm_shell = $parm_cwd . "/aux-var/sh";

##################################################
#     Create fake DNS zones for this host        #
##################################################

# There are fixed zone files for 127.0.0.1 and ::1, but we also want to be
# sure that there are forward and reverse registrations for this host, using
# its real IP addresses. Dynamically created zone files achieve this.

if ($have_ipv4 || $have_ipv6)
  {
  my($shortname,$domain) = $parm_hostname =~ /^([^.]+)(.*)/;
  open(OUT, ">$parm_cwd/dnszones/db$domain") ||
    tests_exit(-1, "Failed to open $parm_cwd/dnszones/db$domain: $!");
  print OUT "; This is a dynamically constructed fake zone file.\n" .
    "; The following line causes fakens to return PASS_ON\n" .
    "; for queries that it cannot answer\n\n" .
    "PASS ON NOT FOUND\n\n";
  print OUT "$shortname  A     $parm_ipv4\n" if $have_ipv4;
  print OUT "$shortname  AAAA  $parm_ipv6\n" if $have_ipv6;
  print OUT "\n; End\n";
  close(OUT);
  }

if ($have_ipv4 && $parm_ipv4 ne "127.0.0.1")
  {
  my(@components) = $parm_ipv4 =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)/;
  open(OUT, ">$parm_cwd/dnszones/db.ip4.$components[0]") ||
    tests_exit(-1,
      "Failed  to open $parm_cwd/dnszones/db.ip4.$components[0]: $!");
  print OUT "; This is a dynamically constructed fake zone file.\n" .
    "; The zone is $components[0].in-addr.arpa.\n\n" .
    "$components[3].$components[2].$components[1]  PTR  $parm_hostname.\n\n" .
    "; End\n";
  close(OUT);
  }

if ($have_ipv6 && $parm_ipv6 ne "::1")
  {
  my($exp_v6) = $parm_ipv6;
  $exp_v6 =~ s/[^:]//g;
  if ( $parm_ipv6 =~ /^([^:].+)::$/ ) {
    $exp_v6 = $1 . ':0' x (9-length($exp_v6));
  } elsif ( $parm_ipv6 =~ /^(.+)::(.+)$/ ) {
    $exp_v6 = $1 . ':0' x (8-length($exp_v6)) . ':' . $2;
  } elsif ( $parm_ipv6 =~ /^::(.+[^:])$/ ) {
    $exp_v6 = '0:' x (9-length($exp_v6)) . $1;
  } else {
    $exp_v6 = $parm_ipv6;
  }
  my(@components) = split /:/, $exp_v6;
  my(@nibbles) = reverse (split /\s*/, shift @components);
  my($sep) =  "";

  $" = ".";
  open(OUT, ">$parm_cwd/dnszones/db.ip6.@nibbles") ||
    tests_exit(-1,
      "Failed  to open $parm_cwd/dnszones/db.ip6.@nibbles: $!");
  print OUT "; This is a dynamically constructed fake zone file.\n" .
    "; The zone is @nibbles.ip6.arpa.\n\n";

  @components = reverse @components;
  foreach $c (@components)
    {
    $c = "0$c" until $c =~ /^..../;
    @nibbles = reverse(split /\s*/, $c);
    print OUT "$sep@nibbles";
    $sep = ".";
    }

  print OUT "  PTR  $parm_hostname.\n\n; End\n";
  close(OUT);
  $" = " ";
  }



##################################################
#    Create lists of mailboxes and message logs  #
##################################################

# We use these lists to check that a test has created the expected files. It
# should be faster than looking for the file each time. For mailboxes, we have
# to scan a complete subtree, in order to handle maildirs. For msglogs, there
# is just a flat list of files.

@oldmails = list_files_below("mail");
opendir(DIR, "msglog") || tests_exit(-1, "Failed to opendir msglog: $!");
@oldmsglogs = readdir(DIR);
closedir(DIR);



##################################################
#         Run the required tests                 #
##################################################

# Each test script contains a number of tests, separated by a line that
# contains ****. We open input from the terminal so that we can read responses
# to prompts.

open(T, "/dev/tty") || tests_exit(-1, "Failed to open /dev/tty: $!");

print "\nPress RETURN to run the tests: ";
$_ = $force_continue ? "c" : <T>;
print "\n";

$lasttestdir = "";

foreach $test (@test_list)
  {
  local($lineno) = 0;
  local($commandno) = 0;
  local($subtestno) = 0;
  local($testno) = substr($test, -4);
  local($sortlog) = 0;

  my($gnutls) = 0;
  my($docheck) = 1;
  my($thistestdir) = substr($test, 0, -5);

  if ($lasttestdir ne $thistestdir)
    {
    $gnutls = 0;
    if (-s "scripts/$thistestdir/REQUIRES")
      {
      my($indent) = "";
      print "\n>>> The following tests require: ";
      open(IN, "scripts/$thistestdir/REQUIRES") ||
        tests_exit(-1, "Failed to open scripts/$thistestdir/REQUIRES: $1");
      while (<IN>)
        {
        $gnutls = 1 if /^support GnuTLS/;
        print $indent, $_;
        $indent = ">>>                              ";
        }
      close(IN);
      }
    }
  $lasttestdir = $thistestdir;

  # Remove any debris in the spool directory and the test-mail directory
  # and also the files for collecting stdout and stderr. Then put back
  # the test-mail directory for appendfile deliveries.

  system "sudo /bin/rm -rf spool test-*";
  system "mkdir test-mail 2>/dev/null";

  # A privileged Exim will normally make its own spool directory, but some of
  # the tests run in unprivileged modes that don't always work if the spool
  # directory isn't already there. What is more, we want anybody to be able
  # to read it in order to find the daemon's pid.

  system "mkdir spool; " .
         "sudo chown $parm_eximuser:$parm_eximgroup spool; " .
         "sudo chmod 0755 spool";

  # Empty the cache that keeps track of things like message id mappings, and
  # set up the initial sequence strings.

  undef %cache;
  $next_msgid = "aX";
  $next_pid = 1234;
  $next_port = 1111;
  $message_skip = 0;
  $msglog_skip = 0;
  $stderr_skip = 0;
  $stdout_skip = 0;
  $rmfiltertest = 0;
  $is_ipv6test = 0;

  # Remove the associative arrays used to hold checked mail files and msglogs

  undef %expected_mails;
  undef %expected_msglogs;

  # Open the test's script
  open(SCRIPT, "scripts/$test") ||
    tests_exit(-1, "Failed to open \"scripts/$test\": $!");
  # Run through the script once to set variables which should be global
  while (<SCRIPT>)
    {
    if (/^no_message_check/) { $message_skip = 1; next; }
    if (/^no_msglog_check/)  { $msglog_skip = 1; next; }
    if (/^no_stderr_check/)  { $stderr_skip = 1; next; }
    if (/^no_stdout_check/)  { $stdout_skip = 1; next; }
    if (/^rmfiltertest/)     { $rmfiltertest = 1; next; }
    if (/^sortlog/)          { $sortlog = 1; next; }
    }
  # Reset to beginning of file for per test interpreting/processing
  seek(SCRIPT, 0, 0);

  # The first line in the script must be a comment that is used to identify
  # the set of tests as a whole.

  $_ = <SCRIPT>;
  $lineno++;
  tests_exit(-1, "Missing identifying comment at start of $test") if (!/^#/);
  printf("%s %s", (substr $test, 5), (substr $_, 2));

  # Loop for each of the subtests within the script. The variable $server_pid
  # is used to remember the pid of a "server" process, for which we do not
  # wait until we have waited for a subsequent command.

  local($server_pid) = 0;
  for ($commandno = 1; !eof SCRIPT; $commandno++)
    {
    # Skip further leading comments and blank lines, handle the flag setting
    # commands, and deal with tests for IP support.

    while (<SCRIPT>)
      {
      $lineno++;
      # Could remove these variable settings because they are already
      # set above, but doesn't hurt to leave them here.
      if (/^no_message_check/) { $message_skip = 1; next; }
      if (/^no_msglog_check/)  { $msglog_skip = 1; next; }
      if (/^no_stderr_check/)  { $stderr_skip = 1; next; }
      if (/^no_stdout_check/)  { $stdout_skip = 1; next; }
      if (/^rmfiltertest/)     { $rmfiltertest = 1; next; }
      if (/^sortlog/)          { $sortlog = 1; next; }

      if (/^need_largefiles/)
        {
        next if $have_largefiles;
        print ">>> Large file support is needed for test $testno, but is not available: skipping\n";
        $docheck = 0;      # don't check output
        undef $_;          # pretend EOF
        last;
        }

      if (/^need_ipv4/)
        {
        next if $have_ipv4;
        print ">>> IPv4 is needed for test $testno, but is not available: skipping\n";
        $docheck = 0;      # don't check output
        undef $_;          # pretend EOF
        last;
        }

      if (/^need_ipv6/)
        {
        if ($have_ipv6)
          {
          $is_ipv6test = 1;
          next;
          }
        print ">>> IPv6 is needed for test $testno, but is not available: skipping\n";
        $docheck = 0;      # don't check output
        undef $_;          # pretend EOF
        last;
        }

      if (/^need_move_frozen_messages/)
        {
        next if defined $parm_support{"move_frozen_messages"};
        print ">>> move frozen message support is needed for test $testno, " .
          "but is not\n>>> available: skipping\n";
        $docheck = 0;      # don't check output
        undef $_;          # pretend EOF
        last;
        }

      last unless /^(#|\s*$)/;
      }
    last if !defined $_;  # Hit EOF

    my($subtest_startline) = $lineno;

    # Now run the command. The function returns 0 if exim was run and waited
    # for, 1 if any other command was run and waited for, and 2 if a command
    # was run and not waited for (usually a daemon or server startup).

    my($commandname) = "";
    my($expectrc) = 0;
    my($rc, $run_extra) = run_command($testno, \$subtestno, \$expectrc, \$commandname, $TEST_STATE);
    my($cmdrc) = $?;

    if ($debug) {
      print ">> rc=$rc cmdrc=$cmdrc\n";
      if (defined $run_extra) {
        foreach my $k (keys %$run_extra) {
          my $v = defined $run_extra->{$k} ? qq!"$run_extra->{$k}"! : '<undef>';
          print ">>   $k -> $v\n";
        }
      }
    }
    $run_extra = {} unless defined $run_extra;
    foreach my $k (keys %$run_extra) {
      if (exists $TEST_STATE->{$k}) {
        my $nv = defined $run_extra->{$k} ? qq!"$run_extra->{$k}"! : 'removed';
        print ">> override of $k; was $TEST_STATE->{$k}, now $nv\n" if $debug;
      }
      if (defined $run_extra->{$k}) {
        $TEST_STATE->{$k} = $run_extra->{$k};
      } elsif (exists $TEST_STATE->{$k}) {
        delete $TEST_STATE->{$k};
      }
    }

    # Hit EOF after an initial return code number

    tests_exit(-1, "Unexpected EOF in script") if ($rc == 4);

    # Carry on with the next command if we did not wait for this one. $rc == 0
    # if no subprocess was run; $rc == 3 if we started a process but did not
    # wait for it.

    next if ($rc == 0 || $rc == 3);

    # We ran and waited for a command. Check for the expected result unless
    # it died.

    if ($cmdrc != $expectrc && !$sigpipehappened)
      {
      printf("** Command $commandno (\"$commandname\", starting at line $subtest_startline)\n");
      if (($cmdrc & 0xff) == 0)
        {
        printf("** Return code %d (expected %d)", $cmdrc/256, $expectrc/256);
        }
      elsif (($cmdrc & 0xff00) == 0)
        { printf("** Killed by signal %d", $cmdrc & 255); }
      else
        { printf("** Status %x", $cmdrc); }

      for (;;)
        {
        print "\nshow stdErr, show stdOut, Retry, Continue (without file comparison), or Quit? [Q] ";
        $_ = $force_continue ? "c" : <T>;
        tests_exit(1) if /^q?$/i;
        log_failure($log_failed_filename, $testno, "exit code unexpected") if (/^c$/i && $force_continue);
        print "... continue forced\n" if $force_continue;
        last if /^[rc]$/i;
        if (/^e$/i)
          {
          system("$more test-stderr");
          }
        elsif (/^o$/i)
          {
          system("$more test-stdout");
          }
        }

      $retry = 1 if /^r$/i;
      $docheck = 0;
      }

    # If the command was exim, and a listening server is running, we can now
    # close its input, which causes us to wait for it to finish, which is why
    # we didn't close it earlier.

    if ($rc == 2 && $server_pid != 0)
      {
      close SERVERCMD;
      $server_pid = 0;
      if ($? != 0)
        {
        if (($? & 0xff) == 0)
          { printf("Server return code %d", $?/256); }
        elsif (($? & 0xff00) == 0)
          { printf("Server killed by signal %d", $? & 255); }
        else
          { printf("Server status %x", $?); }

        for (;;)
          {
          print "\nShow server stdout, Retry, Continue, or Quit? [Q] ";
          $_ = $force_continue ? "c" : <T>;
          tests_exit(1) if /^q?$/i;
          log_failure($log_failed_filename, $testno, "exit code unexpected") if (/^c$/i && $force_continue);
          print "... continue forced\n" if $force_continue;
          last if /^[rc]$/i;

          if (/^s$/i)
            {
            open(S, "test-stdout-server") ||
              tests_exit(-1, "Failed to open test-stdout-server: $!");
            print while <S>;
            close(S);
            }
          }
        $retry = 1 if /^r$/i;
        }
      }
    }

  close SCRIPT;

  # The script has finished. Check the all the output that was generated. The
  # function returns 0 if all is well, 1 if we should rerun the test (the files
  # have been updated). It does not return if the user responds Q to a prompt.

  if ($retry)
    {
    $retry = '0';
    print (("#" x 79) . "\n");
    redo;
    }

  if ($docheck)
    {
    if (check_output($TEST_STATE->{munge}) != 0)
      {
      print (("#" x 79) . "\n");
      redo;
      }
    else
      {
      print ("  Script completed\n");
      }
    }
  }


##################################################
#         Exit from the test script              #
##################################################

tests_exit(-1, "No runnable tests selected") if @test_list == 0;
tests_exit(0);

# End of runtest script
# vim: set sw=2 et :