763140b486df12413390a0905039ef6de87b006d
[ira/wip.git] / source4 / scripting / python / samba / provision.py
1 #
2 # Unix SMB/CIFS implementation.
3 # backend code for provisioning a Samba4 server
4
5 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
6 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
7 #
8 # Based on the original in EJS:
9 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
10 #
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #   
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #   
21 # You should have received a copy of the GNU General Public License
22 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 #
24
25 """Functions for setting up a Samba configuration."""
26
27 from base64 import b64encode
28 import os
29 import pwd
30 import grp
31 import time
32 import uuid, glue
33 import socket
34 import param
35 import registry
36 import samba
37 from auth import system_session
38 from samba import Ldb, substitute_var, valid_netbios_name, check_all_substituted
39 from samba.samdb import SamDB
40 from samba.idmap import IDmapDB
41 from samba.dcerpc import security
42 import urllib
43 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError, \
44         timestring, CHANGETYPE_MODIFY, CHANGETYPE_NONE
45
46 __docformat__ = "restructuredText"
47
48 DEFAULTSITE = "Default-First-Site-Name"
49
50 class InvalidNetbiosName(Exception):
51     """A specified name was not a valid NetBIOS name."""
52     def __init__(self, name):
53         super(InvalidNetbiosName, self).__init__("The name '%r' is not a valid NetBIOS name" % name)
54
55
56 class ProvisionPaths(object):
57     def __init__(self):
58         self.shareconf = None
59         self.hklm = None
60         self.hkcu = None
61         self.hkcr = None
62         self.hku = None
63         self.hkpd = None
64         self.hkpt = None
65         self.samdb = None
66         self.idmapdb = None
67         self.secrets = None
68         self.keytab = None
69         self.dns_keytab = None
70         self.dns = None
71         self.winsdb = None
72         self.private_dir = None
73         self.ldapdir = None
74         self.slapdconf = None
75         self.modulesconf = None
76         self.memberofconf = None
77         self.fedoradsinf = None
78         self.fedoradspartitions = None
79         self.olmmron = None
80         self.olmmrserveridsconf = None
81         self.olmmrsyncreplconf = None
82
83
84 class ProvisionNames(object):
85     def __init__(self):
86         self.rootdn = None
87         self.domaindn = None
88         self.configdn = None
89         self.schemadn = None
90         self.ldapmanagerdn = None
91         self.dnsdomain = None
92         self.realm = None
93         self.netbiosname = None
94         self.domain = None
95         self.hostname = None
96         self.sitename = None
97         self.smbconf = None
98     
99
100 class ProvisionResult(object):
101     def __init__(self):
102         self.paths = None
103         self.domaindn = None
104         self.lp = None
105         self.samdb = None
106
107 def check_install(lp, session_info, credentials):
108     """Check whether the current install seems ok.
109     
110     :param lp: Loadparm context
111     :param session_info: Session information
112     :param credentials: Credentials
113     """
114     if lp.get("realm") == "":
115         raise Exception("Realm empty")
116     ldb = Ldb(lp.get("sam database"), session_info=session_info, 
117             credentials=credentials, lp=lp)
118     if len(ldb.search("(cn=Administrator)")) != 1:
119         raise "No administrator account found"
120
121
122 def findnss(nssfn, names):
123     """Find a user or group from a list of possibilities.
124     
125     :param nssfn: NSS Function to try (should raise KeyError if not found)
126     :param names: Names to check.
127     :return: Value return by first names list.
128     """
129     for name in names:
130         try:
131             return nssfn(name)
132         except KeyError:
133             pass
134     raise KeyError("Unable to find user/group %r" % names)
135
136
137 findnss_uid = lambda names: findnss(pwd.getpwnam, names)[2]
138 findnss_gid = lambda names: findnss(grp.getgrnam, names)[2]
139
140
141 def read_and_sub_file(file, subst_vars):
142     """Read a file and sub in variables found in it
143     
144     :param file: File to be read (typically from setup directory)
145      param subst_vars: Optional variables to subsitute in the file.
146     """
147     data = open(file, 'r').read()
148     if subst_vars is not None:
149         data = substitute_var(data, subst_vars)
150     check_all_substituted(data)
151     return data
152
153
154 def setup_add_ldif(ldb, ldif_path, subst_vars=None):
155     """Setup a ldb in the private dir.
156     
157     :param ldb: LDB file to import data into
158     :param ldif_path: Path of the LDIF file to load
159     :param subst_vars: Optional variables to subsitute in LDIF.
160     """
161     assert isinstance(ldif_path, str)
162
163     data = read_and_sub_file(ldif_path, subst_vars)
164     ldb.add_ldif(data)
165
166
167 def setup_modify_ldif(ldb, ldif_path, subst_vars=None):
168     """Modify a ldb in the private dir.
169     
170     :param ldb: LDB object.
171     :param ldif_path: LDIF file path.
172     :param subst_vars: Optional dictionary with substitution variables.
173     """
174     data = read_and_sub_file(ldif_path, subst_vars)
175
176     ldb.modify_ldif(data)
177
178
179 def setup_ldb(ldb, ldif_path, subst_vars):
180     """Import a LDIF a file into a LDB handle, optionally substituting variables.
181
182     :note: Either all LDIF data will be added or none (using transactions).
183
184     :param ldb: LDB file to import into.
185     :param ldif_path: Path to the LDIF file.
186     :param subst_vars: Dictionary with substitution variables.
187     """
188     assert ldb is not None
189     ldb.transaction_start()
190     try:
191         setup_add_ldif(ldb, ldif_path, subst_vars)
192     except:
193         ldb.transaction_cancel()
194         raise
195     ldb.transaction_commit()
196
197
198 def setup_file(template, fname, subst_vars):
199     """Setup a file in the private dir.
200
201     :param template: Path of the template file.
202     :param fname: Path of the file to create.
203     :param subst_vars: Substitution variables.
204     """
205     f = fname
206
207     if os.path.exists(f):
208         os.unlink(f)
209
210     data = read_and_sub_file(template, subst_vars)
211     open(f, 'w').write(data)
212
213
214 def provision_paths_from_lp(lp, dnsdomain):
215     """Set the default paths for provisioning.
216
217     :param lp: Loadparm context.
218     :param dnsdomain: DNS Domain name
219     """
220     paths = ProvisionPaths()
221     paths.private_dir = lp.get("private dir")
222     paths.keytab = "secrets.keytab"
223     paths.dns_keytab = "dns.keytab"
224
225     paths.shareconf = os.path.join(paths.private_dir, "share.ldb")
226     paths.samdb = os.path.join(paths.private_dir, lp.get("sam database") or "samdb.ldb")
227     paths.idmapdb = os.path.join(paths.private_dir, lp.get("idmap database") or "idmap.ldb")
228     paths.secrets = os.path.join(paths.private_dir, lp.get("secrets database") or "secrets.ldb")
229     paths.templates = os.path.join(paths.private_dir, "templates.ldb")
230     paths.dns = os.path.join(paths.private_dir, dnsdomain + ".zone")
231     paths.namedconf = os.path.join(paths.private_dir, "named.conf")
232     paths.namedtxt = os.path.join(paths.private_dir, "named.txt")
233     paths.krb5conf = os.path.join(paths.private_dir, "krb5.conf")
234     paths.winsdb = os.path.join(paths.private_dir, "wins.ldb")
235     paths.s4_ldapi_path = os.path.join(paths.private_dir, "ldapi")
236     paths.phpldapadminconfig = os.path.join(paths.private_dir, 
237                                             "phpldapadmin-config.php")
238     paths.ldapdir = os.path.join(paths.private_dir, 
239                                  "ldap")
240     paths.slapdconf = os.path.join(paths.ldapdir, 
241                                    "slapd.conf")
242     paths.modulesconf = os.path.join(paths.ldapdir, 
243                                      "modules.conf")
244     paths.memberofconf = os.path.join(paths.ldapdir, 
245                                       "memberof.conf")
246     paths.fedoradsinf = os.path.join(paths.ldapdir, 
247                                      "fedorads.inf")
248     paths.fedoradspartitions = os.path.join(paths.ldapdir, 
249                                             "fedorads-partitions.ldif")
250     paths.olmmrserveridsconf = os.path.join(paths.ldapdir, 
251                                             "mmr_serverids.conf")
252     paths.olmmrsyncreplconf = os.path.join(paths.ldapdir, 
253                                            "mmr_syncrepl.conf")
254     paths.hklm = "hklm.ldb"
255     paths.hkcr = "hkcr.ldb"
256     paths.hkcu = "hkcu.ldb"
257     paths.hku = "hku.ldb"
258     paths.hkpd = "hkpd.ldb"
259     paths.hkpt = "hkpt.ldb"
260
261     paths.sysvol = lp.get("path", "sysvol")
262
263     paths.netlogon = lp.get("path", "netlogon")
264
265     paths.smbconf = lp.configfile
266
267     return paths
268
269
270 def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None, serverrole=None,
271                 rootdn=None, domaindn=None, configdn=None, schemadn=None, serverdn=None, 
272                 sitename=None):
273     """Guess configuration settings to use."""
274
275     if hostname is None:
276         hostname = socket.gethostname().split(".")[0].lower()
277
278     netbiosname = hostname.upper()
279     if not valid_netbios_name(netbiosname):
280         raise InvalidNetbiosName(netbiosname)
281
282     hostname = hostname.lower()
283
284     if dnsdomain is None:
285         dnsdomain = lp.get("realm")
286
287     if serverrole is None:
288         serverrole = lp.get("server role")
289
290     assert dnsdomain is not None
291     realm = dnsdomain.upper()
292
293     if lp.get("realm").upper() != realm:
294         raise Exception("realm '%s' in %s must match chosen realm '%s'" %
295                         (lp.get("realm"), lp.configfile, realm))
296     
297     dnsdomain = dnsdomain.lower()
298
299     if serverrole == "domain controller":
300         if domain is None:
301             domain = lp.get("workgroup")
302         if domaindn is None:
303             domaindn = "DC=" + dnsdomain.replace(".", ",DC=")
304         if lp.get("workgroup").upper() != domain.upper():
305             raise Exception("workgroup '%s' in smb.conf must match chosen domain '%s'",
306                         lp.get("workgroup"), domain)
307     else:
308         domain = netbiosname
309         if domaindn is None:
310             domaindn = "CN=" + netbiosname
311         
312     assert domain is not None
313     domain = domain.upper()
314     if not valid_netbios_name(domain):
315         raise InvalidNetbiosName(domain)
316         
317     if rootdn is None:
318        rootdn = domaindn
319        
320     if configdn is None:
321         configdn = "CN=Configuration," + rootdn
322     if schemadn is None:
323         schemadn = "CN=Schema," + configdn
324
325     if sitename is None:
326         sitename=DEFAULTSITE
327
328     names = ProvisionNames()
329     names.rootdn = rootdn
330     names.domaindn = domaindn
331     names.configdn = configdn
332     names.schemadn = schemadn
333     names.ldapmanagerdn = "CN=Manager," + rootdn
334     names.dnsdomain = dnsdomain
335     names.domain = domain
336     names.realm = realm
337     names.netbiosname = netbiosname
338     names.hostname = hostname
339     names.sitename = sitename
340     names.serverdn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (netbiosname, sitename, configdn)
341  
342     return names
343     
344
345 def make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, 
346                  targetdir):
347     if hostname is None:
348         hostname = socket.gethostname().split(".")[0].lower()
349
350     if serverrole is None:
351         serverrole = "standalone"
352
353     assert serverrole in ("domain controller", "member server", "standalone")
354     if serverrole == "domain controller":
355         smbconfsuffix = "dc"
356     elif serverrole == "member server":
357         smbconfsuffix = "member"
358     elif serverrole == "standalone":
359         smbconfsuffix = "standalone"
360
361     assert domain is not None
362     assert realm is not None
363
364     default_lp = param.LoadParm()
365     #Load non-existant file
366     if os.path.exists(smbconf):
367         default_lp.load(smbconf)
368     
369     if targetdir is not None:
370         privatedir_line = "private dir = " + os.path.abspath(os.path.join(targetdir, "private"))
371         lockdir_line = "lock dir = " + os.path.abspath(targetdir)
372
373         default_lp.set("lock dir", os.path.abspath(targetdir))
374     else:
375         privatedir_line = ""
376         lockdir_line = ""
377
378     sysvol = os.path.join(default_lp.get("lock dir"), "sysvol")
379     netlogon = os.path.join(sysvol, realm.lower(), "scripts")
380
381     setup_file(setup_path("provision.smb.conf.%s" % smbconfsuffix), 
382                smbconf, {
383             "HOSTNAME": hostname,
384             "DOMAIN": domain,
385             "REALM": realm,
386             "SERVERROLE": serverrole,
387             "NETLOGONPATH": netlogon,
388             "SYSVOLPATH": sysvol,
389             "PRIVATEDIR_LINE": privatedir_line,
390             "LOCKDIR_LINE": lockdir_line
391             })
392
393
394
395 def setup_name_mappings(samdb, idmap, sid, domaindn, root_uid, nobody_uid,
396                         users_gid, wheel_gid):
397     """setup reasonable name mappings for sam names to unix names.
398
399     :param samdb: SamDB object.
400     :param idmap: IDmap db object.
401     :param sid: The domain sid.
402     :param domaindn: The domain DN.
403     :param root_uid: uid of the UNIX root user.
404     :param nobody_uid: uid of the UNIX nobody user.
405     :param users_gid: gid of the UNIX users group.
406     :param wheel_gid: gid of the UNIX wheel group."""
407     # add some foreign sids if they are not present already
408     samdb.add_foreign(domaindn, "S-1-5-7", "Anonymous")
409     samdb.add_foreign(domaindn, "S-1-1-0", "World")
410     samdb.add_foreign(domaindn, "S-1-5-2", "Network")
411     samdb.add_foreign(domaindn, "S-1-5-18", "System")
412     samdb.add_foreign(domaindn, "S-1-5-11", "Authenticated Users")
413
414     idmap.setup_name_mapping("S-1-5-7", idmap.TYPE_UID, nobody_uid)
415     idmap.setup_name_mapping("S-1-5-32-544", idmap.TYPE_GID, wheel_gid)
416
417     idmap.setup_name_mapping(sid + "-500", idmap.TYPE_UID, root_uid)
418     idmap.setup_name_mapping(sid + "-513", idmap.TYPE_GID, users_gid)
419
420
421 def setup_samdb_partitions(samdb_path, setup_path, message, lp, session_info, 
422                            credentials, names,
423                            serverrole, ldap_backend=None, 
424                            ldap_backend_type=None, erase=False):
425     """Setup the partitions for the SAM database. 
426     
427     Alternatively, provision() may call this, and then populate the database.
428     
429     :note: This will wipe the Sam Database!
430     
431     :note: This function always removes the local SAM LDB file. The erase 
432         parameter controls whether to erase the existing data, which 
433         may not be stored locally but in LDAP.
434     """
435     assert session_info is not None
436
437     try:
438         samdb = SamDB(samdb_path, session_info=session_info, 
439                       credentials=credentials, lp=lp)
440         # Wipes the database
441         samdb.erase()
442     except:
443         os.unlink(samdb_path)
444         samdb = SamDB(samdb_path, session_info=session_info, 
445                       credentials=credentials, lp=lp)
446          # Wipes the database
447         samdb.erase()
448         
449
450     #Add modules to the list to activate them by default
451     #beware often order is important
452     #
453     # Some Known ordering constraints:
454     # - rootdse must be first, as it makes redirects from "" -> cn=rootdse
455     # - objectclass must be before password_hash, because password_hash checks
456     #   that the objectclass is of type person (filled in by objectclass
457     #   module when expanding the objectclass list)
458     # - partition must be last
459     # - each partition has its own module list then
460     modules_list = ["rootdse",
461                     "paged_results",
462                     "ranged_results",
463                     "anr",
464                     "server_sort",
465                     "asq",
466                     "extended_dn_store",
467                     "extended_dn_in",
468                     "rdn_name",
469                     "objectclass",
470                     "samldb",
471                     "kludge_acl",
472                     "password_hash",
473                     "operational"]
474     tdb_modules_list = [
475                     "subtree_rename",
476                     "subtree_delete",
477                     "linked_attributes",
478                     "extended_dn_out_ldb"]
479     modules_list2 = ["show_deleted",
480                     "partition"]
481  
482     domaindn_ldb = "users.ldb"
483     if ldap_backend is not None:
484         domaindn_ldb = ldap_backend
485     configdn_ldb = "configuration.ldb"
486     if ldap_backend is not None:
487         configdn_ldb = ldap_backend
488     schemadn_ldb = "schema.ldb"
489     if ldap_backend is not None:
490         schema_ldb = ldap_backend
491         schemadn_ldb = ldap_backend
492         
493     if ldap_backend_type == "fedora-ds":
494         backend_modules = ["nsuniqueid", "paged_searches"]
495         # We can handle linked attributes here, as we don't have directory-side subtree operations
496         tdb_modules_list = ["linked_attributes", "extended_dn_out_dereference"]
497     elif ldap_backend_type == "openldap":
498         backend_modules = ["entryuuid", "paged_searches"]
499         # OpenLDAP handles subtree renames, so we don't want to do any of these things
500         tdb_modules_list = ["extended_dn_out_dereference"]
501     elif ldap_backend is not None:
502         raise "LDAP Backend specified, but LDAP Backend Type not specified"
503     elif serverrole == "domain controller":
504         backend_modules = ["repl_meta_data"]
505     else:
506         backend_modules = ["objectguid"]
507
508     if tdb_modules_list is None:
509         tdb_modules_list_as_string = ""
510     else:
511         tdb_modules_list_as_string = ","+",".join(tdb_modules_list)
512         
513     samdb.transaction_start()
514     try:
515         setup_add_ldif(samdb, setup_path("provision_partitions.ldif"), {
516                 "SCHEMADN": names.schemadn, 
517                 "SCHEMADN_LDB": schemadn_ldb,
518                 "SCHEMADN_MOD2": ",objectguid",
519                 "CONFIGDN": names.configdn,
520                 "CONFIGDN_LDB": configdn_ldb,
521                 "DOMAINDN": names.domaindn,
522                 "DOMAINDN_LDB": domaindn_ldb,
523                 "SCHEMADN_MOD": "schema_fsmo,instancetype",
524                 "CONFIGDN_MOD": "naming_fsmo,instancetype",
525                 "DOMAINDN_MOD": "pdc_fsmo,instancetype",
526                 "MODULES_LIST": ",".join(modules_list),
527                 "TDB_MODULES_LIST": tdb_modules_list_as_string,
528                 "MODULES_LIST2": ",".join(modules_list2),
529                 "BACKEND_MOD": ",".join(backend_modules),
530         })
531
532     except:
533         samdb.transaction_cancel()
534         raise
535
536     samdb.transaction_commit()
537     
538     samdb = SamDB(samdb_path, session_info=session_info, 
539                   credentials=credentials, lp=lp)
540
541     samdb.transaction_start()
542     try:
543         message("Setting up sam.ldb attributes")
544         samdb.load_ldif_file_add(setup_path("provision_init.ldif"))
545
546         message("Setting up sam.ldb rootDSE")
547         setup_samdb_rootdse(samdb, setup_path, names)
548
549         if erase:
550             message("Erasing data from partitions")
551             samdb.erase_partitions()
552
553     except:
554         samdb.transaction_cancel()
555         raise
556
557     samdb.transaction_commit()
558     
559     return samdb
560
561
562 def secretsdb_become_dc(secretsdb, setup_path, domain, realm, dnsdomain, 
563                         netbiosname, domainsid, keytab_path, samdb_url, 
564                         dns_keytab_path, dnspass, machinepass):
565     """Add DC-specific bits to a secrets database.
566     
567     :param secretsdb: Ldb Handle to the secrets database
568     :param setup_path: Setup path function
569     :param machinepass: Machine password
570     """
571     setup_ldb(secretsdb, setup_path("secrets_dc.ldif"), { 
572             "MACHINEPASS_B64": b64encode(machinepass),
573             "DOMAIN": domain,
574             "REALM": realm,
575             "DNSDOMAIN": dnsdomain,
576             "DOMAINSID": str(domainsid),
577             "SECRETS_KEYTAB": keytab_path,
578             "NETBIOSNAME": netbiosname,
579             "SAM_LDB": samdb_url,
580             "DNS_KEYTAB": dns_keytab_path,
581             "DNSPASS_B64": b64encode(dnspass),
582             })
583
584
585 def setup_secretsdb(path, setup_path, session_info, credentials, lp):
586     """Setup the secrets database.
587
588     :param path: Path to the secrets database.
589     :param setup_path: Get the path to a setup file.
590     :param session_info: Session info.
591     :param credentials: Credentials
592     :param lp: Loadparm context
593     :return: LDB handle for the created secrets database
594     """
595     if os.path.exists(path):
596         os.unlink(path)
597     secrets_ldb = Ldb(path, session_info=session_info, credentials=credentials,
598                       lp=lp)
599     secrets_ldb.erase()
600     secrets_ldb.load_ldif_file_add(setup_path("secrets_init.ldif"))
601     secrets_ldb = Ldb(path, session_info=session_info, credentials=credentials,
602                       lp=lp)
603     secrets_ldb.load_ldif_file_add(setup_path("secrets.ldif"))
604
605     if credentials is not None and credentials.authentication_requested():
606         if credentials.get_bind_dn() is not None:
607             setup_add_ldif(secrets_ldb, setup_path("secrets_simple_ldap.ldif"), {
608                     "LDAPMANAGERDN": credentials.get_bind_dn(),
609                     "LDAPMANAGERPASS_B64": b64encode(credentials.get_password())
610                     })
611         else:
612             setup_add_ldif(secrets_ldb, setup_path("secrets_sasl_ldap.ldif"), {
613                     "LDAPADMINUSER": credentials.get_username(),
614                     "LDAPADMINREALM": credentials.get_realm(),
615                     "LDAPADMINPASS_B64": b64encode(credentials.get_password())
616                     })
617
618     return secrets_ldb
619
620
621 def setup_templatesdb(path, setup_path, session_info, credentials, lp):
622     """Setup the templates database.
623
624     :param path: Path to the database.
625     :param setup_path: Function for obtaining the path to setup files.
626     :param session_info: Session info
627     :param credentials: Credentials
628     :param lp: Loadparm context
629     """
630     templates_ldb = SamDB(path, session_info=session_info,
631                           credentials=credentials, lp=lp)
632     # Wipes the database
633     try:
634         templates_ldb.erase()
635     except:
636         os.unlink(path)
637
638     templates_ldb.load_ldif_file_add(setup_path("provision_templates_init.ldif"))
639
640     templates_ldb = SamDB(path, session_info=session_info,
641                           credentials=credentials, lp=lp)
642
643     templates_ldb.load_ldif_file_add(setup_path("provision_templates.ldif"))
644
645
646 def setup_registry(path, setup_path, session_info, credentials, lp):
647     """Setup the registry.
648     
649     :param path: Path to the registry database
650     :param setup_path: Function that returns the path to a setup.
651     :param session_info: Session information
652     :param credentials: Credentials
653     :param lp: Loadparm context
654     """
655     reg = registry.Registry()
656     hive = registry.open_ldb(path, session_info=session_info, 
657                          credentials=credentials, lp_ctx=lp)
658     reg.mount_hive(hive, registry.HKEY_LOCAL_MACHINE)
659     provision_reg = setup_path("provision.reg")
660     assert os.path.exists(provision_reg)
661     reg.diff_apply(provision_reg)
662
663
664 def setup_idmapdb(path, setup_path, session_info, credentials, lp):
665     """Setup the idmap database.
666
667     :param path: path to the idmap database
668     :param setup_path: Function that returns a path to a setup file
669     :param session_info: Session information
670     :param credentials: Credentials
671     :param lp: Loadparm context
672     """
673     if os.path.exists(path):
674         os.unlink(path)
675
676     idmap_ldb = IDmapDB(path, session_info=session_info,
677                         credentials=credentials, lp=lp)
678
679     idmap_ldb.erase()
680     idmap_ldb.load_ldif_file_add(setup_path("idmap_init.ldif"))
681     return idmap_ldb
682
683
684 def setup_samdb_rootdse(samdb, setup_path, names):
685     """Setup the SamDB rootdse.
686
687     :param samdb: Sam Database handle
688     :param setup_path: Obtain setup path
689     """
690     setup_add_ldif(samdb, setup_path("provision_rootdse_add.ldif"), {
691         "SCHEMADN": names.schemadn, 
692         "NETBIOSNAME": names.netbiosname,
693         "DNSDOMAIN": names.dnsdomain,
694         "REALM": names.realm,
695         "DNSNAME": "%s.%s" % (names.hostname, names.dnsdomain),
696         "DOMAINDN": names.domaindn,
697         "ROOTDN": names.rootdn,
698         "CONFIGDN": names.configdn,
699         "SERVERDN": names.serverdn,
700         })
701         
702
703 def setup_self_join(samdb, names,
704                     machinepass, dnspass, 
705                     domainsid, invocationid, setup_path,
706                     policyguid):
707     """Join a host to its own domain."""
708     assert isinstance(invocationid, str)
709     setup_add_ldif(samdb, setup_path("provision_self_join.ldif"), { 
710               "CONFIGDN": names.configdn, 
711               "SCHEMADN": names.schemadn,
712               "DOMAINDN": names.domaindn,
713               "SERVERDN": names.serverdn,
714               "INVOCATIONID": invocationid,
715               "NETBIOSNAME": names.netbiosname,
716               "DEFAULTSITE": names.sitename,
717               "DNSNAME": "%s.%s" % (names.hostname, names.dnsdomain),
718               "MACHINEPASS_B64": b64encode(machinepass),
719               "DNSPASS_B64": b64encode(dnspass),
720               "REALM": names.realm,
721               "DOMAIN": names.domain,
722               "DNSDOMAIN": names.dnsdomain})
723     setup_add_ldif(samdb, setup_path("provision_group_policy.ldif"), { 
724               "POLICYGUID": policyguid,
725               "DNSDOMAIN": names.dnsdomain,
726               "DOMAINSID": str(domainsid),
727               "DOMAINDN": names.domaindn})
728
729
730 def setup_samdb(path, setup_path, session_info, credentials, lp, 
731                 names, message, 
732                 domainsid, aci, domainguid, policyguid, 
733                 fill, adminpass, krbtgtpass, 
734                 machinepass, invocationid, dnspass,
735                 serverrole, ldap_backend=None, 
736                 ldap_backend_type=None):
737     """Setup a complete SAM Database.
738     
739     :note: This will wipe the main SAM database file!
740     """
741
742     erase = (fill != FILL_DRS)
743
744     # Also wipes the database
745     setup_samdb_partitions(path, setup_path, message=message, lp=lp,
746                            credentials=credentials, session_info=session_info,
747                            names=names, 
748                            ldap_backend=ldap_backend, serverrole=serverrole,
749                            ldap_backend_type=ldap_backend_type, erase=erase)
750
751     samdb = SamDB(path, session_info=session_info, 
752                   credentials=credentials, lp=lp)
753     if fill == FILL_DRS:
754         return samdb
755
756     message("Pre-loading the Samba 4 and AD schema")
757     samdb.set_domain_sid(str(domainsid))
758     if serverrole == "domain controller":
759         samdb.set_invocation_id(invocationid)
760
761     load_schema(setup_path, samdb, names.schemadn, names.netbiosname, 
762                 names.configdn, names.sitename, names.serverdn,
763                 names.hostname)
764
765     samdb.transaction_start()
766         
767     try:
768         message("Adding DomainDN: %s (permitted to fail)" % names.domaindn)
769         if serverrole == "domain controller":
770             domain_oc = "domainDNS"
771         else:
772             domain_oc = "samba4LocalDomain"
773
774         setup_add_ldif(samdb, setup_path("provision_basedn.ldif"), {
775                 "DOMAINDN": names.domaindn,
776                 "ACI": aci,
777                 "DOMAIN_OC": domain_oc
778                 })
779
780         message("Modifying DomainDN: " + names.domaindn + "")
781         if domainguid is not None:
782             domainguid_mod = "replace: objectGUID\nobjectGUID: %s\n-" % domainguid
783         else:
784             domainguid_mod = ""
785
786         setup_modify_ldif(samdb, setup_path("provision_basedn_modify.ldif"), {
787             "LDAPTIME": timestring(int(time.time())),
788             "DOMAINSID": str(domainsid),
789             "SCHEMADN": names.schemadn, 
790             "NETBIOSNAME": names.netbiosname,
791             "DEFAULTSITE": names.sitename,
792             "CONFIGDN": names.configdn,
793             "SERVERDN": names.serverdn,
794             "POLICYGUID": policyguid,
795             "DOMAINDN": names.domaindn,
796             "DOMAINGUID_MOD": domainguid_mod,
797             })
798
799         message("Adding configuration container (permitted to fail)")
800         setup_add_ldif(samdb, setup_path("provision_configuration_basedn.ldif"), {
801             "CONFIGDN": names.configdn, 
802             "ACI": aci,
803             })
804         message("Modifying configuration container")
805         setup_modify_ldif(samdb, setup_path("provision_configuration_basedn_modify.ldif"), {
806             "CONFIGDN": names.configdn, 
807             "SCHEMADN": names.schemadn,
808             })
809
810         message("Adding schema container (permitted to fail)")
811         setup_add_ldif(samdb, setup_path("provision_schema_basedn.ldif"), {
812             "SCHEMADN": names.schemadn,
813             "ACI": aci,
814             })
815         message("Modifying schema container")
816
817         prefixmap = open(setup_path("prefixMap.txt"), 'r').read()
818
819         setup_modify_ldif(samdb, 
820             setup_path("provision_schema_basedn_modify.ldif"), {
821             "SCHEMADN": names.schemadn,
822             "NETBIOSNAME": names.netbiosname,
823             "DEFAULTSITE": names.sitename,
824             "CONFIGDN": names.configdn,
825             "SERVERDN": names.serverdn,
826             "PREFIXMAP_B64": b64encode(prefixmap)
827             })
828
829         message("Setting up sam.ldb Samba4 schema")
830         setup_add_ldif(samdb, setup_path("schema_samba4.ldif"), 
831                        {"SCHEMADN": names.schemadn })
832         message("Setting up sam.ldb AD schema")
833         setup_add_ldif(samdb, setup_path("schema.ldif"), 
834                        {"SCHEMADN": names.schemadn})
835         setup_add_ldif(samdb, setup_path("aggregate_schema.ldif"), 
836                        {"SCHEMADN": names.schemadn})
837
838         message("Setting up sam.ldb configuration data")
839         setup_add_ldif(samdb, setup_path("provision_configuration.ldif"), {
840             "CONFIGDN": names.configdn,
841             "NETBIOSNAME": names.netbiosname,
842             "DEFAULTSITE": names.sitename,
843             "DNSDOMAIN": names.dnsdomain,
844             "DOMAIN": names.domain,
845             "SCHEMADN": names.schemadn,
846             "DOMAINDN": names.domaindn,
847             "SERVERDN": names.serverdn
848             })
849
850         message("Setting up display specifiers")
851         setup_add_ldif(samdb, setup_path("display_specifiers.ldif"), 
852                        {"CONFIGDN": names.configdn})
853
854         message("Adding users container (permitted to fail)")
855         setup_add_ldif(samdb, setup_path("provision_users_add.ldif"), {
856                 "DOMAINDN": names.domaindn})
857         message("Modifying users container")
858         setup_modify_ldif(samdb, setup_path("provision_users_modify.ldif"), {
859                 "DOMAINDN": names.domaindn})
860         message("Adding computers container (permitted to fail)")
861         setup_add_ldif(samdb, setup_path("provision_computers_add.ldif"), {
862                 "DOMAINDN": names.domaindn})
863         message("Modifying computers container")
864         setup_modify_ldif(samdb, setup_path("provision_computers_modify.ldif"), {
865                 "DOMAINDN": names.domaindn})
866         message("Setting up sam.ldb data")
867         setup_add_ldif(samdb, setup_path("provision.ldif"), {
868             "DOMAINDN": names.domaindn,
869             "NETBIOSNAME": names.netbiosname,
870             "DEFAULTSITE": names.sitename,
871             "CONFIGDN": names.configdn,
872             "SERVERDN": names.serverdn
873             })
874
875         if fill == FILL_FULL:
876             message("Setting up sam.ldb users and groups")
877             setup_add_ldif(samdb, setup_path("provision_users.ldif"), {
878                 "DOMAINDN": names.domaindn,
879                 "DOMAINSID": str(domainsid),
880                 "CONFIGDN": names.configdn,
881                 "ADMINPASS_B64": b64encode(adminpass),
882                 "KRBTGTPASS_B64": b64encode(krbtgtpass),
883                 })
884
885             if serverrole == "domain controller":
886                 message("Setting up self join")
887                 setup_self_join(samdb, names=names, invocationid=invocationid, 
888                                 dnspass=dnspass,  
889                                 machinepass=machinepass, 
890                                 domainsid=domainsid, policyguid=policyguid,
891                                 setup_path=setup_path)
892
893     except:
894         samdb.transaction_cancel()
895         raise
896
897     samdb.transaction_commit()
898     return samdb
899
900
901 FILL_FULL = "FULL"
902 FILL_NT4SYNC = "NT4SYNC"
903 FILL_DRS = "DRS"
904
905 def provision(setup_dir, message, session_info, 
906               credentials, smbconf=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, 
907               rootdn=None, domaindn=None, schemadn=None, configdn=None, 
908               serverdn=None,
909               domain=None, hostname=None, hostip=None, hostip6=None, 
910               domainsid=None, adminpass=None, krbtgtpass=None, domainguid=None, 
911               policyguid=None, invocationid=None, machinepass=None, 
912               dnspass=None, root=None, nobody=None, nogroup=None, users=None, 
913               wheel=None, backup=None, aci=None, serverrole=None, 
914               ldap_backend=None, ldap_backend_type=None, sitename=None):
915     """Provision samba4
916     
917     :note: caution, this wipes all existing data!
918     """
919
920     def setup_path(file):
921         return os.path.join(setup_dir, file)
922
923     if domainsid is None:
924         domainsid = security.random_sid()
925
926     if policyguid is None:
927         policyguid = str(uuid.uuid4())
928     if adminpass is None:
929         adminpass = glue.generate_random_str(12)
930     if krbtgtpass is None:
931         krbtgtpass = glue.generate_random_str(12)
932     if machinepass is None:
933         machinepass  = glue.generate_random_str(12)
934     if dnspass is None:
935         dnspass = glue.generate_random_str(12)
936     root_uid = findnss_uid([root or "root"])
937     nobody_uid = findnss_uid([nobody or "nobody"])
938     users_gid = findnss_gid([users or "users"])
939     if wheel is None:
940         wheel_gid = findnss_gid(["wheel", "adm"])
941     else:
942         wheel_gid = findnss_gid([wheel])
943     if aci is None:
944         aci = "# no aci for local ldb"
945
946     if targetdir is not None:
947         if (not os.path.exists(os.path.join(targetdir, "etc"))):
948             os.makedirs(os.path.join(targetdir, "etc"))
949         smbconf = os.path.join(targetdir, "etc", "smb.conf")
950
951     # only install a new smb.conf if there isn't one there already
952     if not os.path.exists(smbconf):
953         make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, 
954                      targetdir)
955
956     lp = param.LoadParm()
957     lp.load(smbconf)
958
959     names = guess_names(lp=lp, hostname=hostname, domain=domain, 
960                         dnsdomain=realm, serverrole=serverrole, sitename=sitename,
961                         rootdn=rootdn, domaindn=domaindn, configdn=configdn, schemadn=schemadn,
962                         serverdn=serverdn)
963
964     paths = provision_paths_from_lp(lp, names.dnsdomain)
965
966     if hostip is None:
967         try:
968             hostip = socket.getaddrinfo(names.hostname, None, socket.AF_INET, socket.AI_CANONNAME, socket.IPPROTO_IP)[0][-1][0]
969         except socket.gaierror, (socket.EAI_NODATA, msg):
970             hostip = None
971
972     if hostip6 is None:
973         try:
974             hostip6 = socket.getaddrinfo(names.hostname, None, socket.AF_INET6, socket.AI_CANONNAME, socket.IPPROTO_IP)[0][-1][0]
975         except socket.gaierror, (socket.EAI_NODATA, msg): 
976             hostip6 = None
977
978     if serverrole is None:
979         serverrole = lp.get("server role")
980
981     assert serverrole in ("domain controller", "member server", "standalone")
982     if invocationid is None and serverrole == "domain controller":
983         invocationid = str(uuid.uuid4())
984
985     if not os.path.exists(paths.private_dir):
986         os.mkdir(paths.private_dir)
987
988     ldapi_url = "ldapi://%s" % urllib.quote(paths.s4_ldapi_path, safe="")
989     
990     if ldap_backend is not None:
991         if ldap_backend == "ldapi":
992             # provision-backend will set this path suggested slapd command line / fedorads.inf
993             ldap_backend = "ldapi://%s" % urllib.quote(os.path.join(paths.private_dir, "ldap", "ldapi"), safe="")
994              
995     # only install a new shares config db if there is none
996     if not os.path.exists(paths.shareconf):
997         message("Setting up share.ldb")
998         share_ldb = Ldb(paths.shareconf, session_info=session_info, 
999                         credentials=credentials, lp=lp)
1000         share_ldb.load_ldif_file_add(setup_path("share.ldif"))
1001
1002      
1003     message("Setting up secrets.ldb")
1004     secrets_ldb = setup_secretsdb(paths.secrets, setup_path, 
1005                                   session_info=session_info, 
1006                                   credentials=credentials, lp=lp)
1007
1008     message("Setting up the registry")
1009     setup_registry(paths.hklm, setup_path, session_info, 
1010                    credentials=credentials, lp=lp)
1011
1012     message("Setting up templates db")
1013     setup_templatesdb(paths.templates, setup_path, session_info=session_info, 
1014                       credentials=credentials, lp=lp)
1015
1016     message("Setting up idmap db")
1017     idmap = setup_idmapdb(paths.idmapdb, setup_path, session_info=session_info,
1018                           credentials=credentials, lp=lp)
1019
1020     samdb = setup_samdb(paths.samdb, setup_path, session_info=session_info, 
1021                         credentials=credentials, lp=lp, names=names,
1022                         message=message, 
1023                         domainsid=domainsid, 
1024                         aci=aci, domainguid=domainguid, policyguid=policyguid, 
1025                         fill=samdb_fill, 
1026                         adminpass=adminpass, krbtgtpass=krbtgtpass,
1027                         invocationid=invocationid, 
1028                         machinepass=machinepass, dnspass=dnspass,
1029                         serverrole=serverrole, ldap_backend=ldap_backend, 
1030                         ldap_backend_type=ldap_backend_type)
1031
1032     if lp.get("server role") == "domain controller":
1033         if paths.netlogon is None:
1034             message("Existing smb.conf does not have a [netlogon] share, but you are configuring a DC.")
1035             message("Please either remove %s or see the template at %s" % 
1036                     ( paths.smbconf, setup_path("provision.smb.conf.dc")))
1037             assert(paths.netlogon is not None)
1038
1039         if paths.sysvol is None:
1040             message("Existing smb.conf does not have a [sysvol] share, but you are configuring a DC.")
1041             message("Please either remove %s or see the template at %s" % 
1042                     (paths.smbconf, setup_path("provision.smb.conf.dc")))
1043             assert(paths.sysvol is not None)            
1044             
1045         policy_path = os.path.join(paths.sysvol, names.dnsdomain, "Policies", 
1046                                    "{" + policyguid + "}")
1047         os.makedirs(policy_path, 0755)
1048         open(os.path.join(policy_path, "GPT.INI"), 'w').write("")
1049         os.makedirs(os.path.join(policy_path, "Machine"), 0755)
1050         os.makedirs(os.path.join(policy_path, "User"), 0755)
1051         if not os.path.isdir(paths.netlogon):
1052             os.makedirs(paths.netlogon, 0755)
1053
1054     if samdb_fill == FILL_FULL:
1055         setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn,
1056                             root_uid=root_uid, nobody_uid=nobody_uid,
1057                             users_gid=users_gid, wheel_gid=wheel_gid)
1058
1059         message("Setting up sam.ldb rootDSE marking as synchronized")
1060         setup_modify_ldif(samdb, setup_path("provision_rootdse_modify.ldif"))
1061
1062         # Only make a zone file on the first DC, it should be replicated with DNS replication
1063         if serverrole == "domain controller":
1064             secrets_ldb = Ldb(paths.secrets, session_info=session_info, 
1065                               credentials=credentials, lp=lp)
1066             secretsdb_become_dc(secrets_ldb, setup_path, domain=domain, realm=names.realm,
1067                                 netbiosname=names.netbiosname, domainsid=domainsid, 
1068                                 keytab_path=paths.keytab, samdb_url=paths.samdb, 
1069                                 dns_keytab_path=paths.dns_keytab, dnspass=dnspass, 
1070                                 machinepass=machinepass, dnsdomain=names.dnsdomain)
1071
1072             samdb = SamDB(paths.samdb, session_info=session_info, 
1073                       credentials=credentials, lp=lp)
1074
1075             domainguid = samdb.searchone(basedn=domaindn, attribute="objectGUID")
1076             assert isinstance(domainguid, str)
1077             hostguid = samdb.searchone(basedn=domaindn, attribute="objectGUID",
1078                                        expression="(&(objectClass=computer)(cn=%s))" % names.hostname,
1079                                        scope=SCOPE_SUBTREE)
1080             assert isinstance(hostguid, str)
1081
1082             create_zone_file(paths.dns, setup_path, dnsdomain=names.dnsdomain,
1083                              domaindn=names.domaindn, hostip=hostip,
1084                              hostip6=hostip6, hostname=names.hostname,
1085                              dnspass=dnspass, realm=names.realm,
1086                              domainguid=domainguid, hostguid=hostguid)
1087
1088             create_named_conf(paths.namedconf, setup_path, realm=names.realm,
1089                               dnsdomain=names.dnsdomain, private_dir=paths.private_dir)
1090
1091             create_named_txt(paths.namedtxt, setup_path, realm=names.realm,
1092                               dnsdomain=names.dnsdomain, private_dir=paths.private_dir,
1093                               keytab_name=paths.dns_keytab)
1094             message("See %s for an example configuration include file for BIND" % paths.namedconf)
1095             message("and %s for further documentation required for secure DNS updates" % paths.namedtxt)
1096
1097             create_krb5_conf(paths.krb5conf, setup_path, dnsdomain=names.dnsdomain,
1098                              hostname=names.hostname, realm=names.realm)
1099             message("A Kerberos configuration suitable for Samba 4 has been generated at %s" % paths.krb5conf)
1100
1101     create_phpldapadmin_config(paths.phpldapadminconfig, setup_path, 
1102                                ldapi_url)
1103
1104     message("Please install the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php" % paths.phpldapadminconfig)
1105
1106     message("Once the above files are installed, your Samba4 server will be ready to use")
1107     message("Server Role:    %s" % serverrole)
1108     message("Hostname:       %s" % names.hostname)
1109     message("NetBIOS Domain: %s" % names.domain)
1110     message("DNS Domain:     %s" % names.dnsdomain)
1111     message("DOMAIN SID:     %s" % str(domainsid))
1112     message("Admin password: %s" % adminpass)
1113
1114     result = ProvisionResult()
1115     result.domaindn = domaindn
1116     result.paths = paths
1117     result.lp = lp
1118     result.samdb = samdb
1119     return result
1120
1121
1122 def provision_become_dc(setup_dir=None,
1123                         smbconf=None, targetdir=None, realm=None, 
1124                         rootdn=None, domaindn=None, schemadn=None, configdn=None,
1125                         serverdn=None,
1126                         domain=None, hostname=None, domainsid=None, 
1127                         adminpass=None, krbtgtpass=None, domainguid=None, 
1128                         policyguid=None, invocationid=None, machinepass=None, 
1129                         dnspass=None, root=None, nobody=None, nogroup=None, users=None, 
1130                         wheel=None, backup=None, aci=None, serverrole=None, 
1131                         ldap_backend=None, ldap_backend_type=None, sitename=None):
1132
1133     def message(text):
1134         """print a message if quiet is not set."""
1135         print text
1136
1137     return provision(setup_dir, message, system_session(), None,
1138               smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, realm=realm, 
1139               rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, configdn=configdn, serverdn=serverdn,
1140               domain=domain, hostname=hostname, hostip="127.0.0.1", domainsid=domainsid, machinepass=machinepass, serverrole="domain controller", sitename=sitename)
1141     
1142
1143 def setup_db_config(setup_path, dbdir):
1144     """Setup a Berkeley database.
1145     
1146     :param setup_path: Setup path function.
1147     :param dbdir: Database directory."""
1148     if not os.path.isdir(os.path.join(dbdir, "bdb-logs")):
1149         os.makedirs(os.path.join(dbdir, "bdb-logs"), 0700)
1150     if not os.path.isdir(os.path.join(dbdir, "tmp")):
1151         os.makedirs(os.path.join(dbdir, "tmp"), 0700)
1152     
1153     setup_file(setup_path("DB_CONFIG"), os.path.join(dbdir, "DB_CONFIG"),
1154                {"LDAPDBDIR": dbdir})
1155     
1156
1157
1158 def provision_backend(setup_dir=None, message=None,
1159                       smbconf=None, targetdir=None, realm=None, 
1160                       rootdn=None, domaindn=None, schemadn=None, configdn=None,
1161                       domain=None, hostname=None, adminpass=None, root=None, serverrole=None, 
1162                       ldap_backend_type=None, ldap_backend_port=None,
1163                       ol_mmr_urls=None):
1164
1165     def setup_path(file):
1166         return os.path.join(setup_dir, file)
1167
1168     if hostname is None:
1169         hostname = socket.gethostname().split(".")[0].lower()
1170
1171     if root is None:
1172         root = findnss(pwd.getpwnam, ["root"])[0]
1173
1174     if adminpass is None:
1175         adminpass = glue.generate_random_str(12)
1176
1177     if targetdir is not None:
1178         if (not os.path.exists(os.path.join(targetdir, "etc"))):
1179             os.makedirs(os.path.join(targetdir, "etc"))
1180         smbconf = os.path.join(targetdir, "etc", "smb.conf")
1181
1182     # only install a new smb.conf if there isn't one there already
1183     if not os.path.exists(smbconf):
1184         make_smbconf(smbconf, setup_path, hostname, domain, realm, serverrole, 
1185                      targetdir)
1186
1187     lp = param.LoadParm()
1188     lp.load(smbconf)
1189
1190     names = guess_names(lp=lp, hostname=hostname, domain=domain, 
1191                         dnsdomain=realm, serverrole=serverrole, 
1192                         rootdn=rootdn, domaindn=domaindn, configdn=configdn, 
1193                         schemadn=schemadn)
1194
1195     paths = provision_paths_from_lp(lp, names.dnsdomain)
1196
1197     if not os.path.isdir(paths.ldapdir):
1198         os.makedirs(paths.ldapdir, 0700)
1199     schemadb_path = os.path.join(paths.ldapdir, "schema-tmp.ldb")
1200     try:
1201         os.unlink(schemadb_path)
1202     except:
1203         pass
1204
1205     schemadb = Ldb(schemadb_path, lp=lp)
1206  
1207     prefixmap = open(setup_path("prefixMap.txt"), 'r').read()
1208
1209     setup_add_ldif(schemadb, setup_path("provision_schema_basedn.ldif"), 
1210                    {"SCHEMADN": names.schemadn,
1211                     "ACI": "#",
1212                     })
1213     setup_modify_ldif(schemadb, 
1214                       setup_path("provision_schema_basedn_modify.ldif"), \
1215                           {"SCHEMADN": names.schemadn,
1216                            "NETBIOSNAME": names.netbiosname,
1217                            "DEFAULTSITE": DEFAULTSITE,
1218                            "CONFIGDN": names.configdn,
1219                            "SERVERDN": names.serverdn,
1220                            "PREFIXMAP_B64": b64encode(prefixmap)
1221                            })
1222     
1223     setup_add_ldif(schemadb, setup_path("schema_samba4.ldif"), 
1224                    {"SCHEMADN": names.schemadn })
1225     setup_add_ldif(schemadb, setup_path("schema.ldif"), 
1226                    {"SCHEMADN": names.schemadn})
1227
1228     if ldap_backend_type == "fedora-ds":
1229         if ldap_backend_port is not None:
1230             serverport = "ServerPort=%d" % ldap_backend_port
1231         else:
1232             serverport = ""
1233
1234         setup_file(setup_path("fedorads.inf"), paths.fedoradsinf, 
1235                    {"ROOT": root,
1236                     "HOSTNAME": hostname,
1237                     "DNSDOMAIN": names.dnsdomain,
1238                     "LDAPDIR": paths.ldapdir,
1239                     "DOMAINDN": names.domaindn,
1240                     "LDAPMANAGERDN": names.ldapmanagerdn,
1241                     "LDAPMANAGERPASS": adminpass, 
1242                     "SERVERPORT": serverport})
1243         
1244         setup_file(setup_path("fedorads-partitions.ldif"), paths.fedoradspartitions, 
1245                    {"CONFIGDN": names.configdn,
1246                     "SCHEMADN": names.schemadn,
1247                     })
1248         
1249         mapping = "schema-map-fedora-ds-1.0"
1250         backend_schema = "99_ad.ldif"
1251         
1252         slapdcommand="Initailise Fedora DS with: setup-ds.pl --file=%s" % paths.fedoradsinf
1253        
1254         ldapuser = "--simple-bind-dn=" + names.ldapmanagerdn
1255
1256     elif ldap_backend_type == "openldap":
1257         attrs = ["linkID", "lDAPDisplayName"]
1258         res = schemadb.search(expression="(&(linkID=*)(!(linkID:1.2.840.113556.1.4.803:=1))(objectclass=attributeSchema)(omSyntax=127))", base=names.schemadn, scope=SCOPE_SUBTREE, attrs=attrs)
1259
1260         memberof_config = "# Generated from schema in %s\n" % schemadb_path
1261         refint_attributes = ""
1262         for i in range (0, len(res)):
1263             expression = "(&(objectclass=attributeSchema)(linkID=%d)(omSyntax=127))" % (int(res[i]["linkID"][0])+1)
1264             target = schemadb.searchone(basedn=names.schemadn, 
1265                                         expression=expression, 
1266                                         attribute="lDAPDisplayName", 
1267                                         scope=SCOPE_SUBTREE)
1268             if target is not None:
1269                 refint_attributes = refint_attributes + " " + target + " " + res[i]["lDAPDisplayName"][0]
1270             
1271                 memberof_config += read_and_sub_file(setup_path("memberof.conf"),
1272                                                      { "MEMBER_ATTR" : str(res[i]["lDAPDisplayName"][0]),
1273                                                        "MEMBEROF_ATTR" : str(target) })
1274
1275         refint_config = read_and_sub_file(setup_path("refint.conf"),
1276                                             { "LINK_ATTRS" : refint_attributes})
1277
1278 # generate serverids, ldap-urls and syncrepl-blocks for mmr hosts
1279         mmr_on_config = ""
1280         mmr_replicator_acl = ""
1281         mmr_serverids_config = ""
1282         mmr_syncrepl_schema_config = "" 
1283         mmr_syncrepl_config_config = "" 
1284         mmr_syncrepl_user_config = "" 
1285         
1286         if ol_mmr_urls is not None:
1287                 # For now, make these equal
1288                 mmr_pass = adminpass
1289
1290                 url_list=filter(None,ol_mmr_urls.split(' ')) 
1291                 if (len(url_list) == 1):
1292                     url_list=filter(None,ol_mmr_urls.split(',')) 
1293                      
1294
1295                 mmr_on_config = "MirrorMode On"
1296                 mmr_replicator_acl = "  by dn=cn=replicator,cn=samba read"
1297                 serverid=0
1298                 for url in url_list:
1299                         serverid=serverid+1
1300                         mmr_serverids_config += read_and_sub_file(setup_path("mmr_serverids.conf"),
1301                                                                      { "SERVERID" : str(serverid),
1302                                                                        "LDAPSERVER" : url })
1303                         rid=serverid*10
1304                         rid=rid+1
1305                         mmr_syncrepl_schema_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
1306                                                                      {  "RID" : str(rid),
1307                                                                         "MMRDN": names.schemadn,
1308                                                                         "LDAPSERVER" : url,
1309                                                                         "MMR_PASSWORD": mmr_pass})
1310
1311                         rid=rid+1
1312                         mmr_syncrepl_config_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
1313                                                                      {  "RID" : str(rid),
1314                                                                         "MMRDN": names.configdn,
1315                                                                         "LDAPSERVER" : url,
1316                                                                         "MMR_PASSWORD": mmr_pass})
1317
1318                         rid=rid+1
1319                         mmr_syncrepl_user_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
1320                                                                      {  "RID" : str(rid),
1321                                                                         "MMRDN": names.domaindn,
1322                                                                         "LDAPSERVER" : url,
1323                                                                         "MMR_PASSWORD": mmr_pass })
1324
1325
1326         setup_file(setup_path("slapd.conf"), paths.slapdconf,
1327                    {"DNSDOMAIN": names.dnsdomain,
1328                     "LDAPDIR": paths.ldapdir,
1329                     "DOMAINDN": names.domaindn,
1330                     "CONFIGDN": names.configdn,
1331                     "SCHEMADN": names.schemadn,
1332                     "MEMBEROF_CONFIG": memberof_config,
1333                     "MIRRORMODE": mmr_on_config,
1334                     "REPLICATOR_ACL": mmr_replicator_acl,
1335                     "MMR_SERVERIDS_CONFIG": mmr_serverids_config,
1336                     "MMR_SYNCREPL_SCHEMA_CONFIG": mmr_syncrepl_schema_config,
1337                     "MMR_SYNCREPL_CONFIG_CONFIG": mmr_syncrepl_config_config,
1338                     "MMR_SYNCREPL_USER_CONFIG": mmr_syncrepl_user_config,
1339                     "REFINT_CONFIG": refint_config})
1340         setup_file(setup_path("modules.conf"), paths.modulesconf,
1341                    {"REALM": names.realm})
1342         
1343         setup_db_config(setup_path, os.path.join(paths.ldapdir, "db", "user"))
1344         setup_db_config(setup_path, os.path.join(paths.ldapdir, "db", "config"))
1345         setup_db_config(setup_path, os.path.join(paths.ldapdir, "db", "schema"))
1346
1347         if not os.path.exists(os.path.join(paths.ldapdir, "db", "samba",  "cn=samba")):
1348             os.makedirs(os.path.join(paths.ldapdir, "db", "samba",  "cn=samba"), 0700)
1349
1350         setup_file(setup_path("cn=samba.ldif"), 
1351                    os.path.join(paths.ldapdir, "db", "samba",  "cn=samba.ldif"),
1352                    { "UUID": str(uuid.uuid4()), 
1353                      "LDAPTIME": timestring(int(time.time()))} )
1354         setup_file(setup_path("cn=samba-admin.ldif"), 
1355                               os.path.join(paths.ldapdir, "db", "samba",  "cn=samba", "cn=samba-admin.ldif"),
1356                               {"LDAPADMINPASS_B64": b64encode(adminpass),
1357                                "UUID": str(uuid.uuid4()), 
1358                                "LDAPTIME": timestring(int(time.time()))} )
1359         
1360         if ol_mmr_urls is not None:
1361            setup_file(setup_path("cn=replicator.ldif"),
1362                               os.path.join(paths.ldapdir, "db", "samba",  "cn=samba", "cn=replicator.ldif"),
1363                               {"MMR_PASSWORD_B64": b64encode(mmr_pass),
1364                                "UUID": str(uuid.uuid4()),
1365                                "LDAPTIME": timestring(int(time.time()))} )
1366
1367
1368
1369         mapping = "schema-map-openldap-2.3"
1370         backend_schema = "backend-schema.schema"
1371
1372         ldapi_uri = "ldapi://" + urllib.quote(os.path.join(paths.private_dir, "ldap", "ldapi"), safe="")
1373         if ldap_backend_port is not None:
1374             server_port_string = " -h ldap://0.0.0.0:%d" % ldap_backend_port
1375         else:
1376             server_port_string = ""
1377
1378         slapdcommand="Start slapd with:    slapd -f " + paths.ldapdir + "/slapd.conf -h " + ldapi_uri + server_port_string
1379
1380         ldapuser = "--username=samba-admin"
1381
1382             
1383     schema_command = "bin/ad2oLschema --option=convert:target=" + ldap_backend_type + " -I " + setup_path(mapping) + " -H tdb://" + schemadb_path + " -O " + os.path.join(paths.ldapdir, backend_schema)
1384             
1385     os.system(schema_command)
1386
1387     message("Your %s Backend for Samba4 is now configured, and is ready to be started" % ldap_backend_type)
1388     message("Server Role:         %s" % serverrole)
1389     message("Hostname:            %s" % names.hostname)
1390     message("DNS Domain:          %s" % names.dnsdomain)
1391     message("Base DN:             %s" % names.domaindn)
1392
1393     if ldap_backend_type == "openldap":
1394         message("LDAP admin user:     samba-admin")
1395     else:
1396         message("LDAP admin DN:       %s" % names.ldapmanagerdn)
1397
1398     message("LDAP admin password: %s" % adminpass)
1399     message(slapdcommand)
1400     message("Run provision with:  --ldap-backend=ldapi --ldap-backend-type=" + ldap_backend_type + " --password=" + adminpass + " " + ldapuser)
1401
1402 def create_phpldapadmin_config(path, setup_path, ldapi_uri):
1403     """Create a PHP LDAP admin configuration file.
1404
1405     :param path: Path to write the configuration to.
1406     :param setup_path: Function to generate setup paths.
1407     """
1408     setup_file(setup_path("phpldapadmin-config.php"), path, 
1409             {"S4_LDAPI_URI": ldapi_uri})
1410
1411
1412 def create_zone_file(path, setup_path, dnsdomain, domaindn, 
1413                      hostip, hostip6, hostname, dnspass, realm, domainguid, hostguid):
1414     """Write out a DNS zone file, from the info in the current database.
1415
1416     :param path: Path of the new zone file.
1417     :param setup_path: Setup path function.
1418     :param dnsdomain: DNS Domain name
1419     :param domaindn: DN of the Domain
1420     :param hostip: Local IPv4 IP
1421     :param hostip6: Local IPv6 IP
1422     :param hostname: Local hostname
1423     :param dnspass: Password for DNS
1424     :param realm: Realm name
1425     :param domainguid: GUID of the domain.
1426     :param hostguid: GUID of the host.
1427     """
1428     assert isinstance(domainguid, str)
1429
1430     if hostip6 is not None:
1431         hostip6_base_line = "            IN AAAA    " + hostip6
1432         hostip6_host_line = hostname + "        IN AAAA    " + hostip6
1433     else:
1434         hostip6_base_line = ""
1435         hostip6_host_line = ""
1436
1437     if hostip is not None:
1438         hostip_base_line = "            IN A    " + hostip
1439         hostip_host_line = hostname + "        IN A    " + hostip
1440     else:
1441         hostip_base_line = ""
1442         hostip_host_line = ""
1443
1444     setup_file(setup_path("provision.zone"), path, {
1445             "DNSPASS_B64": b64encode(dnspass),
1446             "HOSTNAME": hostname,
1447             "DNSDOMAIN": dnsdomain,
1448             "REALM": realm,
1449             "HOSTIP_BASE_LINE": hostip_base_line,
1450             "HOSTIP_HOST_LINE": hostip_host_line,
1451             "DOMAINGUID": domainguid,
1452             "DATESTRING": time.strftime("%Y%m%d%H"),
1453             "DEFAULTSITE": DEFAULTSITE,
1454             "HOSTGUID": hostguid,
1455             "HOSTIP6_BASE_LINE": hostip6_base_line,
1456             "HOSTIP6_HOST_LINE": hostip6_host_line,
1457         })
1458
1459
1460 def create_named_conf(path, setup_path, realm, dnsdomain,
1461                       private_dir):
1462     """Write out a file containing zone statements suitable for inclusion in a
1463     named.conf file (including GSS-TSIG configuration).
1464     
1465     :param path: Path of the new named.conf file.
1466     :param setup_path: Setup path function.
1467     :param realm: Realm name
1468     :param dnsdomain: DNS Domain name
1469     :param private_dir: Path to private directory
1470     :param keytab_name: File name of DNS keytab file
1471     """
1472
1473     setup_file(setup_path("named.conf"), path, {
1474             "DNSDOMAIN": dnsdomain,
1475             "REALM": realm,
1476             "REALM_WC": "*." + ".".join(realm.split(".")[1:]),
1477             "PRIVATE_DIR": private_dir
1478             })
1479
1480 def create_named_txt(path, setup_path, realm, dnsdomain,
1481                       private_dir, keytab_name):
1482     """Write out a file containing zone statements suitable for inclusion in a
1483     named.conf file (including GSS-TSIG configuration).
1484     
1485     :param path: Path of the new named.conf file.
1486     :param setup_path: Setup path function.
1487     :param realm: Realm name
1488     :param dnsdomain: DNS Domain name
1489     :param private_dir: Path to private directory
1490     :param keytab_name: File name of DNS keytab file
1491     """
1492
1493     setup_file(setup_path("named.txt"), path, {
1494             "DNSDOMAIN": dnsdomain,
1495             "REALM": realm,
1496             "DNS_KEYTAB": keytab_name,
1497             "DNS_KEYTAB_ABS": os.path.join(private_dir, keytab_name),
1498             "PRIVATE_DIR": private_dir
1499         })
1500
1501 def create_krb5_conf(path, setup_path, dnsdomain, hostname, realm):
1502     """Write out a file containing zone statements suitable for inclusion in a
1503     named.conf file (including GSS-TSIG configuration).
1504     
1505     :param path: Path of the new named.conf file.
1506     :param setup_path: Setup path function.
1507     :param dnsdomain: DNS Domain name
1508     :param hostname: Local hostname
1509     :param realm: Realm name
1510     """
1511
1512     setup_file(setup_path("krb5.conf"), path, {
1513             "DNSDOMAIN": dnsdomain,
1514             "HOSTNAME": hostname,
1515             "REALM": realm,
1516         })
1517
1518
1519 def load_schema(setup_path, samdb, schemadn, netbiosname, configdn, sitename,
1520                 serverdn, servername):
1521     """Load schema for the SamDB.
1522     
1523     :param samdb: Load a schema into a SamDB.
1524     :param setup_path: Setup path function.
1525     :param schemadn: DN of the schema
1526     :param netbiosname: NetBIOS name of the host.
1527     :param configdn: DN of the configuration
1528     :param serverdn: DN of the server
1529     :param servername: Host name of the server
1530     """
1531     schema_data = open(setup_path("schema.ldif"), 'r').read()
1532     schema_data += open(setup_path("schema_samba4.ldif"), 'r').read()
1533     schema_data = substitute_var(schema_data, {"SCHEMADN": schemadn})
1534     check_all_substituted(schema_data)
1535     prefixmap = open(setup_path("prefixMap.txt"), 'r').read()
1536     prefixmap = b64encode(prefixmap)
1537
1538     head_data = open(setup_path("provision_schema_basedn_modify.ldif"), 'r').read()
1539     head_data = substitute_var(head_data, {
1540                     "SCHEMADN": schemadn,
1541                     "NETBIOSNAME": netbiosname,
1542                     "CONFIGDN": configdn,
1543                     "DEFAULTSITE": sitename,
1544                     "PREFIXMAP_B64": prefixmap,
1545                     "SERVERDN": serverdn,
1546                     "SERVERNAME": servername,
1547     })
1548     check_all_substituted(head_data)
1549     samdb.attach_schema_from_ldif(head_data, schema_data)
1550