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