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