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