selftest: Start ad_dc_fips with forced fips mode
[samba.git] / selftest / selftest.pl
1 #!/usr/bin/perl
2 # Bootstrap Samba and run a number of tests against it.
3 # Copyright (C) 2005-2010 Jelmer Vernooij <jelmer@samba.org>
4 # Copyright (C) 2007-2009 Stefan Metzmacher <metze@samba.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 use strict;
20 use warnings;
21
22 use FindBin qw($RealBin $Script);
23 use File::Spec;
24 use File::Temp qw(tempfile);
25 use Getopt::Long;
26 use POSIX;
27 use Cwd qw(abs_path);
28 use lib "$RealBin";
29 use Subunit;
30 use SocketWrapper;
31 use target::Samba;
32 use Time::HiRes qw(time);
33
34 eval {
35 require Time::HiRes;
36 Time::HiRes->import("time");
37 };
38 if ($@) {
39         print "You don't have Time::Hires installed !\n";
40 }
41
42 my $opt_help = 0;
43 my $opt_target = "samba";
44 my $opt_quick = 0;
45 my $opt_socket_wrapper = 0;
46 my $opt_socket_wrapper_pcap = undef;
47 my $opt_socket_wrapper_keep_pcap = undef;
48 my $opt_random_order = 0;
49 my $opt_one = 0;
50 my @opt_exclude = ();
51 my @opt_include = ();
52 my @opt_exclude_env = ();
53 my @opt_include_env = ();
54 my $opt_testenv = 0;
55 my $opt_list = 0;
56 my $opt_mitkrb5 = 0;
57 my $opt_resetup_env = undef;
58 my $opt_load_list = undef;
59 my $opt_libnss_wrapper_so_path = "";
60 my $opt_libresolv_wrapper_so_path = "";
61 my $opt_libsocket_wrapper_so_path = "";
62 my $opt_libuid_wrapper_so_path = "";
63 my $opt_libasan_so_path = "";
64 my $opt_use_dns_faking = 0;
65 my @testlists = ();
66
67 my $srcdir = ".";
68 my $bindir = "./bin";
69 my $prefix = "./st";
70
71 my @includes = ();
72 my @excludes = ();
73
74 sub find_in_list($$)
75 {
76         my ($list, $fullname) = @_;
77
78         foreach (@$list) {
79                 if ($fullname =~ /$$_[0]/) {
80                          return ($$_[1]) if ($$_[1]);
81                          return "";
82                 }
83         }
84
85         return undef;
86 }
87
88 sub skip
89 {
90         my ($name, $envname) = @_;
91         my ($env_basename, $env_localpart) = split(/:/, $envname);
92
93         if ($opt_target eq "samba3" && $Samba::ENV_NEEDS_AD_DC{$env_basename}) {
94                 return "environment $envname is disabled as this build does not include an AD DC";
95         }
96
97         if (@opt_include_env && !(grep {$_ eq $env_basename} @opt_include_env)) {
98                 return "environment $envname is disabled (via --include-env command line option) in this test run - skipping";
99         } elsif (@opt_exclude_env && grep {$_ eq $env_basename} @opt_exclude_env) {
100                 return "environment $envname is disabled (via --exclude-env command line option) in this test run - skipping";
101         }
102
103         return find_in_list(\@excludes, $name);
104 }
105
106 sub getlog_env($);
107
108 # expand strings from %ENV
109 sub expand_environment_strings($)
110 {
111         my $s = shift;
112         # we use a reverse sort so we do the longer ones first
113         foreach my $k (sort { $b cmp $a } keys %ENV) {
114                 $s =~ s/\$$k/$ENV{$k}/g;
115         }
116         return $s;
117 }
118
119 my $target;
120
121 sub run_testsuite($$$$$)
122 {
123         my ($envname, $name, $cmd, $i, $totalsuites) = @_;
124         my $pcap_file = $target->setup_pcap($name);
125
126         Subunit::start_testsuite($name);
127         Subunit::progress_push();
128         Subunit::report_time();
129         system($cmd);
130         Subunit::report_time();
131         Subunit::progress_pop();
132
133         if ($? == -1) {
134                 print "command: $cmd\n";
135                 printf "expanded command: %s\n", expand_environment_strings($cmd);
136                 Subunit::end_testsuite($name, "error", "Unable to run $cmd: $!");
137                 exit(1);
138         } elsif ($? & 127) {
139                 print "command: $cmd\n";
140                 printf "expanded command: %s\n", expand_environment_strings($cmd);
141                 Subunit::end_testsuite($name, "error",
142                         sprintf("%s died with signal %d, %s coredump\n", $cmd, ($? & 127),  ($? & 128) ? 'with' : 'without'));
143                 exit(1);
144         }
145
146         my $exitcode = $? >> 8;
147
148         my $envlog = getlog_env($envname);
149         if ($envlog ne "") {
150                 print "envlog: $envlog\n";
151         }
152
153         print "command: $cmd\n";
154         printf "expanded command: %s\n", expand_environment_strings($cmd);
155
156         if ($exitcode == 0) {
157                 Subunit::end_testsuite($name, "success");
158         } else {
159                 Subunit::end_testsuite($name, "failure", "Exit code was $exitcode");
160         }
161
162         $target->cleanup_pcap($pcap_file, $exitcode);
163
164         if (not $opt_socket_wrapper_keep_pcap and defined($pcap_file)) {
165                 print "PCAP FILE: $pcap_file\n";
166         }
167
168         if ($exitcode != 0) {
169                 exit(1) if ($opt_one);
170         }
171
172         return $exitcode;
173 }
174
175 sub ShowHelp()
176 {
177         print "Samba test runner
178 Copyright (C) Jelmer Vernooij <jelmer\@samba.org>
179 Copyright (C) Stefan Metzmacher <metze\@samba.org>
180
181 Usage: $Script [OPTIONS] TESTNAME-REGEX [TESTNAME-REGEX...]
182
183 Generic options:
184  --help                     this help page
185  --target=samba[3]|win      Samba version to target
186  --testlist=FILE            file to read available tests from
187  --exclude=FILE             Exclude tests listed in the file
188  --include=FILE             Include tests listed in the file
189  --exclude-env=ENV          Exclude tests for the specified environment
190  --include-env=ENV          Include tests for the specified environment
191
192 Paths:
193  --prefix=DIR               prefix to run tests in [st]
194  --srcdir=DIR               source directory [.]
195  --bindir=DIR               binaries directory [./bin]
196
197 Preload cwrap:
198  --nss_wrapper_so_path=FILE the nss_wrapper library to preload
199  --resolv_wrapper_so_path=FILE the resolv_wrapper library to preload
200  --socket_wrapper_so_path=FILE the socket_wrapper library to preload
201  --uid_wrapper_so_path=FILE the uid_wrapper library to preload
202  --asan_so_path=FILE the asan library to preload
203
204 DNS:
205   --use-dns-faking          Fake DNS entries rather than talking to our
206                             DNS implementation.
207
208 Target Specific:
209  --socket-wrapper-pcap      save traffic to pcap directories
210  --socket-wrapper-keep-pcap keep all pcap files, not just those for tests that 
211                             failed
212  --socket-wrapper           enable socket wrapper
213
214 Behaviour:
215  --quick                    run quick overall test
216  --one                      abort when the first test fails
217  --testenv                  run a shell in the requested test environment
218  --list                     list available tests
219 ";
220         exit(0);
221 }
222
223 my $result = GetOptions (
224                 'help|h|?' => \$opt_help,
225                 'target=s' => \$opt_target,
226                 'prefix=s' => \$prefix,
227                 'socket-wrapper' => \$opt_socket_wrapper,
228                 'socket-wrapper-pcap' => \$opt_socket_wrapper_pcap,
229                 'socket-wrapper-keep-pcap' => \$opt_socket_wrapper_keep_pcap,
230                 'quick' => \$opt_quick,
231                 'one' => \$opt_one,
232                 'exclude=s' => \@opt_exclude,
233                 'include=s' => \@opt_include,
234                 'exclude-env=s' => \@opt_exclude_env,
235                 'include-env=s' => \@opt_include_env,
236                 'srcdir=s' => \$srcdir,
237                 'bindir=s' => \$bindir,
238                 'testenv' => \$opt_testenv,
239                 'list' => \$opt_list,
240                 'mitkrb5' => \$opt_mitkrb5,
241                 'resetup-environment' => \$opt_resetup_env,
242                 'testlist=s' => \@testlists,
243                 'random-order' => \$opt_random_order,
244                 'load-list=s' => \$opt_load_list,
245                 'nss_wrapper_so_path=s' => \$opt_libnss_wrapper_so_path,
246                 'resolv_wrapper_so_path=s' => \$opt_libresolv_wrapper_so_path,
247                 'socket_wrapper_so_path=s' => \$opt_libsocket_wrapper_so_path,
248                 'uid_wrapper_so_path=s' => \$opt_libuid_wrapper_so_path,
249                 'asan_so_path=s' => \$opt_libasan_so_path,
250                 'use-dns-faking' => \$opt_use_dns_faking
251             );
252
253 exit(1) if (not $result);
254
255 ShowHelp() if ($opt_help);
256
257 die("--list and --testenv are mutually exclusive") if ($opt_list and $opt_testenv);
258
259 # we want unbuffered output
260 $| = 1;
261
262 my @tests = @ARGV;
263
264 # quick hack to disable rpc validation when using valgrind - its way too slow
265 unless (defined($ENV{VALGRIND})) {
266         $ENV{VALIDATE} = "validate";
267         $ENV{MALLOC_CHECK_} = 3;
268 }
269
270 # make all our python scripts unbuffered
271 $ENV{PYTHONUNBUFFERED} = 1;
272
273 # do not depend on the users setup
274 # see also bootstrap/config.py
275 $ENV{TZ} = "UTC";
276 $ENV{LC_ALL} = $ENV{LANG} = "en_US.utf8";
277
278 my $bindir_abs = abs_path($bindir);
279
280 my $torture_maxtime = ($ENV{TORTURE_MAXTIME} or 1200);
281
282 $prefix =~ s+//+/+;
283 $prefix =~ s+/./+/+;
284 $prefix =~ s+/$++;
285
286 die("using an empty prefix isn't allowed") unless $prefix ne "";
287
288 # Ensure we have the test prefix around.
289 #
290 # We need restrictive
291 # permissions on this as some subdirectories in this tree will have
292 # wider permissions (ie 0777) and this would allow other users on the
293 # host to subvert the test process.
294 umask 0077;
295 mkdir($prefix, 0700) unless -d $prefix;
296 chmod 0700, $prefix;
297 # We need to have no umask limitations for the tests.
298 umask 0000;
299
300 my $prefix_abs = abs_path($prefix);
301 my $tmpdir_abs = abs_path("$prefix/tmp");
302 mkdir($tmpdir_abs, 0777) unless -d $tmpdir_abs;
303
304 my $srcdir_abs = abs_path($srcdir);
305
306 die("using an empty absolute prefix isn't allowed") unless $prefix_abs ne "";
307 die("using '/' as absolute prefix isn't allowed") unless $prefix_abs ne "/";
308
309 $ENV{SAMBA_SELFTEST} = "1";
310
311 $ENV{PREFIX} = $prefix;
312 $ENV{PREFIX_ABS} = $prefix_abs;
313 $ENV{SRCDIR} = $srcdir;
314 $ENV{SRCDIR_ABS} = $srcdir_abs;
315 $ENV{GNUPGHOME} = "$srcdir_abs/selftest/gnupg";
316 $ENV{BINDIR} = $bindir_abs;
317
318 my $tls_enabled = not $opt_quick;
319 $ENV{TLS_ENABLED} = ($tls_enabled?"yes":"no");
320
321 sub prefix_pathvar($$)
322 {
323         my ($name, $newpath) = @_;
324         if (defined($ENV{$name})) {
325                 $ENV{$name} = "$newpath:$ENV{$name}";
326         } else {
327                 $ENV{$name} = $newpath;
328         }
329 }
330 prefix_pathvar("PKG_CONFIG_PATH", "$bindir_abs/pkgconfig");
331 prefix_pathvar("PYTHONPATH", "$bindir_abs/python");
332
333 if ($opt_socket_wrapper_keep_pcap) {
334         # Socket wrapper keep pcap implies socket wrapper pcap
335         $opt_socket_wrapper_pcap = 1;
336 }
337
338 if ($opt_socket_wrapper_pcap) {
339         # Socket wrapper pcap implies socket wrapper
340         $opt_socket_wrapper = 1;
341 }
342
343 my $ld_preload = $ENV{LD_PRELOAD};
344
345 if ($opt_libasan_so_path) {
346         if ($ld_preload) {
347                 $ld_preload = "$ld_preload:$opt_libasan_so_path";
348         } else {
349                 $ld_preload = "$opt_libasan_so_path";
350         }
351 }
352
353 if ($opt_libnss_wrapper_so_path) {
354         if ($ld_preload) {
355                 $ld_preload = "$ld_preload:$opt_libnss_wrapper_so_path";
356         } else {
357                 $ld_preload = "$opt_libnss_wrapper_so_path";
358         }
359 }
360
361 if ($opt_libresolv_wrapper_so_path) {
362         if ($ld_preload) {
363                 $ld_preload = "$ld_preload:$opt_libresolv_wrapper_so_path";
364         } else {
365                 $ld_preload = "$opt_libresolv_wrapper_so_path";
366         }
367 }
368
369 if ($opt_libsocket_wrapper_so_path) {
370         if ($ld_preload) {
371                 $ld_preload = "$ld_preload:$opt_libsocket_wrapper_so_path";
372         } else {
373                 $ld_preload = "$opt_libsocket_wrapper_so_path";
374         }
375 }
376
377 if ($opt_libuid_wrapper_so_path) {
378         if ($ld_preload) {
379                 $ld_preload = "$ld_preload:$opt_libuid_wrapper_so_path";
380         } else {
381                 $ld_preload = "$opt_libuid_wrapper_so_path";
382         }
383 }
384
385 if (defined($ENV{USE_NAMESPACES})) {
386         print "Using linux containerization for selftest testenv(s)...\n";
387
388         # Create a common bridge to connect up the testenv namespaces. We give
389         # it the client's IP address, as this is where the tests will run from
390         my $ipv4_addr = Samba::get_ipv4_addr("client");
391         my $ipv6_addr = Samba::get_ipv6_addr("client");
392         system "$ENV{SRCDIR_ABS}/selftest/ns/create_bridge.sh selftest0 $ipv4_addr $ipv6_addr";
393 }
394
395 $ENV{LD_PRELOAD} = $ld_preload;
396 print "LD_PRELOAD=$ENV{LD_PRELOAD}\n";
397
398 # Enable uid_wrapper globally
399 $ENV{UID_WRAPPER} = 1;
400
401 # We are already hitting the limit, so double it.
402 $ENV{NSS_WRAPPER_MAX_HOSTENTS} = 200;
403
404 # Disable RTLD_DEEPBIND hack for Samba bind dlz module
405 #
406 # This is needed in order to allow the ldb_*ldap module
407 # to work with a preloaded socket wrapper.
408 $ENV{LDB_MODULES_DISABLE_DEEPBIND} = 1;
409
410 my $socket_wrapper_dir;
411 if ($opt_socket_wrapper) {
412         $socket_wrapper_dir = SocketWrapper::setup_dir("$prefix_abs/w", $opt_socket_wrapper_pcap);
413         print "SOCKET_WRAPPER_DIR=$socket_wrapper_dir\n";
414 } elsif (not $opt_list) {
415          unless ($< == 0) {
416                  warn("not using socket wrapper, but also not running as root. Will not be able to listen on proper ports");
417          }
418 }
419
420 if ($opt_use_dns_faking) {
421         print "DNS: Faking nameserver\n";
422         $ENV{SAMBA_DNS_FAKING} = 1;
423 }
424
425 my $testenv_default = "none";
426
427 if ($opt_mitkrb5 == 1) {
428         $ENV{MITKRB5} = $opt_mitkrb5;
429         $ENV{KRB5RCACHETYPE} = "none";
430 }
431
432 # After this many seconds, the server will self-terminate.  All tests
433 # must terminate in this time, and testenv will only stay alive this
434 # long
435
436 my $server_maxtime;
437 if ($opt_testenv) {
438     # 1 year should be enough :-)
439     $server_maxtime = 365 * 24 * 60 * 60;
440 } else {
441     # make test should run under 5 hours
442     $server_maxtime = 5 * 60 * 60;
443 }
444
445 if (defined($ENV{SMBD_MAXTIME}) and $ENV{SMBD_MAXTIME} ne "") {
446     $server_maxtime = $ENV{SMBD_MAXTIME};
447 }
448
449 $target = new Samba($bindir, $srcdir, $server_maxtime,
450                     $opt_socket_wrapper_pcap,
451                     $opt_socket_wrapper_keep_pcap);
452 unless ($opt_list) {
453         if ($opt_target eq "samba") {
454                 $testenv_default = "ad_dc";
455         } elsif ($opt_target eq "samba3") {
456                 $testenv_default = "nt4_member";
457         }
458 }
459
460 sub read_test_regexes($)
461 {
462         my ($name) = @_;
463         my @ret = ();
464         open(LF, "<$name") or die("unable to read $name: $!");
465         while (<LF>) { 
466                 chomp; 
467                 next if (/^#/);
468                 if (/^(.*?)([ \t]+)\#([\t ]*)(.*?)$/) {
469                         push (@ret, [$1, $4]);
470                 } else {
471                         s/^(.*?)([ \t]+)\#([\t ]*)(.*?)$//;
472                         push (@ret, [$_, undef]); 
473                 }
474         }
475         close(LF);
476         return @ret;
477 }
478
479 foreach (@opt_exclude) {
480         push (@excludes, read_test_regexes($_));
481 }
482
483 foreach (@opt_include) {
484         push (@includes, read_test_regexes($_));
485 }
486
487 # We give the selftest client 6 different IPv4 addresses to use. Most tests
488 # only use the first (.11) IP. Note that winsreplication.c is one test that
489 # uses the other IPs (search for iface_list_count()).
490 $ENV{SOCKET_WRAPPER_IPV4_NETWORK} = "10.53.57.0";
491 my $interfaces = Samba::get_interfaces_config("client", 6);
492
493 my $clientdir = "$prefix_abs/client";
494
495 my $conffile = "$clientdir/client.conf";
496 $ENV{SMB_CONF_PATH} = $conffile;
497
498 sub write_clientconf($$$)
499 {
500         my ($conffile, $clientdir, $vars) = @_;
501
502         mkdir("$clientdir", 0777) unless -d "$clientdir";
503
504         if ( -d "$clientdir/private" ) {
505                 unlink <$clientdir/private/*>;
506         } else {
507                 mkdir("$clientdir/private", 0777);
508         }
509
510         if ( -d "$clientdir/bind-dns" ) {
511                 unlink <$clientdir/bind-dns/*>;
512         } else {
513                 mkdir("$clientdir/bind-dns", 0777);
514         }
515
516         if ( -d "$clientdir/lockdir" ) {
517                 unlink <$clientdir/lockdir/*>;
518         } else {
519                 mkdir("$clientdir/lockdir", 0777);
520         }
521
522         if ( -d "$clientdir/statedir" ) {
523                 unlink <$clientdir/statedir/*>;
524         } else {
525                 mkdir("$clientdir/statedir", 0777);
526         }
527
528         if ( -d "$clientdir/cachedir" ) {
529                 unlink <$clientdir/cachedir/*>;
530         } else {
531                 mkdir("$clientdir/cachedir", 0777);
532         }
533
534         # this is ugly, but the ncalrpcdir needs exactly 0755
535         # otherwise tests fail.
536         my $mask = umask;
537         umask 0022;
538         if ( -d "$clientdir/ncalrpcdir/np" ) {
539                 unlink <$clientdir/ncalrpcdir/np/*>;
540                 rmdir "$clientdir/ncalrpcdir/np";
541         }
542         if ( -d "$clientdir/ncalrpcdir" ) {
543                 unlink <$clientdir/ncalrpcdir/*>;
544                 rmdir "$clientdir/ncalrpcdir";
545         }
546         mkdir("$clientdir/ncalrpcdir", 0755);
547         umask $mask;
548
549         my $cadir = "$ENV{SRCDIR_ABS}/selftest/manage-ca/CA-samba.example.com";
550         my $cacert = "$cadir/Public/CA-samba.example.com-cert.pem";
551         my $cacrl_pem = "$cadir/Public/CA-samba.example.com-crl.pem";
552         my $ca_users_dir = "$cadir/Users";
553
554         if ( -d "$clientdir/pkinit" ) {
555                 unlink <$clientdir/pkinit/*>;
556         } else {
557                 mkdir("$clientdir/pkinit", 0700);
558         }
559
560         # each user has a USER-${USER_PRINCIPAL_NAME}-cert.pem and
561         # USER-${USER_PRINCIPAL_NAME}-private-key.pem symlink
562         # We make a copy here and make the certificated easily
563         # accessable in the client environment.
564         $mask = umask;
565         umask 0077;
566         opendir USERS, "${ca_users_dir}" or die "Could not open dir '${ca_users_dir}': $!";
567         for my $d (readdir USERS) {
568                 my $user_dir = "${ca_users_dir}/${d}";
569                 next if ${d} =~ /^\./;
570                 next if (! -d "${user_dir}");
571                 opendir USER, "${user_dir}" or die "Could not open dir '${user_dir}': $!";
572                 for my $l (readdir USER) {
573                         my $user_link = "${user_dir}/${l}";
574                         next if ${l} =~ /^\./;
575                         next if (! -l "${user_link}");
576
577                         my $dest = "${clientdir}/pkinit/${l}";
578                         Samba::copy_file_content(${user_link}, ${dest});
579                 }
580                 closedir USER;
581         }
582         closedir USERS;
583         umask $mask;
584
585         open(CF, ">$conffile");
586         print CF "[global]\n";
587         print CF "\tnetbios name = client\n";
588         if (defined($vars->{DOMAIN})) {
589                 print CF "\tworkgroup = $vars->{DOMAIN}\n";
590         }
591         if (defined($vars->{REALM})) {
592                 print CF "\trealm = $vars->{REALM}\n";
593         }
594         if ($opt_socket_wrapper) {
595                 print CF "\tinterfaces = $interfaces\n";
596         }
597         print CF "
598         private dir = $clientdir/private
599         binddns dir = $clientdir/bind-dns
600         lock dir = $clientdir/lockdir
601         state directory = $clientdir/statedir
602         cache directory = $clientdir/cachedir
603         ncalrpc dir = $clientdir/ncalrpcdir
604         panic action = $RealBin/gdb_backtrace \%d
605         max xmit = 32K
606         notify:inotify = false
607         ldb:nosync = true
608         system:anonymous = true
609         client lanman auth = Yes
610         client min protocol = CORE
611         log level = 1
612         torture:basedir = $clientdir
613 #We don't want to pass our self-tests if the PAC code is wrong
614         gensec:require_pac = true
615 #We don't want to run 'speed' tests for very long
616         torture:timelimit = 1
617         winbind separator = /
618         tls cafile = ${cacert}
619         tls crlfile = ${cacrl_pem}
620         tls verify peer = no_check
621         include system krb5 conf = no
622         elasticsearch:mappings = $srcdir_abs/source3/rpc_server/mdssvc/elasticsearch_mappings.json
623 ";
624         close(CF);
625 }
626
627 my @todo = ();
628
629 sub should_run_test($)
630 {
631         my $name = shift;
632         if ($#tests == -1) {
633                 return 1;
634         }
635         for (my $i=0; $i <= $#tests; $i++) {
636                 if ($name =~ /$tests[$i]/i) {
637                         return 1;
638                 }
639         }
640         return 0;
641 }
642
643 sub read_testlist($)
644 {
645         my ($filename) = @_;
646
647         my @ret = ();
648         open(IN, $filename) or die("Unable to open $filename: $!");
649
650         while (<IN>) {
651                 if (/-- TEST(-LOADLIST|) --\n/) {
652                         my $supports_loadlist = (defined($1) and $1 eq "-LOADLIST");
653                         my $name = <IN>;
654                         $name =~ s/\n//g;
655                         my $env = <IN>;
656                         $env =~ s/\n//g;
657                         my $loadlist;
658                         if ($supports_loadlist) {
659                                 $loadlist = <IN>;
660                                 $loadlist =~ s/\n//g;
661                         }
662                         my $cmdline = <IN>;
663                         $cmdline =~ s/\n//g;
664                         if (should_run_test($name) == 1) {
665                                 push (@ret, [$name, $env, $cmdline, $loadlist]);
666                         }
667                 } else {
668                         print;
669                 }
670         }
671         close(IN) or die("Error creating recipe from $filename");
672         return @ret;
673 }
674
675 if ($#testlists == -1) {
676         die("No testlists specified");
677 }
678
679 $ENV{SELFTEST_PREFIX} = "$prefix_abs";
680 $ENV{SELFTEST_TMPDIR} = "$tmpdir_abs";
681 $ENV{TMPDIR} = "$tmpdir_abs";
682 $ENV{TEST_DATA_PREFIX} = "$tmpdir_abs";
683 if ($opt_quick) {
684         $ENV{SELFTEST_QUICK} = "1";
685 } else {
686         $ENV{SELFTEST_QUICK} = "";
687 }
688 $ENV{SELFTEST_MAXTIME} = $torture_maxtime;
689
690 my $selftest_resolv_conf_path = "$tmpdir_abs/selftest.resolv.conf";
691 $ENV{RESOLV_CONF} = "${selftest_resolv_conf_path}.global";
692
693 my $selftest_krbt_ccache_path = "$tmpdir_abs/selftest.krb5_ccache";
694 $ENV{KRB5CCNAME} = "FILE:${selftest_krbt_ccache_path}.global";
695
696 my @available = ();
697 foreach my $fn (@testlists) {
698         foreach (read_testlist($fn)) {
699                 my $name = $$_[0];
700                 next if (@includes and not defined(find_in_list(\@includes, $name)));
701                 push (@available, $_);
702         }
703 }
704
705 my $restricted = undef;
706 my $restricted_used = {};
707
708 if ($opt_load_list) {
709         $restricted = [];
710         open(LOAD_LIST, "<$opt_load_list") or die("Unable to open $opt_load_list");
711         while (<LOAD_LIST>) {
712                 chomp;
713                 push (@$restricted, $_);
714         }
715         close(LOAD_LIST);
716 }
717
718 my $individual_tests = undef;
719 $individual_tests = {};
720
721 foreach my $testsuite (@available) {
722         my $name = $$testsuite[0];
723         my $skipreason = skip(@$testsuite);
724         if (defined($restricted)) {
725                 # Find the testsuite for this test
726                 my $match = undef;
727                 foreach my $r (@$restricted) {
728                         if ($r eq $name) {
729                                 $individual_tests->{$name} = [];
730                                 $match = $r;
731                                 $restricted_used->{$r} = 1;
732                         } elsif (substr($r, 0, length($name)+1) eq "$name.") {
733                                 push(@{$individual_tests->{$name}}, $r);
734                                 $match = $r;
735                                 $restricted_used->{$r} = 1;
736                         }
737                 }
738                 if ($match) {
739                         if (defined($skipreason)) {
740                                 if (not $opt_list) {
741                                         Subunit::skip_testsuite($name, $skipreason);
742                                 }
743                         } else {
744                                 push(@todo, $testsuite);
745                         }
746                 }
747         } elsif (defined($skipreason)) {
748                 if (not $opt_list) {
749                         Subunit::skip_testsuite($name, $skipreason);
750                 }
751         } else {
752                 push(@todo, $testsuite);
753         }
754 }
755
756 if (defined($restricted)) {
757         foreach (@$restricted) {
758                 unless (defined($restricted_used->{$_})) {
759                         print "No test or testsuite found matching $_\n";
760                 }
761         }
762 } elsif ($#todo == -1) {
763         print STDERR "No tests to run\n";
764         exit(1);
765 }
766
767 my $suitestotal = $#todo + 1;
768
769 unless ($opt_list) {
770         Subunit::progress($suitestotal);
771         Subunit::report_time();
772 }
773
774 my $i = 0;
775 $| = 1;
776
777 my %running_envs = ();
778
779 sub get_running_env($)
780 {
781         my ($name) = @_;
782
783         my $envname = $name;
784
785         $envname =~ s/:.*//;
786
787         return $running_envs{$envname};
788 }
789
790 sub sighandler($)
791 {
792         my $signame = shift;
793
794         $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'DEFAULT';
795         $SIG{PIPE} = 'IGNORE';
796
797         open(STDOUT, ">&STDERR") or die "can't dup STDOUT to STDERR: $!";
798
799         print "$0: PID[$$]: Got SIG${signame} teardown environments.\n";
800         teardown_env($_) foreach(keys %running_envs);
801         system("pstree -p $$");
802         print "$0: PID[$$]: Exiting...\n";
803         exit(1);
804 };
805
806 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = $SIG{PIPE} = \&sighandler;
807
808 sub setup_env($$)
809 {
810         my ($name, $prefix) = @_;
811
812         my $testenv_vars = undef;
813
814         my $envname = $name;
815         my $option = $name;
816
817         $envname =~ s/:.*//;
818         $option =~ s/^[^:]*//;
819         $option =~ s/^://;
820
821         $option = "client" if $option eq "";
822
823         # Initially clear out the environment for the provision, so previous envs'
824         # variables don't leak in. Provisioning steps must explicitly set their
825         # necessary variables when calling out to other executables
826         Samba::clear_exported_envvars();
827         delete $ENV{SOCKET_WRAPPER_DEFAULT_IFACE};
828         delete $ENV{SMB_CONF_PATH};
829
830         $ENV{RESOLV_CONF} = "${selftest_resolv_conf_path}.${envname}/ignore";
831         $ENV{KRB5CCNAME} = "FILE:${selftest_krbt_ccache_path}.${envname}/ignore";
832
833         if (defined(get_running_env($envname))) {
834                 $testenv_vars = get_running_env($envname);
835                 if (not $testenv_vars->{target}->check_env($testenv_vars)) {
836                         print $testenv_vars->{target}->getlog_env($testenv_vars);
837                         $testenv_vars = undef;
838                 }
839         } else {
840                 $testenv_vars = $target->setup_env($envname, $prefix);
841                 if (not defined($testenv_vars)) {
842                         my $msg = "$opt_target can't start up known environment '$envname'";
843                         if ($opt_one) {
844                                 die($msg);
845                         }
846                         warn $msg;
847                         return;
848                 }
849                 if (ref $testenv_vars ne "HASH") {
850                         return $testenv_vars;
851                 }
852                 if (defined($testenv_vars->{target})) {
853                         $testenv_vars->{target} = $target;
854                 }
855         }
856
857         return undef unless defined($testenv_vars);
858
859         $running_envs{$envname} = $testenv_vars;
860
861         if ($option eq "local") {
862                 SocketWrapper::set_default_iface($testenv_vars->{SOCKET_WRAPPER_DEFAULT_IFACE});
863                 $ENV{SMB_CONF_PATH} = $testenv_vars->{SERVERCONFFILE};
864         } elsif ($option eq "client") {
865                 SocketWrapper::set_default_iface(11);
866                 write_clientconf($conffile, $clientdir, $testenv_vars);
867                 $ENV{SMB_CONF_PATH} = $conffile;
868         } else {
869                 die("Unknown option[$option] for envname[$envname]");
870         }
871
872         # export the environment variables for the testenv (SERVER, SERVER_IP, etc)
873         Samba::export_envvars($testenv_vars);
874
875         my $krb5_ccache_path = "${selftest_krbt_ccache_path}.${envname}.${option}";
876         unlink($krb5_ccache_path);
877         $ENV{KRB5CCNAME} = "FILE:${krb5_ccache_path}";
878         return $testenv_vars;
879 }
880
881 sub getlog_env($)
882 {
883         my ($envname) = @_;
884         return "" if ($envname eq "none");
885         my $env = get_running_env($envname);
886         return $env->{target}->getlog_env($env);
887 }
888
889 sub check_env($)
890 {
891         my ($envname) = @_;
892         my $env = get_running_env($envname);
893         return $env->{target}->check_env($env);
894 }
895
896 sub teardown_env($)
897 {
898         my ($envname) = @_;
899         return if ($envname eq "none");
900         print STDERR "teardown_env($envname)\n";
901         my $env = get_running_env($envname);
902         $env->{target}->teardown_env($env);
903         delete $running_envs{$envname};
904 }
905
906 # This 'global' file needs to be empty when we start
907 unlink("$prefix_abs/dns_host_file");
908 unlink("$prefix_abs/hosts");
909
910 if ($opt_random_order) {
911         require List::Util;
912         my @newtodo = List::Util::shuffle(@todo);
913         @todo = @newtodo;
914 }
915
916 if ($opt_testenv) {
917         my $testenv_name = $ENV{SELFTEST_TESTENV};
918         $testenv_name = $testenv_default unless defined($testenv_name);
919
920         my $testenv_vars = setup_env($testenv_name, $prefix);
921
922         if (not $testenv_vars or $testenv_vars eq "UNKNOWN") {
923                 die("Unable to setup environment $testenv_name");
924         }
925
926         $ENV{PIDDIR} = $testenv_vars->{PIDDIR};
927         $ENV{ENVNAME} = $testenv_name;
928
929         my $envvarstr = Samba::exported_envvars_str($testenv_vars);
930
931         my @term_args = ("echo -e \"
932 Welcome to the Samba4 Test environment '$testenv_name'
933
934 This matches the client environment used in make test
935 server is pid `cat \$PIDDIR/samba.pid`
936
937 Some useful environment variables:
938 TORTURE_OPTIONS=\$TORTURE_OPTIONS
939 SMB_CONF_PATH=\$SMB_CONF_PATH
940
941 $envvarstr
942 \" && LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH} bash");
943         my @term = ();
944         if ($ENV{TERMINAL}) {
945             @term = ($ENV{TERMINAL});
946                 # override the default terminal args (if specified)
947                 if (defined($ENV{TERMINAL_ARGS})) {
948                         @term_args = split(/ /, $ENV{TERMINAL_ARGS});
949                 }
950         } else {
951             @term = ("xterm", "-e");
952             unshift(@term_args, ("bash", "-c"));
953         }
954
955         system(@term, @term_args);
956
957         teardown_env($testenv_name);
958 } elsif ($opt_list) {
959         foreach (@todo) {
960                 my $name = $$_[0];
961                 my $envname = $$_[1];
962                 my $cmd = $$_[2];
963                 my $listcmd = $$_[3];
964
965                 unless (defined($listcmd)) {
966                         warn("Unable to list tests in $name");
967                         # Rather than ignoring this testsuite altogether, just pretend the entire testsuite is
968                         # a single "test".
969                         print "$name\n";
970                         next;
971                 }
972
973                 system($listcmd);
974
975                 if ($? == -1) {
976                         die("Unable to run $listcmd: $!");
977                 } elsif ($? & 127) {
978                         die(sprintf("%s died with signal %d, %s coredump\n", $listcmd, ($? & 127),  ($? & 128) ? 'with' : 'without'));
979                 }
980
981                 my $exitcode = $? >> 8;
982                 if ($exitcode != 0) {
983                         die("$cmd exited with exit code $exitcode");
984                 }
985         }
986 } else {
987         foreach (@todo) {
988                 $i++;
989                 my $cmd = $$_[2];
990                 my $name = $$_[0];
991                 my $envname = $$_[1];
992                 my $envvars = setup_env($envname, $prefix);
993
994                 if (not defined($envvars)) {
995                         Subunit::start_testsuite($name);
996                         Subunit::end_testsuite($name, "error",
997                                 "unable to set up environment $envname - exiting");
998                         next;
999                 } elsif ($envvars eq "UNKNOWN") {
1000                         Subunit::start_testsuite($name);
1001                         Subunit::end_testsuite($name, "error",
1002                                 "environment $envname is unknown - exiting");
1003                         next;
1004                 }
1005
1006                 # Generate a file with the individual tests to run, if the 
1007                 # test runner for this test suite supports it.
1008                 if ($individual_tests and $individual_tests->{$name}) {
1009                         if ($$_[3]) {
1010                                 my ($fh, $listid_file) = tempfile(UNLINK => 0);
1011                                 foreach my $test (@{$individual_tests->{$name}}) {
1012                                         print $fh substr($test, length($name)+1) . "\n";
1013                                 }
1014                                 $cmd =~ s/\$LOADLIST/--load-list=$listid_file/g;
1015                         } else {
1016                                 warn("Unable to run individual tests in $name, it does not support --loadlist.");
1017                         }
1018                 }
1019
1020                 run_testsuite($envname, $name, $cmd, $i, $suitestotal);
1021
1022                 teardown_env($envname) if ($opt_resetup_env);
1023         }
1024 }
1025
1026 print "\n";
1027
1028 teardown_env($_) foreach (keys %running_envs);
1029
1030 my $failed = 0;
1031
1032 # if there were any valgrind failures, show them
1033 foreach (<$prefix/valgrind.log*>) {
1034         next unless (-s $_);
1035         print "VALGRIND FAILURE\n";
1036         $failed++;
1037         system("cat $_");
1038 }
1039 exit 0;