selftest: Don't use global dirs when parsing customdc realm
[metze/samba/wip.git] / selftest / target / Samba4.pm
1 #!/usr/bin/perl
2 # Bootstrap Samba and run a number of tests against it.
3 # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
4 # Published under the GNU GPL, v3 or later.
5
6 # NOTE: Refer to the README for more details about the various testenvs,
7 # and tips about adding new testenvs.
8
9 package Samba4;
10
11 use strict;
12 use Cwd qw(abs_path);
13 use FindBin qw($RealBin);
14 use POSIX;
15 use SocketWrapper;
16 use target::Samba;
17 use target::Samba3;
18 use Archive::Tar;
19 use File::Path 'make_path';
20
21 sub new($$$$$) {
22         my ($classname, $bindir, $ldap, $srcdir, $server_maxtime) = @_;
23
24         my $self = {
25                 vars => {},
26                 ldap => $ldap,
27                 bindir => $bindir,
28                 srcdir => $srcdir,
29                 server_maxtime => $server_maxtime,
30                 target3 => new Samba3($bindir, $srcdir, $server_maxtime)
31         };
32         bless $self;
33         return $self;
34 }
35
36 sub scriptdir_path($$) {
37         my ($self, $path) = @_;
38         return "$self->{srcdir}/source4/scripting/$path";
39 }
40
41 sub openldap_start($$$) {
42 }
43
44 sub slapd_start($$)
45 {
46         my $count = 0;
47         my ($self, $env_vars, $STDIN_READER) = @_;
48         my $ldbsearch = Samba::bindir_path($self, "ldbsearch");
49
50         my $uri = $env_vars->{LDAP_URI};
51
52         if (system("$ldbsearch -H $uri -s base -b \"\" supportedLDAPVersion > /dev/null") == 0) {
53             print "A SLAPD is still listening to $uri before we started the LDAP backend.  Aborting!";
54             return 1;
55         }
56         # running slapd in the background means it stays in the same process group, so it can be
57         # killed by timelimit
58         my $pid = fork();
59         if ($pid == 0) {
60                 open STDOUT, ">$env_vars->{LDAPDIR}/logs";
61                 open STDERR, '>&STDOUT';
62                 close($env_vars->{STDIN_PIPE});
63                 open STDIN, ">&", $STDIN_READER or die "can't dup STDIN_READER to STDIN: $!";
64
65                 if ($self->{ldap} eq "fedora-ds") {
66                         exec("$ENV{FEDORA_DS_ROOT}/sbin/ns-slapd", "-D", $env_vars->{FEDORA_DS_DIR}, "-d0", "-i", $env_vars->{FEDORA_DS_PIDFILE});
67                 } elsif ($self->{ldap} eq "openldap") {
68                         exec($ENV{OPENLDAP_SLAPD}, "-dnone", "-F", $env_vars->{SLAPD_CONF_D}, "-h", $uri);
69                 }
70                 die("Unable to start slapd: $!");
71         }
72         $env_vars->{SLAPD_PID} = $pid;
73         sleep(1);
74         while (system("$ldbsearch -H $uri -s base -b \"\" supportedLDAPVersion > /dev/null") != 0) {
75                 $count++;
76                 if ($count > 40) {
77                         $self->slapd_stop($env_vars);
78                         return 0;
79                 }
80                 sleep(1);
81         }
82         return 1;
83 }
84
85 sub slapd_stop($$)
86 {
87         my ($self, $envvars) = @_;
88         kill 9, $envvars->{SLAPD_PID};
89         return 1;
90 }
91
92 sub check_or_start($$$)
93 {
94         my ($self, $env_vars, $process_model) = @_;
95         my $STDIN_READER;
96
97         my $env_ok = $self->check_env($env_vars);
98         if ($env_ok) {
99                 return $env_vars->{SAMBA_PID};
100         } elsif (defined($env_vars->{SAMBA_PID})) {
101                 warn("SAMBA PID $env_vars->{SAMBA_PID} is not running (died)");
102                 return undef;
103         }
104
105         # use a pipe for stdin in the child processes. This allows
106         # those processes to monitor the pipe for EOF to ensure they
107         # exit when the test script exits
108         pipe($STDIN_READER, $env_vars->{STDIN_PIPE});
109
110         # Start slapd before samba, but with the fifo on stdin
111         if (defined($self->{ldap})) {
112                 unless($self->slapd_start($env_vars, $STDIN_READER)) {
113                         warn("couldn't start slapd (main run)");
114                         return undef;
115                 }
116         }
117
118         # build up the command to run samba
119         my @preargs = ();
120         my @optargs = ();
121         if (defined($ENV{SAMBA_OPTIONS})) {
122                 @optargs = split(/ /, $ENV{SAMBA_OPTIONS});
123         }
124         if(defined($ENV{SAMBA_VALGRIND})) {
125                 @preargs = split(/ /,$ENV{SAMBA_VALGRIND});
126         }
127
128         if (defined($process_model)) {
129                 push @optargs, ("-M", $process_model);
130         }
131         my $binary = Samba::bindir_path($self, "samba");
132         my @full_cmd = (@preargs, $binary, "-i",
133                         "--no-process-group", "--maximum-runtime=$self->{server_maxtime}",
134                         $env_vars->{CONFIGURATION}, @optargs);
135
136         # the samba process takes some additional env variables (compared to s3)
137         my $samba_envs = Samba::get_env_for_process("samba", $env_vars);
138         $samba_envs->{RESOLV_CONF} = $env_vars->{RESOLV_CONF};
139         $samba_envs->{UID_WRAPPER} = "1";
140         if (defined($ENV{MITKRB5})) {
141                 $samba_envs->{KRB5_KDC_PROFILE} = $env_vars->{MITKDC_CONFIG};
142         }
143
144         # fork a child process and exec() samba
145         my $daemon_ctx = {
146                 NAME => "samba",
147                 BINARY_PATH => $binary,
148                 FULL_CMD => [ @full_cmd ],
149                 LOG_FILE => $env_vars->{SAMBA_TEST_LOG},
150                 TEE_STDOUT => 1,
151                 ENV_VARS => $samba_envs,
152         };
153         my $pid = Samba::fork_and_exec($self, $env_vars, $daemon_ctx, $STDIN_READER);
154
155         $env_vars->{SAMBA_PID} = $pid;
156
157         # close the parent's read-end of the pipe
158         close($STDIN_READER);
159
160         if ($self->wait_for_start($env_vars) != 0) {
161             warn("Samba $pid failed to start up");
162             return undef;
163         }
164
165         return $pid;
166 }
167
168 sub wait_for_start($$)
169 {
170         my ($self, $testenv_vars) = @_;
171         my $count = 0;
172         my $ret = 0;
173
174         if (not $self->check_env($testenv_vars)) {
175             warn("unable to confirm Samba $testenv_vars->{SAMBA_PID} is running");
176             return -1;
177         }
178
179         # This will return quickly when things are up, but be slow if we
180         # need to wait for (eg) SSL init
181         my $nmblookup =  Samba::bindir_path($self, "nmblookup4");
182
183         do {
184                 $ret = system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{SERVER}");
185                 if ($ret != 0) {
186                         sleep(1);
187                 } else {
188                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{SERVER}");
189                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
190                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
191                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
192                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
193                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{SERVER}");
194                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{SERVER}");
195                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
196                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
197                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
198                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
199                 }
200                 $count++;
201         } while ($ret != 0 && $count < 20);
202         if ($count == 20) {
203                 teardown_env($self, $testenv_vars);
204                 warn("nbt not reachable after 20 retries\n");
205                 return -1;
206         }
207
208         # Ensure we have the first RID Set before we start tests.  This makes the tests more reliable.
209         if ($testenv_vars->{SERVER_ROLE} eq "domain controller") {
210                 print "waiting for working LDAP and a RID Set to be allocated\n";
211                 my $ldbsearch = Samba::bindir_path($self, "ldbsearch");
212                 my $count = 0;
213                 my $base_dn = "DC=".join(",DC=", split(/\./, $testenv_vars->{REALM}));
214
215                 my $search_dn = $base_dn;
216                 if ($testenv_vars->{NETBIOSNAME} ne "RODC") {
217                         # TODO currently no check for actual rIDAllocationPool
218                         $search_dn = "cn=RID Set,cn=$testenv_vars->{NETBIOSNAME},ou=domain controllers,$base_dn";
219                 }
220                 my $max_wait = 60;
221
222                 # Add hosts file for name lookups
223                 my $cmd = "NSS_WRAPPER_HOSTS='$testenv_vars->{NSS_WRAPPER_HOSTS}' ";
224                 if (defined($testenv_vars->{RESOLV_WRAPPER_CONF})) {
225                         $cmd .= "RESOLV_WRAPPER_CONF='$testenv_vars->{RESOLV_WRAPPER_CONF}' ";
226                 } else {
227                         $cmd .= "RESOLV_WRAPPER_HOSTS='$testenv_vars->{RESOLV_WRAPPER_HOSTS}' ";
228                 }
229                 $cmd .= "RESOLV_CONF='$testenv_vars->{RESOLV_CONF}' ";
230
231                 $cmd .= "$ldbsearch ";
232                 $cmd .= "$testenv_vars->{CONFIGURATION} ";
233                 $cmd .= "-H ldap://$testenv_vars->{SERVER} ";
234                 $cmd .= "-U$testenv_vars->{USERNAME}%$testenv_vars->{PASSWORD} ";
235                 $cmd .= "-s base ";
236                 $cmd .= "-b '$search_dn' ";
237                 while (system("$cmd >/dev/null") != 0) {
238                         $count++;
239                         if ($count > $max_wait) {
240                                 teardown_env($self, $testenv_vars);
241                                 warn("Timed out ($max_wait sec) waiting for working LDAP and a RID Set to be allocated by $testenv_vars->{NETBIOSNAME} PID $testenv_vars->{SAMBA_PID}");
242                                 return -1;
243                         }
244                         print "Waiting for working LDAP...\n";
245                         sleep(1);
246                 }
247         }
248
249         my $wbinfo =  Samba::bindir_path($self, "wbinfo");
250
251         $count = 0;
252         do {
253                 my $cmd = "NSS_WRAPPER_PASSWD=$testenv_vars->{NSS_WRAPPER_PASSWD} ";
254                 $cmd .= "NSS_WRAPPER_GROUP=$testenv_vars->{NSS_WRAPPER_GROUP} ";
255                 $cmd .= "SELFTEST_WINBINDD_SOCKET_DIR=$testenv_vars->{SELFTEST_WINBINDD_SOCKET_DIR} ";
256                 $cmd .= "$wbinfo -P";
257                 $ret = system($cmd);
258
259                 if ($ret != 0) {
260                         sleep(1);
261                 }
262                 $count++;
263         } while ($ret != 0 && $count < 20);
264         if ($count == 20) {
265                 teardown_env($self, $testenv_vars);
266                 warn("winbind not reachable after 20 retries\n");
267                 return -1;
268         }
269
270         # Ensure we registered all our names
271         if ($testenv_vars->{SERVER_ROLE} eq "domain controller") {
272                 my $max_wait = 120;
273                 print "Waiting for dns_update_cache to be created.\n";
274                 $count = 0;
275                 while (not -e "$testenv_vars->{PRIVATEDIR}/dns_update_cache") {
276                         $count++;
277                         if ($count > $max_wait) {
278                                 teardown_env($self, $testenv_vars);
279                                 warn("Timed out ($max_wait sec) waiting for dns_update_cache PID $testenv_vars->{SAMBA_PID}");
280                                 return -1;
281                         }
282                         print "Waiting for dns_update_cache to be created...\n";
283                         sleep(1);
284                 }
285                 print "Waiting for dns_update_cache to be filled.\n";
286                 $count = 0;
287                 while ((-s "$testenv_vars->{PRIVATEDIR}/dns_update_cache") == 0) {
288                         $count++;
289                         if ($count > $max_wait) {
290                                 teardown_env($self, $testenv_vars);
291                                 warn("Timed out ($max_wait sec) waiting for dns_update_cache PID $testenv_vars->{SAMBA_PID}");
292                                 return -1;
293                         }
294                         print "Waiting for dns_update_cache to be filled...\n";
295                         sleep(1);
296                 }
297         }
298
299         print $self->getlog_env($testenv_vars);
300
301         print "READY ($testenv_vars->{SAMBA_PID})\n";
302
303         return 0
304 }
305
306 sub write_ldb_file($$$)
307 {
308         my ($self, $file, $ldif) = @_;
309
310         my $ldbadd =  Samba::bindir_path($self, "ldbadd");
311         open(LDIF, "|$ldbadd -H $file >/dev/null");
312         print LDIF $ldif;
313         return(close(LDIF));
314 }
315
316 sub add_wins_config($$)
317 {
318         my ($self, $privatedir) = @_;
319         my $client_ip = Samba::get_ipv4_addr("client");
320
321         return $self->write_ldb_file("$privatedir/wins_config.ldb", "
322 dn: name=TORTURE_11,CN=PARTNERS
323 objectClass: wreplPartner
324 name: TORTURE_11
325 address: $client_ip
326 pullInterval: 0
327 pushChangeCount: 0
328 type: 0x3
329 ");
330 }
331
332 sub mk_fedora_ds($$)
333 {
334         my ($self, $ctx) = @_;
335
336         #Make the subdirectory be as fedora DS would expect
337         my $fedora_ds_dir = "$ctx->{ldapdir}/slapd-$ctx->{ldap_instance}";
338
339         my $pidfile = "$fedora_ds_dir/logs/slapd-$ctx->{ldap_instance}.pid";
340
341         return ($fedora_ds_dir, $pidfile);
342 }
343
344 sub mk_openldap($$)
345 {
346         my ($self, $ctx) = @_;
347
348         my $slapd_conf_d = "$ctx->{ldapdir}/slapd.d";
349         my $pidfile = "$ctx->{ldapdir}/slapd.pid";
350
351         return ($slapd_conf_d, $pidfile);
352 }
353
354 sub setup_dns_hub_internal($$$)
355 {
356         my ($self, $hostname, $prefix) = @_;
357         my $STDIN_READER;
358
359         unless(-d $prefix or make_path($prefix, 0777)) {
360                 warn("Unable to create $prefix");
361                 return undef;
362         }
363         my $prefix_abs = abs_path($prefix);
364
365         die ("prefix=''") if $prefix_abs eq "";
366         die ("prefix='/'") if $prefix_abs eq "/";
367
368         unless (system("rm -rf $prefix_abs/*") == 0) {
369                 warn("Unable to clean up");
370         }
371
372         my $env = undef;
373         $env->{NETBIOSNAME} = $hostname;
374
375         $env->{SERVER_IP} = Samba::get_ipv4_addr($hostname);
376         $env->{SERVER_IPV6} = Samba::get_ipv6_addr($hostname);
377         $env->{SOCKET_WRAPPER_DEFAULT_IFACE} = Samba::get_interface($hostname);
378         $env->{DNS_HUB_LOG} = "$prefix_abs/dns_hub.log";
379         $env->{RESOLV_CONF} = "$prefix_abs/resolv.conf";
380         $env->{TESTENV_DIR} = $prefix_abs;
381
382         open(RESOLV_CONF, ">$env->{RESOLV_CONF}");
383         print RESOLV_CONF "nameserver $env->{SERVER_IP}\n";
384         print RESOLV_CONF "nameserver $env->{SERVER_IPV6}\n";
385         close(RESOLV_CONF);
386
387         my @preargs = ();
388         my @args = ();
389         if (!defined($ENV{PYTHON})) {
390             push (@preargs, "env");
391             push (@preargs, "python");
392         } else {
393             push (@preargs, $ENV{PYTHON});
394         }
395         my $binary = "$self->{srcdir}/selftest/target/dns_hub.py";
396         push (@args, "$self->{server_maxtime}");
397         push (@args, "$env->{SERVER_IP}");
398         push (@args, Samba::realm_to_ip_mappings());
399         my @full_cmd = (@preargs, $binary, @args);
400
401         my $daemon_ctx = {
402                 NAME => "dnshub",
403                 BINARY_PATH => $binary,
404                 FULL_CMD => [ @full_cmd ],
405                 LOG_FILE => $env->{DNS_HUB_LOG},
406                 TEE_STDOUT => 1,
407                 PCAP_FILE => "$ENV{SOCKET_WRAPPER_PCAP_DIR}/env-$hostname$.pcap",
408                 ENV_VARS => {},
409         };
410
411         # use a pipe for stdin in the child processes. This allows
412         # those processes to monitor the pipe for EOF to ensure they
413         # exit when the test script exits
414         pipe($STDIN_READER, $env->{STDIN_PIPE});
415
416         my $pid = Samba::fork_and_exec($self, $env, $daemon_ctx, $STDIN_READER);
417
418         $env->{SAMBA_PID} = $pid;
419         $env->{KRB5_CONFIG} = "$prefix_abs/no_krb5.conf";
420
421         # close the parent's read-end of the pipe
422         close($STDIN_READER);
423
424         return $env;
425 }
426
427 sub setup_dns_hub
428 {
429         my ($self, $prefix) = @_;
430
431         my $hostname = "rootdnsforwarder";
432
433         my $env = $self->setup_dns_hub_internal("$hostname", "$prefix/$hostname");
434
435         $self->{dns_hub_env} = $env;
436
437         return $env;
438 }
439
440 sub get_dns_hub_env($)
441 {
442         my ($self, $prefix) = @_;
443
444         if (defined($self->{dns_hub_env})) {
445                 return $self->{dns_hub_env};
446         }
447
448         die("get_dns_hub_env() not setup 'dns_hub_env'");
449         return undef;
450 }
451
452 # Returns the environmental variables that we pass to samba-tool commands
453 sub get_cmd_env_vars
454 {
455         my ($self, $localenv) = @_;
456
457         my $cmd_env = "NSS_WRAPPER_HOSTS='$localenv->{NSS_WRAPPER_HOSTS}' ";
458         $cmd_env .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$localenv->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
459         if (defined($localenv->{RESOLV_WRAPPER_CONF})) {
460                 $cmd_env .= "RESOLV_WRAPPER_CONF=\"$localenv->{RESOLV_WRAPPER_CONF}\" ";
461         } else {
462                 $cmd_env .= "RESOLV_WRAPPER_HOSTS=\"$localenv->{RESOLV_WRAPPER_HOSTS}\" ";
463         }
464         $cmd_env .= " KRB5_CONFIG=\"$localenv->{KRB5_CONFIG}\" ";
465         $cmd_env .= "KRB5CCNAME=\"$localenv->{KRB5_CCACHE}\" ";
466         $cmd_env .= "RESOLV_CONF=\"$localenv->{RESOLV_CONF}\" ";
467
468         return $cmd_env;
469 }
470
471 # Sets up a forest trust namespace.
472 # (Note this is different to kernel namespaces, setup by the
473 # USE_NAMESPACES=1 option)
474 sub setup_namespaces($$:$$)
475 {
476         my ($self, $localenv, $upn_array, $spn_array) = @_;
477
478         @{$upn_array} = [] unless defined($upn_array);
479         my $upn_args = "";
480         foreach my $upn (@{$upn_array}) {
481                 $upn_args .= " --add-upn-suffix=$upn";
482         }
483
484         @{$spn_array} = [] unless defined($spn_array);
485         my $spn_args = "";
486         foreach my $spn (@{$spn_array}) {
487                 $spn_args .= " --add-spn-suffix=$spn";
488         }
489
490         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
491
492         my $cmd_env = $self->get_cmd_env_vars($localenv);
493
494         my $cmd_config = " $localenv->{CONFIGURATION}";
495
496         my $namespaces = $cmd_env;
497         $namespaces .= " $samba_tool domain trust namespaces $upn_args $spn_args";
498         $namespaces .= $cmd_config;
499         unless (system($namespaces) == 0) {
500                 warn("Failed to add namespaces \n$namespaces");
501                 return;
502         }
503
504         return;
505 }
506
507 sub setup_trust($$$$$)
508 {
509         my ($self, $localenv, $remoteenv, $type, $extra_args) = @_;
510
511         $localenv->{TRUST_SERVER} = $remoteenv->{SERVER};
512
513         $localenv->{TRUST_USERNAME} = $remoteenv->{USERNAME};
514         $localenv->{TRUST_PASSWORD} = $remoteenv->{PASSWORD};
515         $localenv->{TRUST_DOMAIN} = $remoteenv->{DOMAIN};
516         $localenv->{TRUST_REALM} = $remoteenv->{REALM};
517         $localenv->{TRUST_DOMSID} = $remoteenv->{DOMSID};
518
519         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
520
521         # setup the trust
522         my $cmd_env = $self->get_cmd_env_vars($localenv);
523
524         my $cmd_config = " $localenv->{CONFIGURATION}";
525         my $cmd_creds = $cmd_config;
526         $cmd_creds .= " -U$localenv->{TRUST_DOMAIN}\\\\$localenv->{TRUST_USERNAME}\%$localenv->{TRUST_PASSWORD}";
527
528         my $create = $cmd_env;
529         $create .= " $samba_tool domain trust create --type=${type} $localenv->{TRUST_REALM}";
530         $create .= " $extra_args";
531         $create .= $cmd_creds;
532         unless (system($create) == 0) {
533                 warn("Failed to create trust \n$create");
534                 return undef;
535         }
536
537         my $groupname = "g_$localenv->{TRUST_DOMAIN}";
538         my $groupadd = $cmd_env;
539         $groupadd .= " $samba_tool group add '$groupname' --group-scope=Domain $cmd_config";
540         unless (system($groupadd) == 0) {
541                 warn("Failed to create group \n$groupadd");
542                 return undef;
543         }
544         my $groupmem = $cmd_env;
545         $groupmem .= " $samba_tool group addmembers '$groupname' '$localenv->{TRUST_DOMSID}-513' $cmd_config";
546         unless (system($groupmem) == 0) {
547                 warn("Failed to add group member \n$groupmem");
548                 return undef;
549         }
550
551         return $localenv
552 }
553
554 sub provision_raw_prepare($$$$$$$$$$$$)
555 {
556         my ($self, $prefix, $server_role, $hostname,
557             $domain, $realm, $samsid, $functional_level,
558             $password, $kdc_ipv4, $kdc_ipv6) = @_;
559         my $ctx;
560         my $python_cmd = "";
561         if (defined $ENV{PYTHON}) {
562                 $python_cmd = $ENV{PYTHON} . " ";
563         }
564         $ctx->{python} = $python_cmd;
565         my $netbiosname = uc($hostname);
566
567         unless(-d $prefix or mkdir($prefix, 0777)) {
568                 warn("Unable to create $prefix");
569                 return undef;
570         }
571         my $prefix_abs = abs_path($prefix);
572
573         die ("prefix=''") if $prefix_abs eq "";
574         die ("prefix='/'") if $prefix_abs eq "/";
575
576         unless (system("rm -rf $prefix_abs/*") == 0) {
577                 warn("Unable to clean up");
578         }
579
580         
581         my $swiface = Samba::get_interface($hostname);
582
583         $ctx->{prefix} = $prefix;
584         $ctx->{prefix_abs} = $prefix_abs;
585
586         $ctx->{server_role} = $server_role;
587         $ctx->{hostname} = $hostname;
588         $ctx->{netbiosname} = $netbiosname;
589         $ctx->{swiface} = $swiface;
590         $ctx->{password} = $password;
591         $ctx->{kdc_ipv4} = $kdc_ipv4;
592         $ctx->{kdc_ipv6} = $kdc_ipv6;
593         $ctx->{krb5_ccname} = "$prefix_abs/krb5cc_%{uid}";
594         if ($functional_level eq "2000") {
595                 $ctx->{supported_enctypes} = "arcfour-hmac-md5 des-cbc-md5 des-cbc-crc"
596         }
597
598 #
599 # Set smbd log level here.
600 #
601         $ctx->{server_loglevel} =$ENV{SERVER_LOG_LEVEL} || 1;
602         $ctx->{username} = "Administrator";
603         $ctx->{domain} = $domain;
604         $ctx->{realm} = uc($realm);
605         $ctx->{dnsname} = lc($realm);
606         $ctx->{samsid} = $samsid;
607
608         $ctx->{functional_level} = $functional_level;
609
610         my $unix_name = ($ENV{USER} or $ENV{LOGNAME} or `whoami`);
611         chomp $unix_name;
612         $ctx->{unix_name} = $unix_name;
613         $ctx->{unix_uid} = $>;
614         my @mygid = split(" ", $();
615         $ctx->{unix_gid} = $mygid[0];
616         $ctx->{unix_gids_str} = $);
617         @{$ctx->{unix_gids}} = split(" ", $ctx->{unix_gids_str});
618
619         $ctx->{etcdir} = "$prefix_abs/etc";
620         $ctx->{piddir} = "$prefix_abs/pid";
621         $ctx->{smb_conf} = "$ctx->{etcdir}/smb.conf";
622         $ctx->{krb5_conf} = "$ctx->{etcdir}/krb5.conf";
623         $ctx->{krb5_ccache} = "$prefix_abs/krb5_ccache";
624         $ctx->{mitkdc_conf} = "$ctx->{etcdir}/mitkdc.conf";
625         $ctx->{privatedir} = "$prefix_abs/private";
626         $ctx->{binddnsdir} = "$prefix_abs/bind-dns";
627         $ctx->{ncalrpcdir} = "$prefix_abs/ncalrpc";
628         $ctx->{lockdir} = "$prefix_abs/lockdir";
629         $ctx->{logdir} = "$prefix_abs/logs";
630         $ctx->{statedir} = "$prefix_abs/statedir";
631         $ctx->{cachedir} = "$prefix_abs/cachedir";
632         $ctx->{winbindd_socket_dir} = "$prefix_abs/winbindd_socket";
633         $ctx->{ntp_signd_socket_dir} = "$prefix_abs/ntp_signd_socket";
634         $ctx->{nsswrap_passwd} = "$ctx->{etcdir}/passwd";
635         $ctx->{nsswrap_group} = "$ctx->{etcdir}/group";
636         $ctx->{nsswrap_hosts} = "$ENV{SELFTEST_PREFIX}/hosts";
637         $ctx->{nsswrap_hostname} = "$ctx->{hostname}.$ctx->{dnsname}";
638         if ($ENV{SAMBA_DNS_FAKING}) {
639                 $ctx->{dns_host_file} = "$ENV{SELFTEST_PREFIX}/dns_host_file";
640                 $ctx->{samba_dnsupdate} = "$ENV{SRCDIR_ABS}/source4/scripting/bin/samba_dnsupdate -s $ctx->{smb_conf} --all-interfaces --use-file=$ctx->{dns_host_file}";
641                 $ctx->{samba_dnsupdate} = $python_cmd .  $ctx->{samba_dnsupdate};
642         } else {
643                 $ctx->{samba_dnsupdate} = "$ENV{SRCDIR_ABS}/source4/scripting/bin/samba_dnsupdate -s $ctx->{smb_conf} --all-interfaces";
644                 $ctx->{samba_dnsupdate} = $python_cmd .  $ctx->{samba_dnsupdate};
645                 $ctx->{use_resolv_wrapper} = 1;
646         }
647
648         my $dns_hub = $self->get_dns_hub_env();
649         $ctx->{resolv_conf} = $dns_hub->{RESOLV_CONF};
650
651         $ctx->{tlsdir} = "$ctx->{privatedir}/tls";
652
653         $ctx->{ipv4} = Samba::get_ipv4_addr($hostname);
654         $ctx->{ipv6} = Samba::get_ipv6_addr($hostname);
655
656         push(@{$ctx->{directories}}, $ctx->{privatedir});
657         push(@{$ctx->{directories}}, $ctx->{binddnsdir});
658         push(@{$ctx->{directories}}, $ctx->{etcdir});
659         push(@{$ctx->{directories}}, $ctx->{piddir});
660         push(@{$ctx->{directories}}, $ctx->{lockdir});
661         push(@{$ctx->{directories}}, $ctx->{logdir});
662         push(@{$ctx->{directories}}, $ctx->{statedir});
663         push(@{$ctx->{directories}}, $ctx->{cachedir});
664
665         $ctx->{smb_conf_extra_options} = "";
666
667         my @provision_options = ();
668         push (@provision_options, "KRB5_CONFIG=\"$ctx->{krb5_conf}\"");
669         push (@provision_options, "KRB5_CCACHE=\"$ctx->{krb5_ccache}\"");
670         push (@provision_options, "NSS_WRAPPER_PASSWD=\"$ctx->{nsswrap_passwd}\"");
671         push (@provision_options, "NSS_WRAPPER_GROUP=\"$ctx->{nsswrap_group}\"");
672         push (@provision_options, "NSS_WRAPPER_HOSTS=\"$ctx->{nsswrap_hosts}\"");
673         push (@provision_options, "NSS_WRAPPER_HOSTNAME=\"$ctx->{nsswrap_hostname}\"");
674         if (defined($ctx->{use_resolv_wrapper})) {
675                 push (@provision_options, "RESOLV_WRAPPER_CONF=\"$ctx->{resolv_conf}\"");
676                 push (@provision_options, "RESOLV_CONF=\"$ctx->{resolv_conf}\"");
677         } else {
678                 push (@provision_options, "RESOLV_WRAPPER_HOSTS=\"$ctx->{dns_host_file}\"");
679         }
680         if (defined($ENV{GDB_PROVISION})) {
681                 push (@provision_options, "gdb --args");
682                 if (!defined($ENV{PYTHON})) {
683                     push (@provision_options, "env");
684                     push (@provision_options, "python");
685                 }
686         }
687         if (defined($ENV{VALGRIND_PROVISION})) {
688                 push (@provision_options, "valgrind");
689                 if (!defined($ENV{PYTHON})) {
690                     push (@provision_options, "env");
691                     push (@provision_options, "python");
692                 }
693         }
694
695         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
696
697         push (@provision_options, $samba_tool);
698         push (@provision_options, "domain");
699         push (@provision_options, "provision");
700         push (@provision_options, "--configfile=$ctx->{smb_conf}");
701         push (@provision_options, "--host-name=$ctx->{hostname}");
702         push (@provision_options, "--host-ip=$ctx->{ipv4}");
703         push (@provision_options, "--quiet");
704         push (@provision_options, "--domain=$ctx->{domain}");
705         push (@provision_options, "--realm=$ctx->{realm}");
706         if (defined($ctx->{samsid})) {
707                 push (@provision_options, "--domain-sid=$ctx->{samsid}");
708         }
709         push (@provision_options, "--adminpass=$ctx->{password}");
710         push (@provision_options, "--krbtgtpass=krbtgt$ctx->{password}");
711         push (@provision_options, "--machinepass=machine$ctx->{password}");
712         push (@provision_options, "--root=$ctx->{unix_name}");
713         push (@provision_options, "--server-role=\"$ctx->{server_role}\"");
714         push (@provision_options, "--function-level=\"$ctx->{functional_level}\"");
715
716         @{$ctx->{provision_options}} = @provision_options;
717
718         return $ctx;
719 }
720
721 sub has_option
722 {
723         my ($self, $keyword, @options_list) = @_;
724
725         # convert the options-list to a hash-map for easy keyword lookup
726         my %options_dict = map { $_ => 1 } @options_list;
727
728         return exists $options_dict{$keyword};
729 }
730
731 #
732 # Step1 creates the basic configuration
733 #
734 sub provision_raw_step1($$)
735 {
736         my ($self, $ctx) = @_;
737
738         mkdir($_, 0777) foreach (@{$ctx->{directories}});
739
740         ##
741         ## lockdir and piddir must be 0755
742         ##
743         chmod 0755, $ctx->{lockdir};
744         chmod 0755, $ctx->{piddir};
745
746         unless (open(CONFFILE, ">$ctx->{smb_conf}")) {
747                 warn("can't open $ctx->{smb_conf}$?");
748                 return undef;
749         }
750
751         Samba::prepare_keyblobs($ctx);
752         my $crlfile = "$ctx->{tlsdir}/crl.pem";
753         $crlfile = "" unless -e ${crlfile};
754
755         # work out which file server to use. Default to source3 smbd (s3fs),
756         # unless the source4 NTVFS (smb) file server has been specified
757         my $services = "-smb +s3fs";
758         if ($self->has_option("--use-ntvfs", @{$ctx->{provision_options}})) {
759                 $services = "+smb -s3fs";
760         }
761
762         my $interfaces = Samba::get_interfaces_config($ctx->{netbiosname});
763
764         print CONFFILE "
765 [global]
766         netbios name = $ctx->{netbiosname}
767         posix:eadb = $ctx->{statedir}/eadb.tdb
768         workgroup = $ctx->{domain}
769         realm = $ctx->{realm}
770         private dir = $ctx->{privatedir}
771         binddns dir = $ctx->{binddnsdir}
772         pid directory = $ctx->{piddir}
773         ncalrpc dir = $ctx->{ncalrpcdir}
774         lock dir = $ctx->{lockdir}
775         state directory = $ctx->{statedir}
776         cache directory = $ctx->{cachedir}
777         winbindd socket directory = $ctx->{winbindd_socket_dir}
778         ntp signd socket directory = $ctx->{ntp_signd_socket_dir}
779         winbind separator = /
780         interfaces = $interfaces
781         tls dh params file = $ctx->{tlsdir}/dhparms.pem
782         tls crlfile = ${crlfile}
783         tls verify peer = no_check
784         panic action = $RealBin/gdb_backtrace \%d
785         wins support = yes
786         server role = $ctx->{server_role}
787         server services = +echo $services
788         dcerpc endpoint servers = +winreg +srvsvc
789         notify:inotify = false
790         ldb:nosync = true
791         ldap server require strong auth = yes
792 #We don't want to pass our self-tests if the PAC code is wrong
793         gensec:require_pac = true
794         log file = $ctx->{logdir}/log.\%m
795         log level = $ctx->{server_loglevel}
796         lanman auth = Yes
797         ntlm auth = Yes
798         rndc command = true
799         dns update command = $ctx->{samba_dnsupdate}
800         spn update command = $ctx->{python} $ENV{SRCDIR_ABS}/source4/scripting/bin/samba_spnupdate -s $ctx->{smb_conf}
801         gpo update command = $ctx->{python} $ENV{SRCDIR_ABS}/source4/scripting/bin/samba-gpupdate -s $ctx->{smb_conf} --target=Computer
802         samba kcc command = $ctx->{python} $ENV{SRCDIR_ABS}/source4/scripting/bin/samba_kcc
803         dreplsrv:periodic_startup_interval = 0
804         dsdb:schema update allowed = yes
805
806         vfs objects = dfs_samba4 acl_xattr fake_acls xattr_tdb streams_depot
807
808         idmap_ldb:use rfc2307=yes
809         winbind enum users = yes
810         winbind enum groups = yes
811
812         rpc server port:netlogon = 1026
813         include system krb5 conf = no
814
815 ";
816
817         print CONFFILE "
818
819         # Begin extra options
820         $ctx->{smb_conf_extra_options}
821         # End extra options
822 ";
823         close(CONFFILE);
824
825         #Default the KDC IP to the server's IP
826         if (not defined($ctx->{kdc_ipv4})) {
827                 $ctx->{kdc_ipv4} = $ctx->{ipv4};
828         }
829         if (not defined($ctx->{kdc_ipv6})) {
830                 $ctx->{kdc_ipv6} = $ctx->{ipv6};
831         }
832
833         Samba::mk_krb5_conf($ctx);
834         Samba::mk_mitkdc_conf($ctx, abs_path(Samba::bindir_path($self, "shared")));
835
836         open(PWD, ">$ctx->{nsswrap_passwd}");
837         if ($ctx->{unix_uid} != 0) {
838                 print PWD "root:x:0:0:root gecos:$ctx->{prefix_abs}:/bin/false\n";
839         }
840         print PWD "$ctx->{unix_name}:x:$ctx->{unix_uid}:65531:$ctx->{unix_name} gecos:$ctx->{prefix_abs}:/bin/false\n";
841         print PWD "nobody:x:65534:65533:nobody gecos:$ctx->{prefix_abs}:/bin/false
842 pdbtest:x:65533:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
843 pdbtest2:x:65532:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
844 pdbtest3:x:65531:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
845 pdbtest4:x:65530:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
846 ";
847         close(PWD);
848         my $uid_rfc2307test = 65533;
849
850         open(GRP, ">$ctx->{nsswrap_group}");
851         if ($ctx->{unix_gid} != 0) {
852                 print GRP "root:x:0:\n";
853         }
854         print GRP "$ctx->{unix_name}:x:$ctx->{unix_gid}:\n";
855         print GRP "wheel:x:10:
856 users:x:65531:
857 nobody:x:65533:
858 nogroup:x:65534:nobody
859 ";
860         close(GRP);
861         my $gid_rfc2307test = 65532;
862
863         my $hostname = lc($ctx->{hostname});
864         open(HOSTS, ">>$ctx->{nsswrap_hosts}");
865         if ($hostname eq "localdc") {
866                 print HOSTS "$ctx->{ipv4} ${hostname}.$ctx->{dnsname} $ctx->{dnsname} ${hostname}\n";
867                 print HOSTS "$ctx->{ipv6} ${hostname}.$ctx->{dnsname} $ctx->{dnsname} ${hostname}\n";
868         } else {
869                 print HOSTS "$ctx->{ipv4} ${hostname}.$ctx->{dnsname} ${hostname}\n";
870                 print HOSTS "$ctx->{ipv6} ${hostname}.$ctx->{dnsname} ${hostname}\n";
871         }
872         close(HOSTS);
873
874         my $configuration = "--configfile=$ctx->{smb_conf}";
875
876 #Ensure the config file is valid before we start
877         my $testparm = Samba::bindir_path($self, "samba-tool") . " testparm";
878         if (system("$testparm $configuration -v --suppress-prompt >/dev/null 2>&1") != 0) {
879                 system("$testparm -v --suppress-prompt $configuration >&2");
880                 warn("Failed to create a valid smb.conf configuration $testparm!");
881                 return undef;
882         }
883         unless (system("($testparm $configuration -v --suppress-prompt --parameter-name=\"netbios name\" --section-name=global 2> /dev/null | grep -i \"^$ctx->{netbiosname}\" ) >/dev/null 2>&1") == 0) {
884                 warn("Failed to create a valid smb.conf configuration! $testparm $configuration -v --suppress-prompt --parameter-name=\"netbios name\" --section-name=global");
885                 return undef;
886         }
887
888         # Return the environment variables for the new testenv DC.
889         # Note that we have SERVER_X and DC_SERVER_X variables (which have the same
890         # value initially). In a 2 DC setup, $DC_SERVER_X will always be the PDC.
891         my $ret = {
892                 KRB5_CONFIG => $ctx->{krb5_conf},
893                 KRB5_CCACHE => $ctx->{krb5_ccache},
894                 MITKDC_CONFIG => $ctx->{mitkdc_conf},
895                 PIDDIR => $ctx->{piddir},
896                 SERVER => $ctx->{hostname},
897                 DC_SERVER => $ctx->{hostname},
898                 SERVER_IP => $ctx->{ipv4},
899                 DC_SERVER_IP => $ctx->{ipv4},
900                 SERVER_IPV6 => $ctx->{ipv6},
901                 DC_SERVER_IPV6 => $ctx->{ipv6},
902                 NETBIOSNAME => $ctx->{netbiosname},
903                 DC_NETBIOSNAME => $ctx->{netbiosname},
904                 DOMAIN => $ctx->{domain},
905                 USERNAME => $ctx->{username},
906                 DC_USERNAME => $ctx->{username},
907                 REALM => $ctx->{realm},
908                 DNSNAME => $ctx->{dnsname},
909                 SAMSID => $ctx->{samsid},
910                 PASSWORD => $ctx->{password},
911                 DC_PASSWORD => $ctx->{password},
912                 LDAPDIR => $ctx->{ldapdir},
913                 LDAP_INSTANCE => $ctx->{ldap_instance},
914                 SELFTEST_WINBINDD_SOCKET_DIR => $ctx->{winbindd_socket_dir},
915                 NCALRPCDIR => $ctx->{ncalrpcdir},
916                 LOCKDIR => $ctx->{lockdir},
917                 STATEDIR => $ctx->{statedir},
918                 CACHEDIR => $ctx->{cachedir},
919                 PRIVATEDIR => $ctx->{privatedir},
920                 BINDDNSDIR => $ctx->{binddnsdir},
921                 SERVERCONFFILE => $ctx->{smb_conf},
922                 TESTENV_DIR => $ctx->{prefix_abs},
923                 CONFIGURATION => $configuration,
924                 SOCKET_WRAPPER_DEFAULT_IFACE => $ctx->{swiface},
925                 NSS_WRAPPER_PASSWD => $ctx->{nsswrap_passwd},
926                 NSS_WRAPPER_GROUP => $ctx->{nsswrap_group},
927                 NSS_WRAPPER_HOSTS => $ctx->{nsswrap_hosts},
928                 NSS_WRAPPER_HOSTNAME => $ctx->{nsswrap_hostname},
929                 SAMBA_TEST_FIFO => "$ctx->{prefix}/samba_test.fifo",
930                 SAMBA_TEST_LOG => "$ctx->{prefix}/samba_test.log",
931                 SAMBA_TEST_LOG_POS => 0,
932                 NSS_WRAPPER_MODULE_SO_PATH => Samba::nss_wrapper_winbind_so_path($self),
933                 NSS_WRAPPER_MODULE_FN_PREFIX => "winbind",
934                 LOCAL_PATH => $ctx->{share},
935                 UID_RFC2307TEST => $uid_rfc2307test,
936                 GID_RFC2307TEST => $gid_rfc2307test,
937                 SERVER_ROLE => $ctx->{server_role},
938                 RESOLV_CONF => $ctx->{resolv_conf}
939         };
940
941         if (defined($ctx->{use_resolv_wrapper})) {
942                 $ret->{RESOLV_WRAPPER_CONF} = $ctx->{resolv_conf};
943         } else {
944                 $ret->{RESOLV_WRAPPER_HOSTS} = $ctx->{dns_host_file};
945         }
946
947         if ($ctx->{server_role} eq "domain controller") {
948                 $ret->{DOMSID} = $ret->{SAMSID};
949         }
950
951         return $ret;
952 }
953
954 #
955 # Step2 runs the provision script
956 #
957 sub provision_raw_step2($$$)
958 {
959         my ($self, $ctx, $ret) = @_;
960
961         my $provision_cmd = join(" ", @{$ctx->{provision_options}});
962         unless (system($provision_cmd) == 0) {
963                 warn("Unable to provision: \n$provision_cmd\n");
964                 return undef;
965         }
966
967         my $testallowed_account = "testallowed";
968         my $samba_tool_cmd = "";
969         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
970         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
971         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
972             . " user create --configfile=$ctx->{smb_conf} $testallowed_account $ctx->{password}";
973         unless (system($samba_tool_cmd) == 0) {
974                 warn("Unable to add testallowed user: \n$samba_tool_cmd\n");
975                 return undef;
976         }
977
978         my $ldbmodify = "";
979         $ldbmodify .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
980         $ldbmodify .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
981         $ldbmodify .= Samba::bindir_path($self, "ldbmodify");
982         $ldbmodify .=  " --configfile=$ctx->{smb_conf}";
983         my $base_dn = "DC=".join(",DC=", split(/\./, $ctx->{realm}));
984
985         if ($ctx->{server_role} ne "domain controller") {
986                 $base_dn = "DC=$ctx->{netbiosname}";
987         }
988
989         my $user_dn = "cn=$testallowed_account,cn=users,$base_dn";
990         $testallowed_account = "testallowed account";
991         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
992         print LDIF "dn: $user_dn
993 changetype: modify
994 replace: samAccountName
995 samAccountName: $testallowed_account
996 -
997 ";
998         close(LDIF);
999
1000         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
1001         print LDIF "dn: $user_dn
1002 changetype: modify
1003 replace: userPrincipalName
1004 userPrincipalName: testallowed upn\@$ctx->{realm}
1005 replace: servicePrincipalName
1006 servicePrincipalName: host/testallowed
1007 -           
1008 ";
1009         close(LDIF);
1010
1011         $samba_tool_cmd = "";
1012         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1013         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1014         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
1015             . " user create --configfile=$ctx->{smb_conf} testdenied $ctx->{password}";
1016         unless (system($samba_tool_cmd) == 0) {
1017                 warn("Unable to add testdenied user: \n$samba_tool_cmd\n");
1018                 return undef;
1019         }
1020
1021         my $user_dn = "cn=testdenied,cn=users,$base_dn";
1022         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
1023         print LDIF "dn: $user_dn
1024 changetype: modify
1025 replace: userPrincipalName
1026 userPrincipalName: testdenied_upn\@$ctx->{realm}.upn
1027 -           
1028 ";
1029         close(LDIF);
1030
1031         $samba_tool_cmd = "";
1032         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1033         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1034         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
1035             . " user create --configfile=$ctx->{smb_conf} testupnspn $ctx->{password}";
1036         unless (system($samba_tool_cmd) == 0) {
1037                 warn("Unable to add testupnspn user: \n$samba_tool_cmd\n");
1038                 return undef;
1039         }
1040
1041         my $user_dn = "cn=testupnspn,cn=users,$base_dn";
1042         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
1043         print LDIF "dn: $user_dn
1044 changetype: modify
1045 replace: userPrincipalName
1046 userPrincipalName: http/testupnspn.$ctx->{dnsname}\@$ctx->{realm}
1047 replace: servicePrincipalName
1048 servicePrincipalName: http/testupnspn.$ctx->{dnsname}
1049 -
1050 ";
1051         close(LDIF);
1052
1053         $samba_tool_cmd = "";
1054         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1055         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1056         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
1057             . " group addmembers --configfile=$ctx->{smb_conf} 'Allowed RODC Password Replication Group' '$testallowed_account'";
1058         unless (system($samba_tool_cmd) == 0) {
1059                 warn("Unable to add '$testallowed_account' user to 'Allowed RODC Password Replication Group': \n$samba_tool_cmd\n");
1060                 return undef;
1061         }
1062
1063         # Create to users alice and bob!
1064         my $user_account_array = ["alice", "bob", "jane"];
1065
1066         foreach my $user_account (@{$user_account_array}) {
1067                 my $samba_tool_cmd = "";
1068
1069                 $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1070                 $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1071                 $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
1072                     . " user create --configfile=$ctx->{smb_conf} $user_account Secret007";
1073                 unless (system($samba_tool_cmd) == 0) {
1074                         warn("Unable to create user: $user_account\n$samba_tool_cmd\n");
1075                         return undef;
1076                 }
1077         }
1078
1079         my $ldbmodify = "";
1080         $ldbmodify .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1081         $ldbmodify .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1082         $ldbmodify .= Samba::bindir_path($self, "ldbmodify");
1083         $ldbmodify .=  " --configfile=$ctx->{smb_conf}";
1084         my $base_dn = "DC=".join(",DC=", split(/\./, $ctx->{realm}));
1085         my $user_dn = "cn=jane,cn=users,$base_dn";
1086
1087         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
1088         print LDIF "dn: $user_dn
1089 changetype: modify
1090 replace: userPrincipalName
1091 userPrincipalName: jane.doe\@$ctx->{realm}
1092 -
1093 ";
1094         close(LDIF);
1095
1096         return $ret;
1097 }
1098
1099 sub provision($$$$$$$$$$)
1100 {
1101         my ($self, $prefix, $server_role, $hostname,
1102             $domain, $realm, $functional_level,
1103             $password, $kdc_ipv4, $kdc_ipv6, $extra_smbconf_options, $extra_smbconf_shares,
1104             $extra_provision_options) = @_;
1105
1106         my $samsid = Samba::random_domain_sid();
1107
1108         my $ctx = $self->provision_raw_prepare($prefix, $server_role,
1109                                                $hostname,
1110                                                $domain, $realm,
1111                                                $samsid,
1112                                                $functional_level,
1113                                                $password, $kdc_ipv4, $kdc_ipv6);
1114
1115         if (defined($extra_provision_options)) {
1116                 push (@{$ctx->{provision_options}}, @{$extra_provision_options});
1117         }
1118
1119         $ctx->{share} = "$ctx->{prefix_abs}/share";
1120         push(@{$ctx->{directories}}, "$ctx->{share}");
1121         push(@{$ctx->{directories}}, "$ctx->{share}/test1");
1122         push(@{$ctx->{directories}}, "$ctx->{share}/test2");
1123
1124         # precreate directories for printer drivers
1125         push(@{$ctx->{directories}}, "$ctx->{share}/W32X86");
1126         push(@{$ctx->{directories}}, "$ctx->{share}/x64");
1127         push(@{$ctx->{directories}}, "$ctx->{share}/WIN40");
1128
1129         my $msdfs = "no";
1130         $msdfs = "yes" if ($server_role eq "domain controller");
1131         $ctx->{smb_conf_extra_options} = "
1132
1133         max xmit = 32K
1134         server max protocol = SMB2
1135         host msdfs = $msdfs
1136         lanman auth = yes
1137
1138         # fruit:copyfile is a global option
1139         fruit:copyfile = yes
1140
1141         $extra_smbconf_options
1142
1143 [tmp]
1144         path = $ctx->{share}
1145         read only = no
1146         posix:sharedelay = 100000
1147         posix:oplocktimeout = 3
1148         posix:writetimeupdatedelay = 500000
1149
1150 [xcopy_share]
1151         path = $ctx->{share}
1152         read only = no
1153         posix:sharedelay = 100000
1154         posix:oplocktimeout = 3
1155         posix:writetimeupdatedelay = 500000
1156         create mask = 777
1157         force create mode = 777
1158
1159 [posix_share]
1160         path = $ctx->{share}
1161         read only = no
1162         create mask = 0777
1163         force create mode = 0
1164         directory mask = 0777
1165         force directory mode = 0
1166
1167 [test1]
1168         path = $ctx->{share}/test1
1169         read only = no
1170         posix:sharedelay = 100000
1171         posix:oplocktimeout = 3
1172         posix:writetimeupdatedelay = 500000
1173
1174 [test2]
1175         path = $ctx->{share}/test2
1176         read only = no
1177         posix:sharedelay = 100000
1178         posix:oplocktimeout = 3
1179         posix:writetimeupdatedelay = 500000
1180
1181 [cifs]
1182         path = $ctx->{share}/_ignore_cifs_
1183         read only = no
1184         ntvfs handler = cifs
1185         cifs:server = $ctx->{netbiosname}
1186         cifs:share = tmp
1187         cifs:use-s4u2proxy = yes
1188         # There is no username specified here, instead the client is expected
1189         # to log in with kerberos, and the serverwill use delegated credentials.
1190         # Or the server tries s4u2self/s4u2proxy to impersonate the client
1191
1192 [simple]
1193         path = $ctx->{share}
1194         read only = no
1195         ntvfs handler = simple
1196
1197 [sysvol]
1198         path = $ctx->{statedir}/sysvol
1199         read only = no
1200
1201 [netlogon]
1202         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1203         read only = no
1204
1205 [cifsposix]
1206         copy = simple
1207         ntvfs handler = cifsposix
1208
1209 [vfs_fruit]
1210         path = $ctx->{share}
1211         vfs objects = catia fruit streams_xattr acl_xattr
1212         ea support = yes
1213         fruit:resource = file
1214         fruit:metadata = netatalk
1215         fruit:locking = netatalk
1216         fruit:encoding = native
1217
1218 $extra_smbconf_shares
1219 ";
1220
1221         if (defined($self->{ldap})) {
1222                 $ctx->{ldapdir} = "$ctx->{privatedir}/ldap";
1223                 push(@{$ctx->{directories}}, "$ctx->{ldapdir}");
1224
1225                 my $ldap_uri= "$ctx->{ldapdir}/ldapi";
1226                 $ldap_uri =~ s|/|%2F|g;
1227                 $ldap_uri = "ldapi://$ldap_uri";
1228                 $ctx->{ldap_uri} = $ldap_uri;
1229
1230                 $ctx->{ldap_instance} = lc($ctx->{netbiosname});
1231         }
1232
1233         my $ret = $self->provision_raw_step1($ctx);
1234         unless (defined $ret) {
1235                 return undef;
1236         }
1237
1238         if (defined($self->{ldap})) {
1239                 $ret->{LDAP_URI} = $ctx->{ldap_uri};
1240                 push (@{$ctx->{provision_options}}, "--ldap-backend-type=" . $self->{ldap});
1241                 push (@{$ctx->{provision_options}}, "--ldap-backend-nosync");
1242                 if ($self->{ldap} eq "openldap") {
1243                         push (@{$ctx->{provision_options}}, "--slapd-path=" . $ENV{OPENLDAP_SLAPD});
1244                         ($ret->{SLAPD_CONF_D}, $ret->{OPENLDAP_PIDFILE}) = $self->mk_openldap($ctx) or die("Unable to create openldap directories");
1245
1246                 } elsif ($self->{ldap} eq "fedora-ds") {
1247                         push (@{$ctx->{provision_options}}, "--slapd-path=" . "$ENV{FEDORA_DS_ROOT}/sbin/ns-slapd");
1248                         push (@{$ctx->{provision_options}}, "--setup-ds-path=" . "$ENV{FEDORA_DS_ROOT}/sbin/setup-ds.pl");
1249                         ($ret->{FEDORA_DS_DIR}, $ret->{FEDORA_DS_PIDFILE}) = $self->mk_fedora_ds($ctx) or die("Unable to create fedora ds directories");
1250                 }
1251
1252         }
1253
1254         return $self->provision_raw_step2($ctx, $ret);
1255 }
1256
1257 # For multi-DC testenvs, we want $DC_SERVER to always be the PDC (i.e. the
1258 # original DC) in the testenv. $SERVER is always the joined DC that we are
1259 # actually running the test against
1260 sub set_pdc_env_vars
1261 {
1262         my ($self, $env, $dcvars) = @_;
1263
1264         $env->{DC_SERVER} = $dcvars->{DC_SERVER};
1265         $env->{DC_SERVER_IP} = $dcvars->{DC_SERVER_IP};
1266         $env->{DC_SERVER_IPV6} = $dcvars->{DC_SERVER_IPV6};
1267         $env->{DC_SERVERCONFFILE} = $dcvars->{SERVERCONFFILE};
1268         $env->{DC_NETBIOSNAME} = $dcvars->{DC_NETBIOSNAME};
1269         $env->{DC_USERNAME} = $dcvars->{DC_USERNAME};
1270         $env->{DC_PASSWORD} = $dcvars->{DC_PASSWORD};
1271 }
1272
1273 sub provision_s4member($$$$$)
1274 {
1275         my ($self, $prefix, $dcvars, $hostname, $more_conf) = @_;
1276         print "PROVISIONING MEMBER...\n";
1277         my $extra_smb_conf = "
1278         passdb backend = samba_dsdb
1279 winbindd:use external pipes = true
1280
1281 # the source4 smb server doesn't allow signing by default
1282 server signing = enabled
1283 raw NTLMv2 auth = yes
1284
1285 rpc_server:default = external
1286 rpc_server:svcctl = embedded
1287 rpc_server:srvsvc = embedded
1288 rpc_server:eventlog = embedded
1289 rpc_server:ntsvcs = embedded
1290 rpc_server:winreg = embedded
1291 rpc_server:spoolss = embedded
1292 rpc_daemon:spoolssd = embedded
1293 rpc_server:tcpip = no
1294 ";
1295         if ($more_conf) {
1296                 $extra_smb_conf = $extra_smb_conf . $more_conf . "\n";
1297         }
1298         my $extra_provision_options = ["--use-ntvfs"];
1299         my $ret = $self->provision($prefix,
1300                                    "member server",
1301                                    $hostname,
1302                                    $dcvars->{DOMAIN},
1303                                    $dcvars->{REALM},
1304                                    "2008",
1305                                    "locMEMpass3",
1306                                    $dcvars->{SERVER_IP},
1307                                    $dcvars->{SERVER_IPV6},
1308                                    $extra_smb_conf, "",
1309                                    $extra_provision_options);
1310         unless ($ret) {
1311                 return undef;
1312         }
1313
1314         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1315         my $cmd = $self->get_cmd_env_vars($ret);
1316         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} member";
1317         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1318         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1319
1320         unless (system($cmd) == 0) {
1321                 warn("Join failed\n$cmd");
1322                 return undef;
1323         }
1324
1325         $ret->{DOMSID} = $dcvars->{DOMSID};
1326         $self->set_pdc_env_vars($ret, $dcvars);
1327
1328         return $ret;
1329 }
1330
1331 sub provision_rpc_proxy($$$)
1332 {
1333         my ($self, $prefix, $dcvars) = @_;
1334         print "PROVISIONING RPC PROXY...\n";
1335
1336         my $extra_smbconf_options = "
1337         passdb backend = samba_dsdb
1338
1339         # rpc_proxy
1340         dcerpc_remote:binding = ncacn_ip_tcp:$dcvars->{SERVER}
1341         dcerpc endpoint servers = epmapper, remote
1342         dcerpc_remote:interfaces = rpcecho
1343         dcerpc_remote:allow_anonymous_fallback = yes
1344
1345 [cifs_to_dc]
1346         path = /tmp/_ignore_cifs_to_dc_/_none_
1347         read only = no
1348         ntvfs handler = cifs
1349         cifs:server = $dcvars->{SERVER}
1350         cifs:share = cifs
1351         cifs:use-s4u2proxy = yes
1352         # There is no username specified here, instead the client is expected
1353         # to log in with kerberos, and the serverwill use delegated credentials.
1354         # Or the server tries s4u2self/s4u2proxy to impersonate the client
1355
1356 ";
1357
1358         my $extra_provision_options = ["--use-ntvfs"];
1359         my $ret = $self->provision($prefix,
1360                                    "member server",
1361                                    "localrpcproxy",
1362                                    $dcvars->{DOMAIN},
1363                                    $dcvars->{REALM},
1364                                    "2008",
1365                                    "locRPCproxypass4",
1366                                    $dcvars->{SERVER_IP},
1367                                    $dcvars->{SERVER_IPV6},
1368                                    $extra_smbconf_options, "",
1369                                    $extra_provision_options);
1370         unless ($ret) {
1371                 return undef;
1372         }
1373
1374         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1375
1376         # The joind runs in the context of the rpc_proxy/member for now
1377         my $cmd = $self->get_cmd_env_vars($ret);
1378         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} member";
1379         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1380         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1381
1382         unless (system($cmd) == 0) {
1383                 warn("Join failed\n$cmd");
1384                 return undef;
1385         }
1386
1387         # Setting up delegation runs in the context of the DC for now
1388         $cmd = "";
1389         $cmd .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$dcvars->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
1390         $cmd .= "KRB5_CONFIG=\"$dcvars->{KRB5_CONFIG}\" ";
1391         $cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1392         $cmd .= "RESOLV_CONF=\"$dcvars->{RESOLV_CONF}\" ";
1393         $cmd .= "$samba_tool delegation for-any-protocol '$ret->{NETBIOSNAME}\$' on";
1394         $cmd .= " $dcvars->{CONFIGURATION}";
1395         print $cmd;
1396
1397         unless (system($cmd) == 0) {
1398                 warn("Delegation failed\n$cmd");
1399                 return undef;
1400         }
1401
1402         # Setting up delegation runs in the context of the DC for now
1403         $cmd = "";
1404         $cmd .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$dcvars->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
1405         $cmd .= "KRB5_CONFIG=\"$dcvars->{KRB5_CONFIG}\" ";
1406         $cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1407         $cmd .= "RESOLV_CONF=\"$dcvars->{RESOLV_CONF}\" ";
1408         $cmd .= "$samba_tool delegation add-service '$ret->{NETBIOSNAME}\$' cifs/$dcvars->{SERVER}";
1409         $cmd .= " $dcvars->{CONFIGURATION}";
1410
1411         unless (system($cmd) == 0) {
1412                 warn("Delegation failed\n$cmd");
1413                 return undef;
1414         }
1415
1416         $ret->{DOMSID} = $dcvars->{DOMSID};
1417         $self->set_pdc_env_vars($ret, $dcvars);
1418
1419         return $ret;
1420 }
1421
1422 sub provision_promoted_dc($$$)
1423 {
1424         my ($self, $prefix, $dcvars) = @_;
1425         print "PROVISIONING PROMOTED DC...\n";
1426
1427         # We do this so that we don't run the provision.  That's the job of 'samba-tool domain dcpromo'.
1428         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1429                                                "promotedvdc",
1430                                                $dcvars->{DOMAIN},
1431                                                $dcvars->{REALM},
1432                                                $dcvars->{SAMSID},
1433                                                "2008",
1434                                                $dcvars->{PASSWORD},
1435                                                $dcvars->{SERVER_IP},
1436                                                $dcvars->{SERVER_IPV6});
1437
1438         push (@{$ctx->{provision_options}}, "--use-ntvfs");
1439
1440         $ctx->{smb_conf_extra_options} = "
1441         max xmit = 32K
1442         server max protocol = SMB2
1443
1444         ntlm auth = ntlmv2-only
1445
1446 [sysvol]
1447         path = $ctx->{statedir}/sysvol
1448         read only = yes
1449
1450 [netlogon]
1451         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1452         read only = no
1453
1454 ";
1455
1456         my $ret = $self->provision_raw_step1($ctx);
1457         unless ($ret) {
1458                 return undef;
1459         }
1460
1461         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1462         my $cmd = $self->get_cmd_env_vars($ret);
1463         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} MEMBER --realm=$dcvars->{REALM}";
1464         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1465         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1466
1467         unless (system($cmd) == 0) {
1468                 warn("Join failed\n$cmd");
1469                 return undef;
1470         }
1471
1472         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1473         my $cmd = $self->get_cmd_env_vars($ret);
1474         $cmd .= "$samba_tool domain dcpromo $ret->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
1475         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1476         $cmd .= " --machinepass=machine$ret->{PASSWORD} --use-ntvfs --dns-backend=BIND9_DLZ";
1477
1478         unless (system($cmd) == 0) {
1479                 warn("Join failed\n$cmd");
1480                 return undef;
1481         }
1482
1483         $self->set_pdc_env_vars($ret, $dcvars);
1484
1485         return $ret;
1486 }
1487
1488 sub provision_vampire_dc($$$)
1489 {
1490         my ($self, $prefix, $dcvars, $fl) = @_;
1491         print "PROVISIONING VAMPIRE DC @ FL $fl...\n";
1492         my $name = "localvampiredc";
1493         my $extra_conf = "";
1494
1495         if ($fl == "2000") {
1496                 $name = "vampire2000dc";
1497         } else {
1498                 $extra_conf = "drs: immediate link sync = yes
1499                        drs: max link sync = 250";
1500         }
1501
1502         # We do this so that we don't run the provision.  That's the job of 'net vampire'.
1503         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1504                                                $name,
1505                                                $dcvars->{DOMAIN},
1506                                                $dcvars->{REALM},
1507                                                $dcvars->{DOMSID},
1508                                                $fl,
1509                                                $dcvars->{PASSWORD},
1510                                                $dcvars->{SERVER_IP},
1511                                                $dcvars->{SERVER_IPV6});
1512
1513         push (@{$ctx->{provision_options}}, "--use-ntvfs");
1514
1515         $ctx->{smb_conf_extra_options} = "
1516         max xmit = 32K
1517         server max protocol = SMB2
1518
1519         ntlm auth = mschapv2-and-ntlmv2-only
1520         $extra_conf
1521
1522 [sysvol]
1523         path = $ctx->{statedir}/sysvol
1524         read only = yes
1525
1526 [netlogon]
1527         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1528         read only = no
1529
1530 ";
1531
1532         my $ret = $self->provision_raw_step1($ctx);
1533         unless ($ret) {
1534                 return undef;
1535         }
1536
1537         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1538         my $cmd = $self->get_cmd_env_vars($ret);
1539         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
1540         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD} --domain-critical-only";
1541         $cmd .= " --machinepass=machine$ret->{PASSWORD} --use-ntvfs";
1542         $cmd .= " --backend-store=mdb";
1543
1544         unless (system($cmd) == 0) {
1545                 warn("Join failed\n$cmd");
1546                 return undef;
1547         }
1548
1549         $self->set_pdc_env_vars($ret, $dcvars);
1550         $ret->{DC_REALM} = $dcvars->{DC_REALM};
1551
1552         return $ret;
1553 }
1554
1555 sub provision_subdom_dc($$$)
1556 {
1557         my ($self, $prefix, $dcvars) = @_;
1558         print "PROVISIONING SUBDOMAIN DC...\n";
1559
1560         # We do this so that we don't run the provision.  That's the job of 'net vampire'.
1561         my $samsid = undef; # TODO pass the domain sid all the way down
1562         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1563                                                "localsubdc",
1564                                                "SAMBASUBDOM",
1565                                                "sub.samba.example.com",
1566                                                $samsid,
1567                                                "2008",
1568                                                $dcvars->{PASSWORD},
1569                                                undef);
1570
1571         push (@{$ctx->{provision_options}}, "--use-ntvfs");
1572
1573         $ctx->{smb_conf_extra_options} = "
1574         max xmit = 32K
1575         server max protocol = SMB2
1576
1577 [sysvol]
1578         path = $ctx->{statedir}/sysvol
1579         read only = yes
1580
1581 [netlogon]
1582         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1583         read only = no
1584
1585 ";
1586
1587         my $ret = $self->provision_raw_step1($ctx);
1588         unless ($ret) {
1589                 return undef;
1590         }
1591
1592         Samba::mk_krb5_conf($ctx);
1593         Samba::mk_mitkdc_conf($ctx, abs_path(Samba::bindir_path($self, "shared")));
1594
1595         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1596         my $cmd = $self->get_cmd_env_vars($ret);
1597         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $ctx->{dnsname} subdomain ";
1598         $cmd .= "--parent-domain=$dcvars->{REALM} -U$dcvars->{DC_USERNAME}\@$dcvars->{REALM}\%$dcvars->{DC_PASSWORD}";
1599         $cmd .= " --machinepass=machine$ret->{PASSWORD} --use-ntvfs";
1600         $cmd .= " --adminpass=$ret->{PASSWORD}";
1601
1602         unless (system($cmd) == 0) {
1603                 warn("Join failed\n$cmd");
1604                 return undef;
1605         }
1606
1607         $ret->{SUBDOM_DC_SERVER} = $ret->{SERVER};
1608
1609         $self->set_pdc_env_vars($ret, $dcvars);
1610
1611         return $ret;
1612 }
1613
1614 sub provision_ad_dc_ntvfs($$)
1615 {
1616         my ($self, $prefix) = @_;
1617
1618         # We keep the old 'winbind' name here in server services to
1619         # ensure upgrades which used that name still work with the now
1620         # alias.
1621
1622         print "PROVISIONING AD DC (NTVFS)...\n";
1623         my $extra_conf_options = "netbios aliases = localDC1-a
1624         server services = +winbind -winbindd
1625         ldap server require strong auth = allow_sasl_over_tls
1626         allow nt4 crypto = yes
1627         raw NTLMv2 auth = yes
1628         lsa over netlogon = yes
1629         rpc server port = 1027
1630         auth event notification = true
1631         dsdb event notification = true
1632         dsdb password event notification = true
1633         dsdb group change notification = true
1634         server schannel = auto
1635         ";
1636         my $extra_provision_options = ["--use-ntvfs"];
1637         my $ret = $self->provision($prefix,
1638                                    "domain controller",
1639                                    "localdc",
1640                                    "SAMBADOMAIN",
1641                                    "samba.example.com",
1642                                    "2008",
1643                                    "locDCpass1",
1644                                    undef,
1645                                    undef,
1646                                    $extra_conf_options,
1647                                    "",
1648                                    $extra_provision_options);
1649         unless ($ret) {
1650                 return undef;
1651         }
1652
1653         unless($self->add_wins_config("$prefix/private")) {
1654                 warn("Unable to add wins configuration");
1655                 return undef;
1656         }
1657         $ret->{NETBIOSALIAS} = "localdc1-a";
1658         $ret->{DC_REALM} = $ret->{REALM};
1659
1660         return $ret;
1661 }
1662
1663 sub provision_fl2000dc($$)
1664 {
1665         my ($self, $prefix) = @_;
1666
1667         print "PROVISIONING DC WITH FOREST LEVEL 2000...\n";
1668         my $extra_conf_options = "
1669         spnego:simulate_w2k=yes
1670         ntlmssp_server:force_old_spnego=yes
1671 ";
1672         my $extra_provision_options = ["--use-ntvfs"];
1673         # This environment uses plain text secrets
1674         # i.e. secret attributes are not encrypted on disk.
1675         # This allows testing of the --plaintext-secrets option for
1676         # provision
1677         push (@{$extra_provision_options}, "--plaintext-secrets");
1678         my $ret = $self->provision($prefix,
1679                                    "domain controller",
1680                                    "dc5",
1681                                    "SAMBA2000",
1682                                    "samba2000.example.com",
1683                                    "2000",
1684                                    "locDCpass5",
1685                                    undef,
1686                                    undef,
1687                                    $extra_conf_options,
1688                                    "",
1689                                    $extra_provision_options);
1690         unless ($ret) {
1691                 return undef;
1692         }
1693
1694         unless($self->add_wins_config("$prefix/private")) {
1695                 warn("Unable to add wins configuration");
1696                 return undef;
1697         }
1698         $ret->{DC_REALM} = $ret->{REALM};
1699
1700         return $ret;
1701 }
1702
1703 sub provision_fl2003dc($$$)
1704 {
1705         my ($self, $prefix, $dcvars) = @_;
1706         my $ip_addr1 = Samba::get_ipv4_addr("fakednsforwarder1");
1707         my $ip_addr2 = Samba::get_ipv4_addr("fakednsforwarder2");
1708
1709         print "PROVISIONING DC WITH FOREST LEVEL 2003...\n";
1710         my $extra_conf_options = "allow dns updates = nonsecure and secure
1711         dcesrv:header signing = no
1712         dcesrv:max auth states = 0
1713         dns forwarder = $ip_addr1 $ip_addr2";
1714         my $extra_provision_options = ["--use-ntvfs"];
1715         my $ret = $self->provision($prefix,
1716                                    "domain controller",
1717                                    "dc6",
1718                                    "SAMBA2003",
1719                                    "samba2003.example.com",
1720                                    "2003",
1721                                    "locDCpass6",
1722                                    undef,
1723                                    undef,
1724                                    $extra_conf_options,
1725                                    "",
1726                                    $extra_provision_options);
1727         unless (defined $ret) {
1728                 return undef;
1729         }
1730
1731         $ret->{DNS_FORWARDER1} = $ip_addr1;
1732         $ret->{DNS_FORWARDER2} = $ip_addr2;
1733
1734         my @samba_tool_options;
1735         push (@samba_tool_options, Samba::bindir_path($self, "samba-tool"));
1736         push (@samba_tool_options, "domain");
1737         push (@samba_tool_options, "passwordsettings");
1738         push (@samba_tool_options, "set");
1739         push (@samba_tool_options, "--configfile=$ret->{SERVERCONFFILE}");
1740         push (@samba_tool_options, "--min-pwd-age=0");
1741         push (@samba_tool_options, "--history-length=1");
1742
1743         my $samba_tool_cmd = join(" ", @samba_tool_options);
1744
1745         unless (system($samba_tool_cmd) == 0) {
1746                 warn("Unable to set min password age to 0: \n$samba_tool_cmd\n");
1747                 return undef;
1748         }
1749
1750         unless($self->add_wins_config("$prefix/private")) {
1751                 warn("Unable to add wins configuration");
1752                 return undef;
1753         }
1754
1755         return $ret;
1756 }
1757
1758 sub provision_fl2008r2dc($$$)
1759 {
1760         my ($self, $prefix, $dcvars) = @_;
1761
1762         print "PROVISIONING DC WITH FOREST LEVEL 2008r2...\n";
1763         my $extra_conf_options = "ldap server require strong auth = no";
1764         my $extra_provision_options = ["--use-ntvfs"];
1765         my $ret = $self->provision($prefix,
1766                                    "domain controller",
1767                                    "dc7",
1768                                    "SAMBA2008R2",
1769                                    "samba2008R2.example.com",
1770                                    "2008_R2",
1771                                    "locDCpass7",
1772                                    undef,
1773                                    undef,
1774                                    $extra_conf_options,
1775                                    "",
1776                                    $extra_provision_options);
1777         unless (defined $ret) {
1778                 return undef;
1779         }
1780
1781         unless ($self->add_wins_config("$prefix/private")) {
1782                 warn("Unable to add wins configuration");
1783                 return undef;
1784         }
1785         $ret->{DC_REALM} = $ret->{REALM};
1786
1787         return $ret;
1788 }
1789
1790
1791 sub provision_rodc($$$)
1792 {
1793         my ($self, $prefix, $dcvars) = @_;
1794         print "PROVISIONING RODC...\n";
1795
1796         # We do this so that we don't run the provision.  That's the job of 'net join RODC'.
1797         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1798                                                "rodc",
1799                                                $dcvars->{DOMAIN},
1800                                                $dcvars->{REALM},
1801                                                $dcvars->{DOMSID},
1802                                                "2008",
1803                                                $dcvars->{PASSWORD},
1804                                                $dcvars->{SERVER_IP},
1805                                                $dcvars->{SERVER_IPV6});
1806         unless ($ctx) {
1807                 return undef;
1808         }
1809
1810         push (@{$ctx->{provision_options}}, "--use-ntvfs");
1811
1812         $ctx->{share} = "$ctx->{prefix_abs}/share";
1813         push(@{$ctx->{directories}}, "$ctx->{share}");
1814
1815         $ctx->{smb_conf_extra_options} = "
1816         max xmit = 32K
1817         server max protocol = SMB2
1818         password server = $dcvars->{DC_SERVER}
1819
1820 [sysvol]
1821         path = $ctx->{statedir}/sysvol
1822         read only = yes
1823
1824 [netlogon]
1825         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1826         read only = yes
1827
1828 [tmp]
1829         path = $ctx->{share}
1830         read only = no
1831         posix:sharedelay = 10000
1832         posix:oplocktimeout = 3
1833         posix:writetimeupdatedelay = 50000
1834
1835 ";
1836
1837         my $ret = $self->provision_raw_step1($ctx);
1838         unless ($ret) {
1839                 return undef;
1840         }
1841
1842         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1843         my $cmd = $self->get_cmd_env_vars($ret);
1844         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} RODC";
1845         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1846         $cmd .= " --server=$dcvars->{DC_SERVER} --use-ntvfs";
1847
1848         unless (system($cmd) == 0) {
1849                 warn("RODC join failed\n$cmd");
1850                 return undef;
1851         }
1852
1853         # This ensures deterministic behaviour for tests that want to have the 'testallowed account'
1854         # user password verified on the RODC
1855         my $testallowed_account = "testallowed account";
1856         $cmd = "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1857         $cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1858         $cmd .= "RESOLV_CONF=\"$ret->{RESOLV_CONF}\" ";
1859         $cmd .= "$samba_tool rodc preload '$testallowed_account' $ret->{CONFIGURATION}";
1860         $cmd .= " --server=$dcvars->{DC_SERVER}";
1861
1862         unless (system($cmd) == 0) {
1863                 warn("RODC join failed\n$cmd");
1864                 return undef;
1865         }
1866
1867         # we overwrite the kdc after the RODC join
1868         # so that use the RODC as kdc and test
1869         # the proxy code
1870         $ctx->{kdc_ipv4} = $ret->{SERVER_IP};
1871         $ctx->{kdc_ipv6} = $ret->{SERVER_IPV6};
1872         Samba::mk_krb5_conf($ctx);
1873         Samba::mk_mitkdc_conf($ctx, abs_path(Samba::bindir_path($self, "shared")));
1874
1875         $self->set_pdc_env_vars($ret, $dcvars);
1876
1877         return $ret;
1878 }
1879
1880 sub read_config_h($)
1881 {
1882         my ($name) = @_;
1883         my %ret = {};
1884         open(LF, "<$name") or die("unable to read $name: $!");
1885         while (<LF>) {
1886                 chomp;
1887                 next if not (/^#define /);
1888                 if (/^#define (.*?)[ \t]+(.*?)$/) {
1889                         $ret{$1} = $2;
1890                         next;
1891                 }
1892                 if (/^#define (.*?)[ \t]+$/) {
1893                         $ret{$1} = 1;;
1894                         next;
1895                 }
1896         }
1897         close(LF);
1898         return \%ret;
1899 }
1900
1901 sub provision_ad_dc($$$$$$)
1902 {
1903         my ($self, $prefix, $hostname, $domain, $realm, $smbconf_args,
1904                 $extra_provision_options) = @_;
1905
1906         my $prefix_abs = abs_path($prefix);
1907
1908         my $bindir_abs = abs_path($self->{bindir});
1909         my $lockdir="$prefix_abs/lockdir";
1910         my $conffile="$prefix_abs/etc/smb.conf";
1911
1912         my $require_mutexes = "dbwrap_tdb_require_mutexes:* = yes";
1913         $require_mutexes = "" if ($ENV{SELFTEST_DONT_REQUIRE_TDB_MUTEX_SUPPORT} eq "1");
1914
1915         my $config_h = {};
1916
1917         if (defined($ENV{CONFIG_H})) {
1918                 $config_h = read_config_h($ENV{CONFIG_H});
1919         }
1920
1921         my $password_hash_gpg_key_ids = "password hash gpg key ids = 4952E40301FAB41A";
1922         $password_hash_gpg_key_ids = "" unless defined($config_h->{HAVE_GPGME});
1923
1924         my $extra_smbconf_options = "
1925         xattr_tdb:file = $prefix_abs/statedir/xattr.tdb
1926
1927         dbwrap_tdb_mutexes:* = yes
1928         ${require_mutexes}
1929
1930         ${password_hash_gpg_key_ids}
1931
1932         kernel oplocks = no
1933         kernel change notify = no
1934         smb2 leases = no
1935
1936         logging = file
1937         printing = bsd
1938         printcap name = /dev/null
1939
1940         max protocol = SMB3
1941         read only = no
1942
1943         smbd:sharedelay = 100000
1944         smbd:writetimeupdatedelay = 500000
1945         create mask = 755
1946         dos filemode = yes
1947         check parent directory delete on close = yes
1948
1949         dcerpc endpoint servers = -winreg -srvsvc
1950
1951         printcap name = /dev/null
1952
1953         addprinter command = $ENV{SRCDIR_ABS}/source3/script/tests/printing/modprinter.pl -a -s $conffile --
1954         deleteprinter command = $ENV{SRCDIR_ABS}/source3/script/tests/printing/modprinter.pl -d -s $conffile --
1955
1956         printing = vlp
1957         print command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb print %p %s
1958         lpq command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lpq %p
1959         lp rm command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lprm %p %j
1960         lp pause command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lppause %p %j
1961         lp resume command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lpresume %p %j
1962         queue pause command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb queuepause %p
1963         queue resume command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb queueresume %p
1964         lpq cache time = 0
1965         print notify backchannel = yes
1966
1967         server schannel = auto
1968         auth event notification = true
1969         dsdb event notification = true
1970         dsdb password event notification = true
1971         dsdb group change notification = true
1972         $smbconf_args
1973 ";
1974
1975         my $extra_smbconf_shares = "
1976
1977 [tmpenc]
1978         copy = tmp
1979         smb encrypt = required
1980
1981 [tmpcase]
1982         copy = tmp
1983         case sensitive = yes
1984
1985 [tmpguest]
1986         copy = tmp
1987         guest ok = yes
1988
1989 [hideunread]
1990         copy = tmp
1991         hide unreadable = yes
1992
1993 [durable]
1994         copy = tmp
1995         kernel share modes = no
1996         kernel oplocks = no
1997         posix locking = no
1998
1999 [print\$]
2000         copy = tmp
2001
2002 [print1]
2003         copy = tmp
2004         printable = yes
2005
2006 [print2]
2007         copy = print1
2008 [print3]
2009         copy = print1
2010 [lp]
2011         copy = print1
2012 ";
2013
2014         push (@{$extra_provision_options}, "--backend-store=mdb");
2015         print "PROVISIONING AD DC...\n";
2016         my $ret = $self->provision($prefix,
2017                                    "domain controller",
2018                                    $hostname,
2019                                    $domain,
2020                                    $realm,
2021                                    "2008",
2022                                    "locDCpass1",
2023                                    undef,
2024                                    undef,
2025                                    $extra_smbconf_options,
2026                                    $extra_smbconf_shares,
2027                                    $extra_provision_options);
2028         unless (defined $ret) {
2029                 return undef;
2030         }
2031
2032         unless($self->add_wins_config("$prefix/private")) {
2033                 warn("Unable to add wins configuration");
2034                 return undef;
2035         }
2036
2037         return $ret;
2038 }
2039
2040 sub provision_chgdcpass($$)
2041 {
2042         my ($self, $prefix) = @_;
2043
2044         print "PROVISIONING CHGDCPASS...\n";
2045         # This environment disallows the use of this password
2046         # (and also removes the default AD complexity checks)
2047         my $unacceptable_password = "widk3Dsle32jxdBdskldsk55klASKQ";
2048         my $extra_smb_conf = "
2049         check password script = $self->{srcdir}/selftest/checkpassword_arg1.sh ${unacceptable_password}
2050         allow dcerpc auth level connect:lsarpc = yes
2051         dcesrv:max auth states = 8
2052 ";
2053         my $extra_provision_options = ["--use-ntvfs"];
2054         push (@{$extra_provision_options}, "--dns-backend=BIND9_DLZ");
2055         my $ret = $self->provision($prefix,
2056                                    "domain controller",
2057                                    "chgdcpass",
2058                                    "CHDCDOMAIN",
2059                                    "chgdcpassword.samba.example.com",
2060                                    "2008",
2061                                    "chgDCpass1",
2062                                    undef,
2063                                    undef,
2064                                    $extra_smb_conf,
2065                                    "",
2066                                    $extra_provision_options);
2067         unless (defined $ret) {
2068                 return undef;
2069         }
2070
2071         unless($self->add_wins_config("$prefix/private")) {
2072                 warn("Unable to add wins configuration");
2073                 return undef;
2074         }
2075         
2076         # Remove secrets.tdb from this environment to test that we
2077         # still start up on systems without the new matching
2078         # secrets.tdb records.
2079         unless (unlink("$ret->{PRIVATEDIR}/secrets.tdb") || unlink("$ret->{PRIVATEDIR}/secrets.ntdb")) {
2080                 warn("Unable to remove $ret->{PRIVATEDIR}/secrets.tdb added during provision");
2081                 return undef;
2082         }
2083
2084         $ret->{UNACCEPTABLE_PASSWORD} = $unacceptable_password;
2085
2086         return $ret;
2087 }
2088
2089 sub teardown_env_terminate($$)
2090 {
2091         my ($self, $envvars) = @_;
2092         my $pid;
2093
2094         # This should cause samba to terminate gracefully
2095         my $smbcontrol = Samba::bindir_path($self, "smbcontrol");
2096         my $cmd = "";
2097         $cmd .= "$smbcontrol samba shutdown $envvars->{CONFIGURATION}";
2098         my $ret = system($cmd);
2099         if ($ret != 0) {
2100                 warn "'$cmd' failed with '$ret'\n";
2101         }
2102
2103         # This should cause samba to terminate gracefully
2104         close($envvars->{STDIN_PIPE});
2105
2106         $pid = $envvars->{SAMBA_PID};
2107         my $count = 0;
2108         my $childpid;
2109
2110         # This should give it time to write out the gcov data
2111         until ($count > 15) {
2112             if (Samba::cleanup_child($pid, "samba") != 0) {
2113                 return;
2114             }
2115             sleep(1);
2116             $count++;
2117         }
2118
2119         # After 15 Seconds, work out why this thing is still alive
2120         warn "server process $pid took more than $count seconds to exit, showing backtrace:\n";
2121         system("$self->{srcdir}/selftest/gdb_backtrace $pid");
2122
2123         until ($count > 30) {
2124             if (Samba::cleanup_child($pid, "samba") != 0) {
2125                 return;
2126             }
2127             sleep(1);
2128             $count++;
2129         }
2130
2131         if (kill(0, $pid)) {
2132             warn "server process $pid took more than $count seconds to exit, sending SIGTERM\n";
2133             kill "TERM", $pid;
2134         }
2135
2136         until ($count > 40) {
2137             if (Samba::cleanup_child($pid, "samba") != 0) {
2138                 return;
2139             }
2140             sleep(1);
2141             $count++;
2142         }
2143         # If it is still around, kill it
2144         if (kill(0, $pid)) {
2145             warn "server process $pid took more than $count seconds to exit, killing\n with SIGKILL\n";
2146             kill 9, $pid;
2147         }
2148         return;
2149 }
2150
2151 sub teardown_env($$)
2152 {
2153         my ($self, $envvars) = @_;
2154         teardown_env_terminate($self, $envvars);
2155
2156         $self->slapd_stop($envvars) if ($self->{ldap});
2157
2158         print $self->getlog_env($envvars);
2159
2160         return;
2161 }
2162
2163 sub getlog_env($$)
2164 {
2165         my ($self, $envvars) = @_;
2166         my $title = "SAMBA LOG of: $envvars->{NETBIOSNAME} pid $envvars->{SAMBA_PID}\n";
2167         my $out = $title;
2168
2169         open(LOG, "<$envvars->{SAMBA_TEST_LOG}");
2170
2171         seek(LOG, $envvars->{SAMBA_TEST_LOG_POS}, SEEK_SET);
2172         while (<LOG>) {
2173                 $out .= $_;
2174         }
2175         $envvars->{SAMBA_TEST_LOG_POS} = tell(LOG);
2176         close(LOG);
2177
2178         return "" if $out eq $title;
2179
2180         return $out;
2181 }
2182
2183 sub check_env($$)
2184 {
2185         my ($self, $envvars) = @_;
2186         my $samba_pid = $envvars->{SAMBA_PID};
2187
2188         if (not defined($samba_pid)) {
2189             return 0;
2190         } elsif ($samba_pid > 0) {
2191             my $childpid = Samba::cleanup_child($samba_pid, "samba");
2192
2193             if ($childpid == 0) {
2194                 return 1;
2195             }
2196             return 0;
2197         } else {
2198             return 1;
2199         }
2200 }
2201
2202 # Declare the environments Samba4 makes available.
2203 # To be set up, they will be called as
2204 #   samba4->setup_$envname($self, $path, $dep_1_vars, $dep_2_vars, ...)
2205 # The interdependencies between the testenvs are declared below. Some testenvs
2206 # are dependent on another testenv running first, e.g. vampire_dc is dependent
2207 # on ad_dc_ntvfs because vampire_dc joins ad_dc_ntvfs's domain. All DCs are
2208 # dependent on dns_hub, which handles resolving DNS queries for the realm.
2209 %Samba4::ENV_DEPS = (
2210         # name               => [dep_1, dep_2, ...],
2211         dns_hub              => [],
2212         ad_dc_ntvfs          => ["dns_hub"],
2213         ad_dc                => ["dns_hub"],
2214         ad_dc_no_nss         => ["dns_hub"],
2215         ad_dc_no_ntlm        => ["dns_hub"],
2216
2217         fl2008r2dc           => ["ad_dc"],
2218         fl2003dc             => ["ad_dc"],
2219         fl2000dc             => ["dns_hub"],
2220
2221         vampire_2000_dc      => ["fl2000dc"],
2222         vampire_dc           => ["ad_dc_ntvfs"],
2223         promoted_dc          => ["ad_dc_ntvfs"],
2224         subdom_dc            => ["ad_dc_ntvfs"],
2225
2226         rodc                 => ["ad_dc_ntvfs"],
2227         rpc_proxy            => ["ad_dc_ntvfs"],
2228         chgdcpass            => ["dns_hub"],
2229
2230         s4member_dflt_domain => ["ad_dc_ntvfs"],
2231         s4member             => ["ad_dc_ntvfs"],
2232
2233         # envs that test the server process model
2234         proclimitdc          => ["dns_hub"],
2235         preforkrestartdc     => ["dns_hub"],
2236
2237         # backup/restore testenvs
2238         backupfromdc         => ["dns_hub"],
2239         customdc             => ["dns_hub"],
2240         restoredc            => ["backupfromdc"],
2241         renamedc             => ["backupfromdc"],
2242         offlinebackupdc      => ["backupfromdc"],
2243         labdc                => ["backupfromdc"],
2244
2245         # aliases in order to split autbuild tasks
2246         fl2008dc             => ["ad_dc_ntvfs"],
2247         ad_dc_default        => ["ad_dc_ntvfs"],
2248         ad_dc_slowtests      => ["ad_dc_ntvfs"],
2249         ad_dc_backup         => ["ad_dc"],
2250
2251         schema_dc      => ["dns_hub"],
2252         schema_pair_dc => ["schema_dc"],
2253
2254         none                 => [],
2255 );
2256
2257 %Samba4::ENV_DEPS_POST = (
2258         schema_dc => ["schema_pair_dc"],
2259 );
2260
2261 sub return_alias_env
2262 {
2263         my ($self, $path, $env) = @_;
2264
2265         # just an alias
2266         return $env;
2267 }
2268
2269 sub setup_fl2008dc
2270 {
2271         my ($self, $path, $dep_env) = @_;
2272         return $self->return_alias_env($path, $dep_env)
2273 }
2274
2275 sub setup_ad_dc_default
2276 {
2277         my ($self, $path, $dep_env) = @_;
2278         return $self->return_alias_env($path, $dep_env)
2279 }
2280
2281 sub setup_ad_dc_slowtests
2282 {
2283         my ($self, $path, $dep_env) = @_;
2284         return $self->return_alias_env($path, $dep_env)
2285 }
2286
2287 sub setup_ad_dc_backup
2288 {
2289         my ($self, $path, $dep_env) = @_;
2290         return $self->return_alias_env($path, $dep_env)
2291 }
2292
2293 sub setup_s4member
2294 {
2295         my ($self, $path, $dc_vars) = @_;
2296
2297         my $env = $self->provision_s4member($path, $dc_vars, "s4member");
2298
2299         if (defined $env) {
2300                 if (not defined($self->check_or_start($env, "standard"))) {
2301                         return undef;
2302                 }
2303         }
2304
2305         return $env;
2306 }
2307
2308 sub setup_s4member_dflt_domain
2309 {
2310         my ($self, $path, $dc_vars) = @_;
2311
2312         my $env = $self->provision_s4member($path, $dc_vars, "s4member_dflt",
2313                                             "winbind use default domain = yes");
2314
2315         if (defined $env) {
2316                 if (not defined($self->check_or_start($env, "standard"))) {
2317                         return undef;
2318                 }
2319         }
2320
2321         return $env;
2322 }
2323
2324 sub setup_rpc_proxy
2325 {
2326         my ($self, $path, $dc_vars) = @_;
2327
2328         my $env = $self->provision_rpc_proxy($path, $dc_vars);
2329
2330         if (defined $env) {
2331                 if (not defined($self->check_or_start($env, "standard"))) {
2332                         return undef;
2333                 }
2334         }
2335         return $env;
2336 }
2337
2338 sub setup_ad_dc_ntvfs
2339 {
2340         my ($self, $path) = @_;
2341
2342         my $env = $self->provision_ad_dc_ntvfs($path);
2343         if (defined $env) {
2344                 if (not defined($self->check_or_start($env, "standard"))) {
2345                     warn("Failed to start ad_dc_ntvfs");
2346                         return undef;
2347                 }
2348         }
2349         return $env;
2350 }
2351
2352 sub setup_chgdcpass
2353 {
2354         my ($self, $path) = @_;
2355
2356         my $env = $self->provision_chgdcpass($path);
2357         if (defined $env) {
2358                 if (not defined($self->check_or_start($env, "standard"))) {
2359                         return undef;
2360                 }
2361         }
2362         return $env;
2363 }
2364
2365 sub setup_fl2000dc
2366 {
2367         my ($self, $path) = @_;
2368
2369         my $env = $self->provision_fl2000dc($path);
2370         if (defined $env) {
2371                 if (not defined($self->check_or_start($env, "standard"))) {
2372                         return undef;
2373                 }
2374         }
2375
2376         return $env;
2377 }
2378
2379 sub setup_fl2003dc
2380 {
2381         my ($self, $path, $dc_vars) = @_;
2382
2383         my $env = $self->provision_fl2003dc($path);
2384
2385         if (defined $env) {
2386                 if (not defined($self->check_or_start($env, "standard"))) {
2387                         return undef;
2388                 }
2389
2390                 $env = $self->setup_trust($env, $dc_vars, "external", "--no-aes-keys");
2391         }
2392         return $env;
2393 }
2394
2395 sub setup_fl2008r2dc
2396 {
2397         my ($self, $path, $dc_vars) = @_;
2398
2399         my $env = $self->provision_fl2008r2dc($path);
2400
2401         if (defined $env) {
2402                 if (not defined($self->check_or_start($env, "standard"))) {
2403                         return undef;
2404                 }
2405
2406                 my $upn_array = ["$env->{REALM}.upn"];
2407                 my $spn_array = ["$env->{REALM}.spn"];
2408
2409                 $self->setup_namespaces($env, $upn_array, $spn_array);
2410
2411                 $env = $self->setup_trust($env, $dc_vars, "forest", "");
2412         }
2413
2414         return $env;
2415 }
2416
2417 sub setup_vampire_dc
2418 {
2419         return setup_generic_vampire_dc(@_, "2008");
2420 }
2421
2422 sub setup_vampire_2000_dc
2423 {
2424         return setup_generic_vampire_dc(@_, "2000");
2425 }
2426
2427 sub setup_generic_vampire_dc
2428 {
2429         my ($self, $path, $dc_vars, $fl) = @_;
2430
2431         my $env = $self->provision_vampire_dc($path, $dc_vars, $fl);
2432
2433         if (defined $env) {
2434                 if (not defined($self->check_or_start($env, "single"))) {
2435                         return undef;
2436                 }
2437
2438                 # force replicated DC to update repsTo/repsFrom
2439                 # for vampired partitions
2440                 my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2441
2442                 # as 'vampired' dc may add data in its local replica
2443                 # we need to synchronize data between DCs
2444                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2445                 my $cmd = $self->get_cmd_env_vars($env);
2446                 $cmd .= " $samba_tool drs replicate $env->{DC_SERVER} $env->{SERVER}";
2447                 $cmd .= " $dc_vars->{CONFIGURATION}";
2448                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2449                 # replicate Configuration NC
2450                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2451                 unless(system($cmd_repl) == 0) {
2452                         warn("Failed to replicate\n$cmd_repl");
2453                         return undef;
2454                 }
2455                 # replicate Default NC
2456                 $cmd_repl = "$cmd \"$base_dn\"";
2457                 unless(system($cmd_repl) == 0) {
2458                         warn("Failed to replicate\n$cmd_repl");
2459                         return undef;
2460                 }
2461
2462                 # Pull in a full set of changes from the main DC
2463                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2464                 $cmd = $self->get_cmd_env_vars($env);
2465                 $cmd .= " $samba_tool drs replicate $env->{SERVER} $env->{DC_SERVER}";
2466                 $cmd .= " $dc_vars->{CONFIGURATION}";
2467                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2468                 # replicate Configuration NC
2469                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2470                 unless(system($cmd_repl) == 0) {
2471                         warn("Failed to replicate\n$cmd_repl");
2472                         return undef;
2473                 }
2474                 # replicate Default NC
2475                 $cmd_repl = "$cmd \"$base_dn\"";
2476                 unless(system($cmd_repl) == 0) {
2477                         warn("Failed to replicate\n$cmd_repl");
2478                         return undef;
2479                 }
2480         }
2481
2482         return $env;
2483 }
2484
2485 sub setup_promoted_dc
2486 {
2487         my ($self, $path, $dc_vars) = @_;
2488
2489         my $env = $self->provision_promoted_dc($path, $dc_vars);
2490
2491         if (defined $env) {
2492                 if (not defined($self->check_or_start($env, "single"))) {
2493                         return undef;
2494                 }
2495
2496                 # force source and replicated DC to update repsTo/repsFrom
2497                 # for vampired partitions
2498                 my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2499                 my $cmd = "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2500                 # as 'vampired' dc may add data in its local replica
2501                 # we need to synchronize data between DCs
2502                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2503                 $cmd = "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\"";
2504                 $cmd .= " KRB5_CONFIG=\"$env->{KRB5_CONFIG}\"";
2505                 $cmd .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2506                 $cmd .= "RESOLV_CONF=\"$env->{RESOLV_CONF}\" ";
2507                 $cmd .= " $samba_tool drs replicate $env->{DC_SERVER} $env->{SERVER}";
2508                 $cmd .= " $dc_vars->{CONFIGURATION}";
2509                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2510                 # replicate Configuration NC
2511                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2512                 unless(system($cmd_repl) == 0) {
2513                         warn("Failed to replicate\n$cmd_repl");
2514                         return undef;
2515                 }
2516                 # replicate Default NC
2517                 $cmd_repl = "$cmd \"$base_dn\"";
2518                 unless(system($cmd_repl) == 0) {
2519                         warn("Failed to replicate\n$cmd_repl");
2520                         return undef;
2521                 }
2522         }
2523
2524         return $env;
2525 }
2526
2527 sub setup_subdom_dc
2528 {
2529         my ($self, $path, $dc_vars) = @_;
2530
2531         my $env = $self->provision_subdom_dc($path, $dc_vars);
2532
2533         if (defined $env) {
2534                 if (not defined($self->check_or_start($env, "single"))) {
2535                         return undef;
2536                 }
2537
2538                 # force replicated DC to update repsTo/repsFrom
2539                 # for primary domain partitions
2540                 my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2541                 my $cmd = "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2542                 # as 'subdomain' dc may add data in its local replica
2543                 # we need to synchronize data between DCs
2544                 my $base_dn = "DC=".join(",DC=", split(/\./, $env->{REALM}));
2545                 my $config_dn = "CN=Configuration,DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2546                 $cmd = "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\"";
2547                 $cmd .= " KRB5_CONFIG=\"$env->{KRB5_CONFIG}\"";
2548                 $cmd .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2549                 $cmd .= "RESOLV_CONF=\"$env->{RESOLV_CONF}\" ";
2550                 $cmd .= " $samba_tool drs replicate $env->{DC_SERVER} $env->{SUBDOM_DC_SERVER}";
2551                 $cmd .= " $dc_vars->{CONFIGURATION}";
2552                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD} --realm=$dc_vars->{DC_REALM}";
2553                 # replicate Configuration NC
2554                 my $cmd_repl = "$cmd \"$config_dn\"";
2555                 unless(system($cmd_repl) == 0) {
2556                         warn("Failed to replicate\n$cmd_repl");
2557                         return undef;
2558                 }
2559                 # replicate Default NC
2560                 $cmd_repl = "$cmd \"$base_dn\"";
2561                 unless(system($cmd_repl) == 0) {
2562                         warn("Failed to replicate\n$cmd_repl");
2563                         return undef;
2564                 }
2565         }
2566
2567         return $env;
2568 }
2569
2570 sub setup_rodc
2571 {
2572         my ($self, $path, $dc_vars) = @_;
2573
2574         my $env = $self->provision_rodc($path, $dc_vars);
2575
2576         unless ($env) {
2577                 return undef;
2578         }
2579
2580         if (not defined($self->check_or_start($env, "standard"))) {
2581             return undef;
2582         }
2583
2584         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2585         my $cmd = "";
2586
2587         my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2588         $cmd .= "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2589         $cmd .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\"";
2590         $cmd .= " KRB5_CONFIG=\"$env->{KRB5_CONFIG}\"";
2591         $cmd .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2592         $cmd .= "RESOLV_CONF=\"$env->{RESOLV_CONF}\" ";
2593         $cmd .= " $samba_tool drs replicate $env->{SERVER} $env->{DC_SERVER}";
2594         $cmd .= " $dc_vars->{CONFIGURATION}";
2595         $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2596         # replicate Configuration NC
2597         my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2598         unless(system($cmd_repl) == 0) {
2599             warn("Failed to replicate\n$cmd_repl");
2600             return undef;
2601         }
2602         # replicate Default NC
2603         $cmd_repl = "$cmd \"$base_dn\"";
2604         unless(system($cmd_repl) == 0) {
2605             warn("Failed to replicate\n$cmd_repl");
2606             return undef;
2607         }
2608
2609         return $env;
2610 }
2611
2612 sub setup_ad_dc
2613 {
2614         my ($self, $path) = @_;
2615
2616         # If we didn't build with ADS, pretend this env was never available
2617         if (not $self->{target3}->have_ads()) {
2618                return "UNKNOWN";
2619         }
2620
2621         my $env = $self->provision_ad_dc($path, "addc", "ADDOMAIN",
2622                                          "addom.samba.example.com", "", undef);
2623         unless ($env) {
2624                 return undef;
2625         }
2626
2627         if (not defined($self->check_or_start($env, "prefork"))) {
2628             return undef;
2629         }
2630
2631         my $upn_array = ["$env->{REALM}.upn"];
2632         my $spn_array = ["$env->{REALM}.spn"];
2633
2634         $self->setup_namespaces($env, $upn_array, $spn_array);
2635
2636         return $env;
2637 }
2638
2639 sub setup_ad_dc_no_nss
2640 {
2641         my ($self, $path) = @_;
2642
2643         # If we didn't build with ADS, pretend this env was never available
2644         if (not $self->{target3}->have_ads()) {
2645                return "UNKNOWN";
2646         }
2647
2648         my $env = $self->provision_ad_dc($path, "addc_no_nss", "ADNONSSDOMAIN",
2649                                          "adnonssdom.samba.example.com", "", undef);
2650         unless ($env) {
2651                 return undef;
2652         }
2653
2654         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2655         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2656
2657         if (not defined($self->check_or_start($env, "single"))) {
2658             return undef;
2659         }
2660
2661         my $upn_array = ["$env->{REALM}.upn"];
2662         my $spn_array = ["$env->{REALM}.spn"];
2663
2664         $self->setup_namespaces($env, $upn_array, $spn_array);
2665
2666         return $env;
2667 }
2668
2669 sub setup_ad_dc_no_ntlm
2670 {
2671         my ($self, $path) = @_;
2672
2673         # If we didn't build with ADS, pretend this env was never available
2674         if (not $self->{target3}->have_ads()) {
2675                return "UNKNOWN";
2676         }
2677
2678         my $env = $self->provision_ad_dc($path, "addc_no_ntlm", "ADNONTLMDOMAIN",
2679                                          "adnontlmdom.samba.example.com",
2680                                          "ntlm auth = disabled", undef);
2681         unless ($env) {
2682                 return undef;
2683         }
2684
2685         if (not defined($self->check_or_start($env, "prefork"))) {
2686             return undef;
2687         }
2688
2689         my $upn_array = ["$env->{REALM}.upn"];
2690         my $spn_array = ["$env->{REALM}.spn"];
2691
2692         $self->setup_namespaces($env, $upn_array, $spn_array);
2693
2694         return $env;
2695 }
2696
2697 #
2698 # AD DC test environment used solely to test pre-fork process restarts.
2699 # As processes get killed off and restarted it should not be used for other
2700 sub setup_preforkrestartdc
2701 {
2702         my ($self, $path) = @_;
2703
2704         # If we didn't build with ADS, pretend this env was never available
2705         if (not $self->{target3}->have_ads()) {
2706                return "UNKNOWN";
2707         }
2708
2709         # note DC name must be <= 15 chars so we use 'prockill' instead of
2710         # 'preforkrestart'
2711         my $env = $self->provision_ad_dc(
2712                 $path,
2713                 "prockilldc",
2714                 "PROCKILLDOMAIN",
2715                 "prockilldom.samba.example.com",
2716                 "prefork backoff increment = 5\nprefork maximum backoff=10");
2717         unless ($env) {
2718                 return undef;
2719         }
2720
2721         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2722         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2723
2724         if (not defined($self->check_or_start($env, "prefork"))) {
2725             return undef;
2726         }
2727
2728         my $upn_array = ["$env->{REALM}.upn"];
2729         my $spn_array = ["$env->{REALM}.spn"];
2730
2731         $self->setup_namespaces($env, $upn_array, $spn_array);
2732
2733         return $env;
2734 }
2735
2736 #
2737 # ad_dc test environment used solely to test standard process model connection
2738 # process limits. As the limit is set artificially low it should not be used
2739 # for other tests.
2740 sub setup_proclimitdc
2741 {
2742         my ($self, $path) = @_;
2743
2744         # If we didn't build with ADS, pretend this env was never available
2745         if (not $self->{target3}->have_ads()) {
2746                return "UNKNOWN";
2747         }
2748
2749         my $env = $self->provision_ad_dc(
2750                 $path,
2751                 "proclimitdc",
2752                 "PROCLIMITDOM",
2753                 "proclimit.samba.example.com",
2754                 "max smbd processes = 20");
2755         unless ($env) {
2756                 return undef;
2757         }
2758
2759         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2760         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2761
2762         if (not defined($self->check_or_start($env, "standard"))) {
2763             return undef;
2764         }
2765
2766         my $upn_array = ["$env->{REALM}.upn"];
2767         my $spn_array = ["$env->{REALM}.spn"];
2768
2769         $self->setup_namespaces($env, $upn_array, $spn_array);
2770
2771         return $env;
2772 }
2773
2774 # Used to test a live upgrade of the schema on a 2 DC network.
2775 sub setup_schema_dc
2776 {
2777         my ($self, $path) = @_;
2778
2779         # provision the PDC using an older base schema
2780         my $provision_args = ["--base-schema=2008_R2", "--backend-store=mdb"];
2781
2782         my $env = $self->provision_ad_dc($path, "liveupgrade1dc", "SCHEMADOMAIN",
2783                                          "schema.samba.example.com",
2784                                          "drs: max link sync = 2",
2785                                          $provision_args);
2786         unless ($env) {
2787                 return undef;
2788         }
2789
2790         if (not defined($self->check_or_start($env, "prefork"))) {
2791             return undef;
2792         }
2793
2794         my $upn_array = ["$env->{REALM}.upn"];
2795         my $spn_array = ["$env->{REALM}.spn"];
2796
2797         $self->setup_namespaces($env, $upn_array, $spn_array);
2798
2799         return $env;
2800 }
2801
2802 # the second DC in the live schema upgrade pair
2803 sub setup_schema_pair_dc
2804 {
2805         # note: dcvars contains the env info for the dependent testenv ('schema_dc')
2806         my ($self, $prefix, $dcvars) = @_;
2807         print "Preparing SCHEMA UPGRADE PAIR DC...\n";
2808
2809         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "liveupgrade2dc",
2810                                                     $dcvars->{DOMAIN},
2811                                                     $dcvars->{REALM},
2812                                                     $dcvars->{PASSWORD},
2813                                                     "");
2814
2815         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2816         my $cmd_vars = "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2817         $cmd_vars .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
2818         if (defined($env->{RESOLV_WRAPPER_CONF})) {
2819                 $cmd_vars .= "RESOLV_WRAPPER_CONF=\"$env->{RESOLV_WRAPPER_CONF}\" ";
2820         } else {
2821                 $cmd_vars .= "RESOLV_WRAPPER_HOSTS=\"$env->{RESOLV_WRAPPER_HOSTS}\" ";
2822         }
2823         $cmd_vars .= "KRB5_CONFIG=\"$env->{KRB5_CONFIG}\" ";
2824         $cmd_vars .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2825         $cmd_vars .= "RESOLV_CONF=\"$env->{RESOLV_CONF}\" ";
2826
2827         my $join_cmd = $cmd_vars;
2828         $join_cmd .= "$samba_tool domain join $env->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
2829         $join_cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD} ";
2830         $join_cmd .= " --backend-store=mdb";
2831
2832         my $upgrade_cmd = $cmd_vars;
2833         $upgrade_cmd .= "$samba_tool domain schemaupgrade $dcvars->{CONFIGURATION}";
2834         $upgrade_cmd .= " -U$dcvars->{USERNAME}\%$dcvars->{PASSWORD}";
2835
2836         my $repl_cmd = $cmd_vars;
2837         $repl_cmd .= "$samba_tool drs replicate $env->{SERVER} $dcvars->{SERVER}";
2838         $repl_cmd .= " CN=Schema,CN=Configuration,DC=schema,DC=samba,DC=example,DC=com";
2839         $repl_cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
2840
2841         unless (system($join_cmd) == 0) {
2842                 warn("Join failed\n$join_cmd");
2843                 return undef;
2844         }
2845
2846         $env->{DC_SERVER} = $dcvars->{SERVER};
2847         $env->{DC_SERVER_IP} = $dcvars->{SERVER_IP};
2848         $env->{DC_SERVER_IPV6} = $dcvars->{SERVER_IPV6};
2849         $env->{DC_NETBIOSNAME} = $dcvars->{NETBIOSNAME};
2850
2851         # start samba for the new DC
2852         if (not defined($self->check_or_start($env, "standard"))) {
2853             return undef;
2854         }
2855
2856         unless (system($upgrade_cmd) == 0) {
2857                 warn("Schema upgrade failed\n$upgrade_cmd");
2858                 return undef;
2859         }
2860
2861         unless (system($repl_cmd) == 0) {
2862                 warn("Post-update schema replication failed\n$repl_cmd");
2863                 return undef;
2864         }
2865
2866         return $env;
2867 }
2868
2869 # Sets up a DC that's solely used to do a domain backup from. We then use the
2870 # backupfrom-DC to create the restore-DC - this proves that the backup/restore
2871 # process will create a Samba DC that will actually start up.
2872 # We don't use the backup-DC for anything else because its domain will conflict
2873 # with the restore DC.
2874 sub setup_backupfromdc
2875 {
2876         my ($self, $path) = @_;
2877
2878         # If we didn't build with ADS, pretend this env was never available
2879         if (not $self->{target3}->have_ads()) {
2880                return "UNKNOWN";
2881         }
2882
2883         my $provision_args = ["--site=Backup-Site"];
2884
2885         my $env = $self->provision_ad_dc($path, "backupfromdc", "BACKUPDOMAIN",
2886                                          "backupdom.samba.example.com",
2887                                          "samba kcc command = /bin/true",
2888                                          $provision_args);
2889         unless ($env) {
2890                 return undef;
2891         }
2892
2893         if (not defined($self->check_or_start($env))) {
2894             return undef;
2895         }
2896
2897         my $upn_array = ["$env->{REALM}.upn"];
2898         my $spn_array = ["$env->{REALM}.spn"];
2899
2900         $self->setup_namespaces($env, $upn_array, $spn_array);
2901
2902         return $env;
2903 }
2904
2905 # returns the server/user-auth params needed to run an online backup cmd
2906 sub get_backup_server_args
2907 {
2908         # dcvars contains the env info for the backup DC testenv
2909         my ($self, $dcvars) = @_;
2910         my $server = $dcvars->{DC_SERVER_IP};
2911         my $server_args = "--server=$server ";
2912         $server_args .= "-U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
2913         $server_args .= " $dcvars->{CONFIGURATION}";
2914
2915         return $server_args;
2916 }
2917
2918 # Creates a backup of a running testenv DC
2919 sub create_backup
2920 {
2921         # note: dcvars contains the env info for the backup DC testenv
2922         my ($self, $env, $dcvars, $backupdir, $backup_cmd) = @_;
2923
2924         # get all the env variables we pass in with the samba-tool command
2925         my $cmd_env = "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2926         $cmd_env .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
2927         if (defined($env->{RESOLV_WRAPPER_CONF})) {
2928                 $cmd_env .= "RESOLV_WRAPPER_CONF=\"$env->{RESOLV_WRAPPER_CONF}\" ";
2929         } else {
2930                 $cmd_env .= "RESOLV_WRAPPER_HOSTS=\"$env->{RESOLV_WRAPPER_HOSTS}\" ";
2931         }
2932         # Note: use the backupfrom-DC's krb5.conf to do the backup
2933         $cmd_env .= " KRB5_CONFIG=\"$dcvars->{KRB5_CONFIG}\" ";
2934         $cmd_env .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2935
2936         # use samba-tool to create a backup from the 'backupfromdc' DC
2937         my $cmd = "";
2938         my $samba_tool = Samba::bindir_path($self, "samba-tool");
2939
2940         $cmd .= "$cmd_env $samba_tool domain backup $backup_cmd";
2941         $cmd .= " --targetdir=$backupdir";
2942
2943         print "Executing: $cmd\n";
2944         unless(system($cmd) == 0) {
2945                 warn("Failed to create backup using: \n$cmd");
2946                 return undef;
2947         }
2948
2949         # get the name of the backup file created
2950         opendir(DIR, $backupdir);
2951         my @files = grep(/\.tar/, readdir(DIR));
2952         closedir(DIR);
2953
2954         if(scalar @files != 1) {
2955                 warn("Backup file not found in directory $backupdir\n");
2956                 return undef;
2957         }
2958         my $backup_file = "$backupdir/$files[0]";
2959         print "Using backup file $backup_file...\n";
2960
2961         return $backup_file;
2962 }
2963
2964 # Restores a backup-file to populate a testenv for a new DC
2965 sub restore_backup_file
2966 {
2967         my ($self, $backup_file, $restore_opts, $restoredir, $smbconf) = @_;
2968
2969         # pass the restore command the testenv's smb.conf that we've already
2970         # generated. But move it to a temp-dir first, so that the restore doesn't
2971         # overwrite it
2972         my $tmpdir = File::Temp->newdir();
2973         my $tmpconf = "$tmpdir/smb.conf";
2974         my $cmd = "cp $smbconf $tmpconf";
2975         unless(system($cmd) == 0) {
2976                 warn("Failed to backup smb.conf using: \n$cmd");
2977                 return -1;
2978         }
2979
2980         my $samba_tool = Samba::bindir_path($self, "samba-tool");
2981         $cmd = "$samba_tool domain backup restore --backup-file=$backup_file";
2982         $cmd .= " --targetdir=$restoredir $restore_opts --configfile=$tmpconf";
2983
2984         print "Executing: $cmd\n";
2985         unless(system($cmd) == 0) {
2986                 warn("Failed to restore backup using: \n$cmd");
2987                 return -1;
2988         }
2989
2990         print "Restore complete\n";
2991         return 0
2992 }
2993
2994 # sets up the initial directory and returns the new testenv's env info
2995 # (without actually doing a 'domain join')
2996 sub prepare_dc_testenv
2997 {
2998         my ($self, $prefix, $dcname, $domain, $realm,
2999                 $password, $conf_options) = @_;
3000
3001         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
3002                                                $dcname,
3003                                                $domain,
3004                                                $realm,
3005                                                undef,
3006                                                "2008",
3007                                                $password,
3008                                                undef,
3009                                                undef);
3010
3011         # the restore uses a slightly different state-dir location to other testenvs
3012         $ctx->{statedir} = "$ctx->{prefix_abs}/state";
3013         push(@{$ctx->{directories}}, "$ctx->{statedir}");
3014
3015         # add support for sysvol/netlogon/tmp shares
3016         $ctx->{share} = "$ctx->{prefix_abs}/share";
3017         push(@{$ctx->{directories}}, "$ctx->{share}");
3018         push(@{$ctx->{directories}}, "$ctx->{share}/test1");
3019
3020         $ctx->{smb_conf_extra_options} = "
3021         $conf_options
3022         max xmit = 32K
3023         server max protocol = SMB2
3024         samba kcc command = /bin/true
3025         xattr_tdb:file = $ctx->{statedir}/xattr.tdb
3026
3027 [sysvol]
3028         path = $ctx->{statedir}/sysvol
3029         read only = no
3030
3031 [netlogon]
3032         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
3033         read only = no
3034
3035 [tmp]
3036         path = $ctx->{share}
3037         read only = no
3038         posix:sharedelay = 10000
3039         posix:oplocktimeout = 3
3040         posix:writetimeupdatedelay = 50000
3041
3042 [test1]
3043         path = $ctx->{share}/test1
3044         read only = no
3045         posix:sharedelay = 100000
3046         posix:oplocktimeout = 3
3047         posix:writetimeupdatedelay = 500000
3048 ";
3049
3050         my $env = $self->provision_raw_step1($ctx);
3051
3052     return ($env, $ctx);
3053 }
3054
3055
3056 # Set up a DC testenv solely by using the samba-tool domain backup/restore
3057 # commands. This proves that we can backup an online DC ('backupfromdc') and
3058 # use the backup file to create a valid, working samba DC.
3059 sub setup_restoredc
3060 {
3061         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3062         my ($self, $prefix, $dcvars) = @_;
3063         print "Preparing RESTORE DC...\n";
3064
3065         # we arbitrarily designate the restored DC as having SMBv1 disabled
3066         my $extra_conf = "
3067         server min protocol = SMB2
3068         client min protocol = SMB2
3069         prefork children = 1";
3070
3071         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "restoredc",
3072                                                     $dcvars->{DOMAIN},
3073                                                     $dcvars->{REALM},
3074                                                     $dcvars->{PASSWORD},
3075                                                     $extra_conf);
3076
3077         # create a backup of the 'backupfromdc'
3078         my $backupdir = File::Temp->newdir();
3079         my $server_args = $self->get_backup_server_args($dcvars);
3080         my $backup_args = "online $server_args";
3081         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
3082                                                $backup_args);
3083         unless($backup_file) {
3084                 return undef;
3085         }
3086
3087         # restore the backup file to populate the restore-DC testenv
3088         my $restore_dir = abs_path($prefix);
3089         my $ret = $self->restore_backup_file($backup_file,
3090                                              "--newservername=$env->{SERVER}",
3091                                              $restore_dir, $env->{SERVERCONFFILE});
3092         unless ($ret == 0) {
3093                 return undef;
3094         }
3095
3096         # start samba for the restored DC
3097         if (not defined($self->check_or_start($env))) {
3098             return undef;
3099         }
3100
3101         return $env;
3102 }
3103
3104 # Set up a DC testenv solely by using the 'samba-tool domain backup rename' and
3105 # restore commands. This proves that we can backup and rename an online DC
3106 # ('backupfromdc') and use the backup file to create a valid, working samba DC.
3107 sub setup_renamedc
3108 {
3109         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3110         my ($self, $prefix, $dcvars) = @_;
3111         print "Preparing RENAME DC...\n";
3112         my $extra_conf = "prefork children = 1";
3113
3114         my $realm = "renamedom.samba.example.com";
3115         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "renamedc",
3116                                                     "RENAMEDOMAIN", $realm,
3117                                                     $dcvars->{PASSWORD}, $extra_conf);
3118
3119         # create a backup of the 'backupfromdc' which renames the domain
3120         my $backupdir = File::Temp->newdir();
3121         my $server_args = $self->get_backup_server_args($dcvars);
3122         my $backup_args = "rename $env->{DOMAIN} $env->{REALM} $server_args";
3123         $backup_args .= " --backend-store=tdb";
3124         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
3125                                                $backup_args);
3126         unless($backup_file) {
3127                 return undef;
3128         }
3129
3130         # restore the backup file to populate the rename-DC testenv
3131         my $restore_dir = abs_path($prefix);
3132         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
3133         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
3134                                              $restore_dir, $env->{SERVERCONFFILE});
3135         unless ($ret == 0) {
3136                 return undef;
3137         }
3138
3139         # start samba for the restored DC
3140         if (not defined($self->check_or_start($env))) {
3141             return undef;
3142         }
3143
3144         my $upn_array = ["$env->{REALM}.upn"];
3145         my $spn_array = ["$env->{REALM}.spn"];
3146
3147         $self->setup_namespaces($env, $upn_array, $spn_array);
3148
3149         return $env;
3150 }
3151
3152 # Set up a DC testenv solely by using the 'samba-tool domain backup offline' and
3153 # restore commands. This proves that we do an offline backup of a local DC
3154 # ('backupfromdc') and use the backup file to create a valid, working samba DC.
3155 sub setup_offlinebackupdc
3156 {
3157         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3158         my ($self, $prefix, $dcvars) = @_;
3159         print "Preparing OFFLINE BACKUP DC...\n";
3160         my $extra_conf = "prefork children = 1";
3161
3162         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "offlinebackupdc",
3163                                                     $dcvars->{DOMAIN},
3164                                                     $dcvars->{REALM},
3165                                                     $dcvars->{PASSWORD}, $extra_conf);
3166
3167         # create an offline backup of the 'backupfromdc' target
3168         my $backupdir = File::Temp->newdir();
3169         my $cmd = "offline -s $dcvars->{SERVERCONFFILE}";
3170         my $backup_file = $self->create_backup($env, $dcvars,
3171                                                $backupdir, $cmd);
3172
3173         unless($backup_file) {
3174                 return undef;
3175         }
3176
3177         # restore the backup file to populate the rename-DC testenv
3178         my $restore_dir = abs_path($prefix);
3179         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
3180         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
3181                                              $restore_dir, $env->{SERVERCONFFILE});
3182         unless ($ret == 0) {
3183                 return undef;
3184         }
3185
3186         # re-create the testenv's krb5.conf (the restore may have overwritten it)
3187         Samba::mk_krb5_conf($ctx);
3188
3189         # start samba for the restored DC
3190         if (not defined($self->check_or_start($env))) {
3191             return undef;
3192         }
3193
3194         return $env;
3195 }
3196
3197 # Set up a DC testenv solely by using the samba-tool 'domain backup rename' and
3198 # restore commands, using the --no-secrets option. This proves that we can
3199 # create a realistic lab environment from an online DC ('backupfromdc').
3200 sub setup_labdc
3201 {
3202         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3203         my ($self, $prefix, $dcvars) = @_;
3204         print "Preparing LAB-DOMAIN DC...\n";
3205         my $extra_conf = "prefork children = 1";
3206
3207         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "labdc",
3208                                                     "LABDOMAIN",
3209                                                     "labdom.samba.example.com",
3210                                                     $dcvars->{PASSWORD}, $extra_conf);
3211
3212         # create a backup of the 'backupfromdc' which renames the domain and uses
3213         # the --no-secrets option to scrub any sensitive info
3214         my $backupdir = File::Temp->newdir();
3215         my $server_args = $self->get_backup_server_args($dcvars);
3216         my $backup_args = "rename $env->{DOMAIN} $env->{REALM} $server_args";
3217         $backup_args .= " --no-secrets --backend-store=mdb";
3218         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
3219                                                $backup_args);
3220         unless($backup_file) {
3221                 return undef;
3222         }
3223
3224         # restore the backup file to populate the lab-DC testenv
3225         my $restore_dir = abs_path($prefix);
3226         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
3227         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
3228                                              $restore_dir, $env->{SERVERCONFFILE});
3229         unless ($ret == 0) {
3230                 return undef;
3231         }
3232
3233         # because we don't include any secrets in the backup, we need to reset the
3234         # admin user's password back to what the testenv expects
3235         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3236         my $cmd = "$samba_tool user setpassword $env->{USERNAME} ";
3237         $cmd .= "--newpassword=$env->{PASSWORD} -H $restore_dir/private/sam.ldb";
3238         $cmd .= " $env->{CONFIGURATION}";
3239
3240         unless(system($cmd) == 0) {
3241                 warn("Failed to reset admin's password: \n$cmd");
3242                 return undef;
3243         }
3244
3245         # start samba for the restored DC
3246         if (not defined($self->check_or_start($env))) {
3247             return undef;
3248         }
3249
3250         my $upn_array = ["$env->{REALM}.upn"];
3251         my $spn_array = ["$env->{REALM}.spn"];
3252
3253         $self->setup_namespaces($env, $upn_array, $spn_array);
3254
3255         return $env;
3256 }
3257
3258 # Inspects a backup *.tar.bz2 file and determines the realm/domain it contains
3259 sub get_backup_domain_realm
3260 {
3261         my ($self, $backup_file) = @_;
3262
3263         print "Determining REALM/DOMAIN values in backup...\n";
3264
3265         # The backup will have the correct domain/realm values in the smb.conf.
3266         # So we can work out the env variables the testenv should use based on
3267         # that. Let's start by extracting the smb.conf
3268         my $tar = Archive::Tar->new($backup_file);
3269         my $tmpdir = File::Temp->newdir();
3270         my $smbconf = "$tmpdir/smb.conf";
3271
3272         # note that the filepaths within the tar-file differ slightly for online
3273         # and offline backups
3274         if ($tar->contains_file("etc/smb.conf")) {
3275                 $tar->extract_file("etc/smb.conf", $smbconf);
3276         } elsif ($tar->contains_file("./etc/smb.conf")) {
3277                 $tar->extract_file("./etc/smb.conf", $smbconf);
3278         } else {
3279                 warn("Could not find smb.conf in $backup_file");
3280                 return undef, undef;
3281         }
3282
3283         # make sure we don't try to create locks/sockets in the default install
3284         # location (i.e. /usr/local/samba/)
3285         my $options = "--option=\"private dir = $tmpdir\"";
3286         $options .=  " --option=\"lock dir = $tmpdir\"";
3287
3288         # now use testparm to read the values we're interested in
3289         my $testparm = Samba::bindir_path($self, "testparm");
3290         my $domain = `$testparm $smbconf -sl --parameter-name=WORKGROUP $options`;
3291         my $realm = `$testparm $smbconf -sl --parameter-name=REALM $options`;
3292         chomp $realm;
3293         chomp $domain;
3294         print "Backup-file REALM is $realm, DOMAIN is $domain\n";
3295
3296         return ($domain, $realm);
3297 }
3298
3299 # This spins up a custom testenv that can be based on any backup-file you want.
3300 # This is just intended for manual testing (rather than automated test-cases)
3301 sub setup_customdc
3302 {
3303         my ($self, $prefix) = @_;
3304         print "Preparing CUSTOM RESTORE DC...\n";
3305         my $dc_name = "customdc";
3306         my $password = "locDCpass1";
3307         my $backup_file = $ENV{'BACKUP_FILE'};
3308
3309         # user must specify a backup file to restore via an ENV variable, i.e.
3310         # BACKUP_FILE=backup-blah.tar.bz2 SELFTEST_TESTENV=customdc make testenv
3311         if (not defined($backup_file)) {
3312                 warn("Please specify BACKUP_FILE");
3313                 return undef;
3314         }
3315
3316         # work out the correct domain/realm env values from the backup-file
3317         my ($domain, $realm) = $self->get_backup_domain_realm($backup_file);
3318         if ($domain eq '' or $realm eq '') {
3319                 warn("Could not determine domain or realm");
3320                 return undef;
3321         }
3322
3323         # create a placeholder directory and smb.conf, as well as the env vars.
3324         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, $dc_name,
3325                                                     $domain, $realm, $password, "");
3326
3327         # restore the specified backup file to populate the testenv
3328         my $restore_dir = abs_path($prefix);
3329         my $ret = $self->restore_backup_file($backup_file,
3330                                              "--newservername=$env->{SERVER}",
3331                                              $restore_dir, $env->{SERVERCONFFILE});
3332         unless ($ret == 0) {
3333                 return undef;
3334         }
3335
3336         # Change the admin password to the testenv default, just in case it's
3337         # different, or in case this was a --no-secrets backup
3338         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3339         my $cmd = "$samba_tool user setpassword $env->{USERNAME} ";
3340         $cmd .= "--newpassword=$password -H $restore_dir/private/sam.ldb";
3341         $cmd .= " $env->{CONFIGURATION}";
3342
3343         unless(system($cmd) == 0) {
3344                 warn("Failed to reset admin's password: \n$cmd");
3345                 return undef;
3346         }
3347
3348         # re-create the testenv's krb5.conf (the restore may have overwritten it,
3349         # if the backup-file was an offline backup)
3350         Samba::mk_krb5_conf($ctx);
3351
3352         # start samba for the restored DC
3353         if (not defined($self->check_or_start($env))) {
3354             return undef;
3355         }
3356
3357         # if this was a backup-rename, then we may need to setup namespaces
3358         my $upn_array = ["$env->{REALM}.upn"];
3359         my $spn_array = ["$env->{REALM}.spn"];
3360
3361         $self->setup_namespaces($env, $upn_array, $spn_array);
3362
3363         return $env;
3364 }
3365
3366 sub setup_none
3367 {
3368         my ($self, $path) = @_;
3369
3370         my $ret = {
3371                 KRB5_CONFIG => abs_path($path) . "/no_krb5.conf",
3372                 SAMBA_PID => -1,
3373         }
3374 }
3375
3376 1;