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