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