fc1bac673d9a8175e5ac3187719a0aad982e5929
[ira/wip.git] / source4 / scripting / python / samba / provisionbackend.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-2009
7 # Copyright (C) Oliver Liebel <oliver@itc.li> 2008-2009
8 #
9 # Based on the original in EJS:
10 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
11 #
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 3 of the License, or
15 # (at your option) any later version.
16 #   
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21 #   
22 # You should have received a copy of the GNU General Public License
23 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 #
25
26 """Functions for setting up a Samba configuration (LDB and LDAP backends)."""
27
28 from base64 import b64encode
29 import os
30 import sys
31 import uuid
32 import time
33
34 from samba import read_and_sub_file
35 from samba import Ldb
36 import urllib
37 from ldb import SCOPE_BASE, SCOPE_ONELEVEL, LdbError, timestring
38 from credentials import Credentials, DONT_USE_KERBEROS
39 from samba import setup_file
40
41 def setup_db_config(setup_path, dbdir):
42     """Setup a Berkeley database.
43     
44     :param setup_path: Setup path function.
45     :param dbdir: Database directory."""
46     if not os.path.isdir(os.path.join(dbdir, "bdb-logs")):
47         os.makedirs(os.path.join(dbdir, "bdb-logs"), 0700)
48         if not os.path.isdir(os.path.join(dbdir, "tmp")):
49             os.makedirs(os.path.join(dbdir, "tmp"), 0700)
50
51     setup_file(setup_path("DB_CONFIG"), os.path.join(dbdir, "DB_CONFIG"),
52                {"LDAPDBDIR": dbdir})
53
54 class ProvisionBackend(object):
55     def __init__(self, backend_type, paths=None, setup_path=None, lp=None, credentials=None, 
56                  names=None, message=None, 
57                  hostname=None, root=None, 
58                  schema=None, ldapadminpass=None,
59                  ldap_backend_extra_port=None,
60                  ol_mmr_urls=None, 
61                  setup_ds_path=None, slapd_path=None, 
62                  nosync=False, ldap_dryrun_mode=False,
63                  domainsid=None):
64         """Provision an LDAP backend for samba4
65         
66         This works for OpenLDAP and Fedora DS
67         """
68         self.paths = paths
69         self.slapd_command = None
70         self.slapd_command_escaped = None
71
72         self.type = backend_type
73         
74         # Set a default - the code for "existing" below replaces this
75         self.ldap_backend_type = backend_type
76
77         self.post_setup = None
78         self.shutdown = None
79
80         if self.type is "ldb":
81             self.credentials = None
82             self.secrets_credentials = None
83             return
84
85         self.ldapi_uri = "ldapi://" + urllib.quote(os.path.join(paths.ldapdir, "ldapi"), safe="")
86         
87         if self.type == "existing":
88             #Check to see that this 'existing' LDAP backend in fact exists
89             ldapi_db = Ldb(self.ldapi_uri, credentials=credentials)
90             search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
91                                                 expression="(objectClass=OpenLDAProotDSE)")
92
93             # If we have got here, then we must have a valid connection to the LDAP server, with valid credentials supplied
94             self.credentials = credentials
95             # This caused them to be set into the long-term database later in the script.
96             self.secrets_credentials = credentials
97
98             self.ldap_backend_type = "openldap" #For now, assume existing backends at least emulate OpenLDAP
99             return
100     
101         # we will shortly start slapd with ldapi for final provisioning. first check with ldapsearch -> rootDSE via self.ldapi_uri
102         # if another instance of slapd is already running 
103         try:
104             ldapi_db = Ldb(self.ldapi_uri)
105             search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
106                                                 expression="(objectClass=OpenLDAProotDSE)");
107             try:
108                 f = open(paths.slapdpid, "r")
109                 p = f.read()
110                 f.close()
111                 message("Check for slapd Process with PID: " + str(p) + " and terminate it manually.")
112             except:
113                 pass
114             
115             raise ProvisioningError("Warning: Another slapd Instance seems already running on this host, listening to " + self.ldapi_uri + ". Please shut it down before you continue. ")
116         
117         except LdbError, e:
118             pass
119
120         # Try to print helpful messages when the user has not specified the path to slapd
121         if slapd_path is None:
122             raise ProvisioningError("Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!")
123         if not os.path.exists(slapd_path):
124             message (slapd_path)
125             raise ProvisioningError("Warning: Given Path to slapd does not exist!")
126
127
128         if not os.path.isdir(paths.ldapdir):
129             os.makedirs(paths.ldapdir, 0700)
130
131         # Put the LDIF of the schema into a database so we can search on
132         # it to generate schema-dependent configurations in Fedora DS and
133         # OpenLDAP
134         schemadb_path = os.path.join(paths.ldapdir, "schema-tmp.ldb")
135         try:
136             os.unlink(schemadb_path)
137         except OSError:
138             pass
139
140         schema.write_to_tmp_ldb(schemadb_path);
141
142         self.credentials = Credentials()
143         self.credentials.guess(lp)
144         #Kerberos to an ldapi:// backend makes no sense
145         self.credentials.set_kerberos_state(DONT_USE_KERBEROS)
146
147         self.secrets_credentials = Credentials()
148         self.secrets_credentials.guess(lp)
149         #Kerberos to an ldapi:// backend makes no sense
150         self.secrets_credentials.set_kerberos_state(DONT_USE_KERBEROS)
151
152
153         def ldap_backend_shutdown(self):
154             # if an LDAP backend is in use, terminate slapd after final provision and check its proper termination
155             if self.slapd.poll() is None:
156                 #Kill the slapd
157                 if hasattr(self.slapd, "terminate"):
158                     self.slapd.terminate()
159                 else:
160                     # Older python versions don't have .terminate()
161                     import signal
162                     os.kill(self.slapd.pid, signal.SIGTERM)
163             
164                 #and now wait for it to die
165                 self.slapd.communicate()
166
167         self.shutdown = ldap_backend_shutdown
168
169         if self.type == "fedora-ds":
170             provision_fds_backend(self, setup_path=setup_path,
171                                   names=names, message=message, 
172                                   hostname=hostname,
173                                   ldapadminpass=ldapadminpass, root=root, 
174                                   schema=schema,
175                                   ldap_backend_extra_port=ldap_backend_extra_port, 
176                                   setup_ds_path=setup_ds_path,
177                                   slapd_path=slapd_path,
178                                   nosync=nosync,
179                                   ldap_dryrun_mode=ldap_dryrun_mode,
180                                   domainsid=domainsid)
181             
182         elif self.type == "openldap":
183             provision_openldap_backend(self, setup_path=setup_path,
184                                        names=names, message=message, 
185                                        hostname=hostname,
186                                        ldapadminpass=ldapadminpass, root=root, 
187                                        schema=schema,
188                                        ldap_backend_extra_port=ldap_backend_extra_port, 
189                                        ol_mmr_urls=ol_mmr_urls, 
190                                        slapd_path=slapd_path,
191                                        nosync=nosync,
192                                        ldap_dryrun_mode=ldap_dryrun_mode)
193         else:
194             raise ProvisioningError("Unknown LDAP backend type selected")
195
196         self.credentials.set_password(ldapadminpass)
197         self.secrets_credentials.set_username("samba-admin")
198         self.secrets_credentials.set_password(ldapadminpass)
199
200         self.slapd_command_escaped = "\'" + "\' \'".join(self.slapd_command) + "\'"
201         setup_file(setup_path("ldap_backend_startup.sh"), paths.ldapdir + "/ldap_backend_startup.sh", {
202                 "SLAPD_COMMAND" : slapd_command})
203
204         # Now start the slapd, so we can provision onto it.  We keep the
205         # subprocess context around, to kill this off at the successful
206         # end of the script
207         self.slapd = subprocess.Popen(self.slapd_provision_command, close_fds=True, shell=False)
208     
209         while self.slapd.poll() is None:
210             # Wait until the socket appears
211             try:
212                 ldapi_db = Ldb(self.ldapi_uri, lp=lp, credentials=self.credentials)
213                 search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
214                                                     expression="(objectClass=OpenLDAProotDSE)")
215                 # If we have got here, then we must have a valid connection to the LDAP server!
216                 return
217             except LdbError, e:
218                 time.sleep(1)
219                 pass
220         
221         raise ProvisioningError("slapd died before we could make a connection to it")
222
223
224 def provision_openldap_backend(result, setup_path=None, names=None,
225                                message=None, 
226                                hostname=None, ldapadminpass=None, root=None, 
227                                schema=None, 
228                                ldap_backend_extra_port=None,
229                                ol_mmr_urls=None, 
230                                slapd_path=None, nosync=False,
231                                ldap_dryrun_mode=False):
232
233     #Allow the test scripts to turn off fsync() for OpenLDAP as for TDB and LDB
234     nosync_config = ""
235     if nosync:
236         nosync_config = "dbnosync"
237         
238     lnkattr = schema.linked_attributes()
239     refint_attributes = ""
240     memberof_config = "# Generated from Samba4 schema\n"
241     for att in  lnkattr.keys():
242         if lnkattr[att] is not None:
243             refint_attributes = refint_attributes + " " + att 
244             
245             memberof_config += read_and_sub_file(setup_path("memberof.conf"),
246                                                  { "MEMBER_ATTR" : att ,
247                                                    "MEMBEROF_ATTR" : lnkattr[att] })
248             
249     refint_config = read_and_sub_file(setup_path("refint.conf"),
250                                       { "LINK_ATTRS" : refint_attributes})
251     
252     attrs = ["linkID", "lDAPDisplayName"]
253     res = schema.ldb.search(expression="(&(objectclass=attributeSchema)(searchFlags:1.2.840.113556.1.4.803:=1))", base=names.schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
254     index_config = ""
255     for i in range (0, len(res)):
256         index_attr = res[i]["lDAPDisplayName"][0]
257         if index_attr == "objectGUID":
258             index_attr = "entryUUID"
259             
260         index_config += "index " + index_attr + " eq\n"
261
262 # generate serverids, ldap-urls and syncrepl-blocks for mmr hosts
263     mmr_on_config = ""
264     mmr_replicator_acl = ""
265     mmr_serverids_config = ""
266     mmr_syncrepl_schema_config = "" 
267     mmr_syncrepl_config_config = "" 
268     mmr_syncrepl_user_config = "" 
269        
270     
271     if ol_mmr_urls is not None:
272         # For now, make these equal
273         mmr_pass = ldapadminpass
274         
275         url_list=filter(None,ol_mmr_urls.split(' ')) 
276         if (len(url_list) == 1):
277             url_list=filter(None,ol_mmr_urls.split(',')) 
278                      
279             
280             mmr_on_config = "MirrorMode On"
281             mmr_replicator_acl = "  by dn=cn=replicator,cn=samba read"
282             serverid=0
283             for url in url_list:
284                 serverid=serverid+1
285                 mmr_serverids_config += read_and_sub_file(setup_path("mmr_serverids.conf"),
286                                                           { "SERVERID" : str(serverid),
287                                                             "LDAPSERVER" : url })
288                 rid=serverid*10
289                 rid=rid+1
290                 mmr_syncrepl_schema_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
291                                                                 {  "RID" : str(rid),
292                                                                    "MMRDN": names.schemadn,
293                                                                    "LDAPSERVER" : url,
294                                                                    "MMR_PASSWORD": mmr_pass})
295                 
296                 rid=rid+1
297                 mmr_syncrepl_config_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
298                                                                 {  "RID" : str(rid),
299                                                                    "MMRDN": names.configdn,
300                                                                    "LDAPSERVER" : url,
301                                                                    "MMR_PASSWORD": mmr_pass})
302                 
303                 rid=rid+1
304                 mmr_syncrepl_user_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
305                                                               {  "RID" : str(rid),
306                                                                  "MMRDN": names.domaindn,
307                                                                  "LDAPSERVER" : url,
308                                                                  "MMR_PASSWORD": mmr_pass })
309     # OpenLDAP cn=config initialisation
310     olc_syncrepl_config = ""
311     olc_mmr_config = "" 
312     # if mmr = yes, generate cn=config-replication directives
313     # and olc_seed.lif for the other mmr-servers
314     if ol_mmr_urls is not None:
315         serverid=0
316         olc_serverids_config = ""
317         olc_syncrepl_seed_config = ""
318         olc_mmr_config += read_and_sub_file(setup_path("olc_mmr.conf"),{})
319         rid=1000
320         for url in url_list:
321             serverid=serverid+1
322             olc_serverids_config += read_and_sub_file(setup_path("olc_serverid.conf"),
323                                                       { "SERVERID" : str(serverid),
324                                                         "LDAPSERVER" : url })
325             
326             rid=rid+1
327             olc_syncrepl_config += read_and_sub_file(setup_path("olc_syncrepl.conf"),
328                                                      {  "RID" : str(rid),
329                                                         "LDAPSERVER" : url,
330                                                         "MMR_PASSWORD": mmr_pass})
331             
332             olc_syncrepl_seed_config += read_and_sub_file(setup_path("olc_syncrepl_seed.conf"),
333                                                           {  "RID" : str(rid),
334                                                              "LDAPSERVER" : url})
335                 
336         setup_file(setup_path("olc_seed.ldif"), result.paths.olcseedldif,
337                    {"OLC_SERVER_ID_CONF": olc_serverids_config,
338                     "OLC_PW": ldapadminpass,
339                     "OLC_SYNCREPL_CONF": olc_syncrepl_seed_config})
340     # end olc
341                 
342     setup_file(setup_path("slapd.conf"), result.paths.slapdconf,
343                {"DNSDOMAIN": names.dnsdomain,
344                 "LDAPDIR": result.paths.ldapdir,
345                 "DOMAINDN": names.domaindn,
346                 "CONFIGDN": names.configdn,
347                 "SCHEMADN": names.schemadn,
348                 "MEMBEROF_CONFIG": memberof_config,
349                 "MIRRORMODE": mmr_on_config,
350                 "REPLICATOR_ACL": mmr_replicator_acl,
351                 "MMR_SERVERIDS_CONFIG": mmr_serverids_config,
352                 "MMR_SYNCREPL_SCHEMA_CONFIG": mmr_syncrepl_schema_config,
353                 "MMR_SYNCREPL_CONFIG_CONFIG": mmr_syncrepl_config_config,
354                 "MMR_SYNCREPL_USER_CONFIG": mmr_syncrepl_user_config,
355                 "OLC_SYNCREPL_CONFIG": olc_syncrepl_config,
356                 "OLC_MMR_CONFIG": olc_mmr_config,
357                 "REFINT_CONFIG": refint_config,
358                 "INDEX_CONFIG": index_config,
359                 "NOSYNC": nosync_config})
360         
361     setup_db_config(setup_path, os.path.join(result.paths.ldapdir, "db", "user"))
362     setup_db_config(setup_path, os.path.join(result.paths.ldapdir, "db", "config"))
363     setup_db_config(setup_path, os.path.join(result.paths.ldapdir, "db", "schema"))
364     
365     if not os.path.exists(os.path.join(result.paths.ldapdir, "db", "samba",  "cn=samba")):
366         os.makedirs(os.path.join(result.paths.ldapdir, "db", "samba",  "cn=samba"), 0700)
367         
368     setup_file(setup_path("cn=samba.ldif"), 
369                os.path.join(result.paths.ldapdir, "db", "samba",  "cn=samba.ldif"),
370                { "UUID": str(uuid.uuid4()), 
371                  "LDAPTIME": timestring(int(time.time()))} )
372     setup_file(setup_path("cn=samba-admin.ldif"), 
373                os.path.join(result.paths.ldapdir, "db", "samba",  "cn=samba", "cn=samba-admin.ldif"),
374                {"LDAPADMINPASS_B64": b64encode(ldapadminpass),
375                 "UUID": str(uuid.uuid4()), 
376                 "LDAPTIME": timestring(int(time.time()))} )
377     
378     if ol_mmr_urls is not None:
379         setup_file(setup_path("cn=replicator.ldif"),
380                    os.path.join(result.paths.ldapdir, "db", "samba",  "cn=samba", "cn=replicator.ldif"),
381                    {"MMR_PASSWORD_B64": b64encode(mmr_pass),
382                     "UUID": str(uuid.uuid4()),
383                     "LDAPTIME": timestring(int(time.time()))} )
384         
385
386     mapping = "schema-map-openldap-2.3"
387     backend_schema = "backend-schema.schema"
388
389     backend_schema_data = schema.ldb.convert_schema_to_openldap("openldap", open(setup_path(mapping), 'r').read())
390     assert backend_schema_data is not None
391     open(os.path.join(result.paths.ldapdir, backend_schema), 'w').write(backend_schema_data)
392
393     # now we generate the needed strings to start slapd automatically,
394     # first ldapi_uri...
395     if ldap_backend_extra_port is not None:
396         # When we use MMR, we can't use 0.0.0.0 as it uses the name
397         # specified there as part of it's clue as to it's own name,
398         # and not to replicate to itself
399         if ol_mmr_urls is None:
400             server_port_string = "ldap://0.0.0.0:%d" % ldap_backend_extra_port
401         else:
402             server_port_string = "ldap://" + names.hostname + "." + names.dnsdomain +":%d" % ldap_backend_extra_port
403     else:
404         server_port_string = ""
405
406     # Prepare the 'result' information - the commands to return in particular
407     result.slapd_provision_command = [slapd_path]
408
409     result.slapd_provision_command.append("-F" + result.paths.olcdir)
410
411     result.slapd_provision_command.append("-h")
412
413     # copy this command so we have two version, one with -d0 and only ldapi, and one with all the listen commands
414     result.slapd_command = list(result.slapd_provision_command)
415     
416     result.slapd_provision_command.append(result.ldapi_uri)
417     result.slapd_provision_command.append("-d0")
418
419     uris = result.ldapi_uri
420     if server_port_string is not "":
421         uris = uris + " " + server_port_string
422
423     result.slapd_command.append(uris)
424
425     # Set the username - done here because Fedora DS still uses the admin DN and simple bind
426     result.credentials.set_username("samba-admin")
427     
428     # If we were just looking for crashes up to this point, it's a
429     # good time to exit before we realise we don't have OpenLDAP on
430     # this system
431     if ldap_dryrun_mode:
432         sys.exit(0)
433
434     # Finally, convert the configuration into cn=config style!
435     if not os.path.isdir(result.paths.olcdir):
436         os.makedirs(result.paths.olcdir, 0770)
437
438         retcode = subprocess.call([slapd_path, "-Ttest", "-f", result.paths.slapdconf, "-F", result.paths.olcdir], close_fds=True, shell=False)
439
440 #        We can't do this, as OpenLDAP is strange.  It gives an error
441 #        output to the above, but does the conversion sucessfully...
442 #
443 #        if retcode != 0:
444 #            raise ProvisioningError("conversion from slapd.conf to cn=config failed")
445
446         if not os.path.exists(os.path.join(result.paths.olcdir, "cn=config.ldif")):
447             raise ProvisioningError("conversion from slapd.conf to cn=config failed")
448
449         # Don't confuse the admin by leaving the slapd.conf around
450         os.remove(result.paths.slapdconf)        
451
452
453 def provision_fds_backend(result, setup_path=None, names=None,
454                           message=None, 
455                           hostname=None, ldapadminpass=None, root=None, 
456                           schema=None,
457                           ldap_backend_extra_port=None,
458                           setup_ds_path=None,
459                           slapd_path=None,
460                           nosync=False, 
461                           ldap_dryrun_mode=False,
462                           domainsid=None):
463
464     if ldap_backend_extra_port is not None:
465         serverport = "ServerPort=%d" % ldap_backend_extra_port
466     else:
467         serverport = ""
468         
469     setup_file(setup_path("fedorads.inf"), result.paths.fedoradsinf, 
470                {"ROOT": root,
471                 "HOSTNAME": hostname,
472                 "DNSDOMAIN": names.dnsdomain,
473                 "LDAPDIR": result.paths.ldapdir,
474                 "DOMAINDN": names.domaindn,
475                 "LDAPMANAGERDN": names.ldapmanagerdn,
476                 "LDAPMANAGERPASS": ldapadminpass, 
477                 "SERVERPORT": serverport})
478
479     setup_file(setup_path("fedorads-partitions.ldif"), result.paths.fedoradspartitions, 
480                {"CONFIGDN": names.configdn,
481                 "SCHEMADN": names.schemadn,
482                 "SAMBADN": names.sambadn,
483                 })
484
485     setup_file(setup_path("fedorads-sasl.ldif"), result.paths.fedoradssasl, 
486                {"SAMBADN": names.sambadn,
487                 })
488
489     setup_file(setup_path("fedorads-dna.ldif"), result.paths.fedoradsdna, 
490                {"DOMAINDN": names.domaindn,
491                 "SAMBADN": names.sambadn,
492                 "DOMAINSID": str(domainsid),
493                 })
494
495     setup_file(setup_path("fedorads-pam.ldif"), result.paths.fedoradspam)
496
497     lnkattr = schema.linked_attributes()
498
499     refint_config = data = open(setup_path("fedorads-refint-delete.ldif"), 'r').read()
500     memberof_config = ""
501     index_config = ""
502     argnum = 3
503
504     for attr in lnkattr.keys():
505         if lnkattr[attr] is not None:
506             refint_config += read_and_sub_file(setup_path("fedorads-refint-add.ldif"),
507                                                  { "ARG_NUMBER" : str(argnum) ,
508                                                    "LINK_ATTR" : attr })
509             memberof_config += read_and_sub_file(setup_path("fedorads-linked-attributes.ldif"),
510                                                  { "MEMBER_ATTR" : attr ,
511                                                    "MEMBEROF_ATTR" : lnkattr[attr] })
512             index_config += read_and_sub_file(setup_path("fedorads-index.ldif"),
513                                                  { "ATTR" : attr })
514             argnum += 1
515
516     open(result.paths.fedoradsrefint, 'w').write(refint_config)
517     open(result.paths.fedoradslinkedattributes, 'w').write(memberof_config)
518
519     attrs = ["lDAPDisplayName"]
520     res = schema.ldb.search(expression="(&(objectclass=attributeSchema)(searchFlags:1.2.840.113556.1.4.803:=1))", base=names.schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
521
522     for i in range (0, len(res)):
523         attr = res[i]["lDAPDisplayName"][0]
524
525         if attr == "objectGUID":
526             attr = "nsUniqueId"
527
528         index_config += read_and_sub_file(setup_path("fedorads-index.ldif"),
529                                              { "ATTR" : attr })
530
531     open(result.paths.fedoradsindex, 'w').write(index_config)
532
533     setup_file(setup_path("fedorads-samba.ldif"), result.paths.fedoradssamba,
534                 {"SAMBADN": names.sambadn, 
535                  "LDAPADMINPASS": ldapadminpass
536                 })
537
538     mapping = "schema-map-fedora-ds-1.0"
539     backend_schema = "99_ad.ldif"
540     
541     # Build a schema file in Fedora DS format
542     backend_schema_data = schema.ldb.convert_schema_to_openldap("fedora-ds", open(setup_path(mapping), 'r').read())
543     assert backend_schema_data is not None
544     open(os.path.join(result.paths.ldapdir, backend_schema), 'w').write(backend_schema_data)
545
546     result.credentials.set_bind_dn(names.ldapmanagerdn)
547
548     # Destory the target directory, or else setup-ds.pl will complain
549     fedora_ds_dir = os.path.join(result.paths.ldapdir, "slapd-samba4")
550     shutil.rmtree(fedora_ds_dir, True)
551
552     result.slapd_provision_command = [slapd_path, "-D", fedora_ds_dir, "-i", result.paths.slapdpid];
553     #In the 'provision' command line, stay in the foreground so we can easily kill it
554     result.slapd_provision_command.append("-d0")
555
556     #the command for the final run is the normal script
557     result.slapd_command = [os.path.join(result.paths.ldapdir, "slapd-samba4", "start-slapd")]
558
559     # If we were just looking for crashes up to this point, it's a
560     # good time to exit before we realise we don't have Fedora DS on
561     if ldap_dryrun_mode:
562         sys.exit(0)
563
564     # Try to print helpful messages when the user has not specified the path to the setup-ds tool
565     if setup_ds_path is None:
566         raise ProvisioningError("Warning: Fedora DS LDAP-Backend must be setup with path to setup-ds, e.g. --setup-ds-path=\"/usr/sbin/setup-ds.pl\"!")
567     if not os.path.exists(setup_ds_path):
568         message (setup_ds_path)
569         raise ProvisioningError("Warning: Given Path to slapd does not exist!")
570
571     # Run the Fedora DS setup utility
572     retcode = subprocess.call([setup_ds_path, "--silent", "--file", result.paths.fedoradsinf], close_fds=True, shell=False)
573     if retcode != 0:
574         raise ProvisioningError("setup-ds failed")
575
576     # Load samba-admin
577     retcode = subprocess.call([
578         os.path.join(result.paths.ldapdir, "slapd-samba4", "ldif2db"), "-s", names.sambadn, "-i", result.paths.fedoradssamba],
579         close_fds=True, shell=False)
580     if retcode != 0:
581         raise("ldib2db failed")
582
583     # Leave a hook to do the 'post initilisation' setup
584     def fds_post_setup(self):
585         ldapi_db = Ldb(self.ldapi_uri, credentials=self.credentials)
586
587         # delete default SASL mappings
588         res = ldapi_db.search(expression="(!(cn=samba-admin mapping))", base="cn=mapping,cn=sasl,cn=config", scope=SCOPE_ONELEVEL, attrs=["dn"])
589     
590         # configure in-directory access control on Fedora DS via the aci attribute (over a direct ldapi:// socket)
591         for i in range (0, len(res)):
592             dn = str(res[i]["dn"])
593             ldapi_db.delete(dn)
594             
595             aci = """(targetattr = "*") (version 3.0;acl "full access to all by samba-admin";allow (all)(userdn = "ldap:///CN=samba-admin,%s");)""" % names.sambadn
596         
597             m = ldb.Message()
598             m["aci"] = ldb.MessageElement([aci], ldb.FLAG_MOD_REPLACE, "aci")
599
600             m.dn = ldb.Dn(1, names.domaindn)
601             ldapi_db.modify(m)
602             
603             m.dn = ldb.Dn(1, names.configdn)
604             ldapi_db.modify(m)
605             
606             m.dn = ldb.Dn(1, names.schemadn)
607             ldapi_db.modify(m)
608             
609     result.post_setup = fds_post_setup
610     
611