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