pydsdb: Move write_prefixes_from_schema_to_ldb to pydsdb from pyglue.
[kai/samba-autobuild/.git] / source4 / scripting / python / samba / __init__.py
1 #!/usr/bin/python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
5 #
6 # Based on the original in EJS:
7 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 """Samba 4."""
24
25 __docformat__ = "restructuredText"
26
27 import os
28 import sys
29
30 def _in_source_tree():
31     """Check whether the script is being run from the source dir. """
32     return os.path.exists("%s/../../../selftest/skip" % os.path.dirname(__file__))
33
34
35 # When running, in-tree, make sure bin/python is in the PYTHONPATH
36 if _in_source_tree():
37     srcdir = "%s/../../.." % os.path.dirname(__file__)
38     sys.path.append("%s/bin/python" % srcdir)
39     default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir
40 else:
41     default_ldb_modules_dir = None
42
43
44 import ldb
45 import dsdb
46 import _glue
47 from samba._ldb import Ldb as _Ldb
48
49 class Ldb(_Ldb):
50     """Simple Samba-specific LDB subclass that takes care
51     of setting up the modules dir, credentials pointers, etc.
52
53     Please note that this is intended to be for all Samba LDB files,
54     not necessarily the Sam database. For Sam-specific helper
55     functions see samdb.py.
56     """
57     def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
58                  credentials=None, flags=0, options=None):
59         """Opens a Samba Ldb file.
60
61         :param url: Optional LDB URL to open
62         :param lp: Optional loadparm object
63         :param modules_dir: Optional modules directory
64         :param session_info: Optional session information
65         :param credentials: Optional credentials, defaults to anonymous.
66         :param flags: Optional LDB flags
67         :param options: Additional options (optional)
68
69         This is different from a regular Ldb file in that the Samba-specific
70         modules-dir is used by default and that credentials and session_info
71         can be passed through (required by some modules).
72         """
73
74         if modules_dir is not None:
75             self.set_modules_dir(modules_dir)
76         elif default_ldb_modules_dir is not None:
77             self.set_modules_dir(default_ldb_modules_dir)
78         elif lp is not None:
79             self.set_modules_dir(os.path.join(lp.get("modules dir"), "ldb"))
80
81         if session_info is not None:
82             self.set_session_info(session_info)
83
84         if credentials is not None:
85             self.set_credentials(credentials)
86
87         if lp is not None:
88             self.set_loadparm(lp)
89
90         # This must be done before we load the schema, as these handlers for
91         # objectSid and objectGUID etc must take precedence over the 'binary
92         # attribute' declaration in the schema
93         self.register_samba_handlers()
94
95         # TODO set debug
96         def msg(l,text):
97             print text
98         #self.set_debug(msg)
99
100         self.set_utf8_casefold()
101
102         # Allow admins to force non-sync ldb for all databases
103         if lp is not None:
104             nosync_p = lp.get("nosync", "ldb")
105             if nosync_p is not None and nosync_p == True:
106                 flags |= ldb.FLG_NOSYNC
107
108         self.set_create_perms()
109
110         if url is not None:
111             self.connect(url, flags, options)
112
113     def set_create_perms(self, perms=0600):
114         # we usually want Samba databases to be private. If we later find we
115         # need one public, we will have to change this here
116         super(Ldb, self).set_create_perms(perms)
117
118     def searchone(self, attribute, basedn=None, expression=None,
119                   scope=ldb.SCOPE_BASE):
120         """Search for one attribute as a string.
121
122         :param basedn: BaseDN for the search.
123         :param attribute: Name of the attribute
124         :param expression: Optional search expression.
125         :param scope: Search scope (defaults to base).
126         :return: Value of attribute as a string or None if it wasn't found.
127         """
128         res = self.search(basedn, scope, expression, [attribute])
129         if len(res) != 1 or res[0][attribute] is None:
130             return None
131         values = set(res[0][attribute])
132         assert len(values) == 1
133         return self.schema_format_value(attribute, values.pop())
134
135     def erase_users_computers(self, dn):
136         """Erases user and computer objects from our AD. This is needed since the 'samldb' module denies the deletion of primary groups. Therefore all groups shouldn't be primary somewhere anymore."""
137
138         try:
139             res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
140                       expression="(|(objectclass=user)(objectclass=computer))")
141         except ldb.LdbError, (errno, _):
142             if errno == ldb.ERR_NO_SUCH_OBJECT:
143                 # Ignore no such object errors
144                 return
145             else:
146                 raise
147
148         try:
149             for msg in res:
150                 self.delete(msg.dn, ["relax:0"])
151         except ldb.LdbError, (errno, _):
152             if errno != ldb.ERR_NO_SUCH_OBJECT:
153                 # Ignore no such object errors
154                 raise
155
156     def erase_except_schema_controlled(self):
157         """Erase this ldb.
158         
159         :note: Removes all records, except those that are controlled by
160             Samba4's schema.
161         """
162
163         basedn = ""
164
165         # Try to delete user/computer accounts to allow deletion of groups
166         self.erase_users_computers(basedn)
167
168         # Delete the 'visible' records, and the invisble 'deleted' records (if this DB supports it)
169         for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
170                                "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
171                                [], controls=["show_deleted:0"]):
172             try:
173                 self.delete(msg.dn, ["relax:0"])
174             except ldb.LdbError, (errno, _):
175                 if errno != ldb.ERR_NO_SUCH_OBJECT:
176                     # Ignore no such object errors
177                     raise
178
179         res = self.search(basedn, ldb.SCOPE_SUBTREE,
180             "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", [], controls=["show_deleted:0"])
181         assert len(res) == 0
182
183         # delete the specials
184         for attr in ["@SUBCLASSES", "@MODULES",
185                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
186             try:
187                 self.delete(attr, ["relax:0"])
188             except ldb.LdbError, (errno, _):
189                 if errno != ldb.ERR_NO_SUCH_OBJECT:
190                     # Ignore missing dn errors
191                     raise
192
193     def erase(self):
194         """Erase this ldb, removing all records."""
195
196         self.erase_except_schema_controlled()
197
198         # delete the specials
199         for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
200             try:
201                 self.delete(attr, ["relax:0"])
202             except ldb.LdbError, (errno, _):
203                 if errno != ldb.ERR_NO_SUCH_OBJECT:
204                     # Ignore missing dn errors
205                     raise
206
207     def erase_partitions(self):
208         """Erase an ldb, removing all records."""
209
210         def erase_recursive(self, dn):
211             try:
212                 res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[],
213                                   controls=["show_deleted:0"])
214             except ldb.LdbError, (errno, _):
215                 if errno == ldb.ERR_NO_SUCH_OBJECT:
216                     # Ignore no such object errors
217                     return
218
219             for msg in res:
220                 erase_recursive(self, msg.dn)
221
222             try:
223                 self.delete(dn, ["relax:0"])
224             except ldb.LdbError, (errno, _):
225                 if errno != ldb.ERR_NO_SUCH_OBJECT:
226                     # Ignore no such object errors
227                     raise
228
229         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)",
230                          ["namingContexts"])
231         assert len(res) == 1
232         if not "namingContexts" in res[0]:
233             return
234         for basedn in res[0]["namingContexts"]:
235             # Try to delete user/computer accounts to allow deletion of groups
236             self.erase_users_computers(basedn)
237             # Try and erase from the bottom-up in the tree
238             erase_recursive(self, basedn)
239
240     def load_ldif_file_add(self, ldif_path):
241         """Load a LDIF file.
242
243         :param ldif_path: Path to LDIF file.
244         """
245         self.add_ldif(open(ldif_path, 'r').read())
246
247     def add_ldif(self, ldif, controls=None):
248         """Add data based on a LDIF string.
249
250         :param ldif: LDIF text.
251         """
252         for changetype, msg in self.parse_ldif(ldif):
253             assert changetype == ldb.CHANGETYPE_NONE
254             self.add(msg,controls)
255
256     def modify_ldif(self, ldif, controls=None):
257         """Modify database based on a LDIF string.
258
259         :param ldif: LDIF text.
260         """
261         for changetype, msg in self.parse_ldif(ldif):
262             if (changetype == ldb.CHANGETYPE_ADD):
263                 self.add(msg, controls)
264             else:
265                 self.modify(msg, controls)
266
267     def set_domain_sid(self, sid):
268         """Change the domain SID used by this LDB.
269
270         :param sid: The new domain sid to use.
271         """
272         dsdb.samdb_set_domain_sid(self, sid)
273
274     def domain_sid(self):
275         """Read the domain SID used by this LDB.
276
277         """
278         dsdb.samdb_get_domain_sid(self)
279
280     def set_schema_from_ldif(self, pf, df):
281         dsdb.dsdb_set_schema_from_ldif(self, pf, df)
282
283     def get_oid_from_attid(self, attid):
284         return dsdb.dsdb_get_oid_from_attid(self, attid)
285
286     def set_schema_from_ldb(self, ldb):
287         dsdb.dsdb_set_schema_from_ldb(self, ldb)
288
289     def write_prefixes_from_schema(self):
290         dsdb.dsdb_write_prefixes_from_schema_to_ldb(self)
291
292     def convert_schema_to_openldap(self, target, mapping):
293         return dsdb.dsdb_convert_schema_to_openldap(self, target, mapping)
294
295     def set_invocation_id(self, invocation_id):
296         """Set the invocation id for this SamDB handle.
297
298         :param invocation_id: GUID of the invocation id.
299         """
300         dsdb.dsdb_set_ntds_invocation_id(self, invocation_id)
301
302     def get_invocation_id(self):
303         """Get the invocation_id id"""
304         return dsdb.samdb_ntds_invocation_id(self)
305
306     def get_ntds_GUID(self):
307         """Get the NTDS objectGUID"""
308         return dsdb.samdb_ntds_objectGUID(self)
309
310     def server_site_name(self):
311         """Get the server site name"""
312         return dsdb.samdb_server_site_name(self)
313
314
315 def substitute_var(text, values):
316     """Substitute strings of the form ${NAME} in str, replacing
317     with substitutions from subobj.
318
319     :param text: Text in which to subsitute.
320     :param values: Dictionary with keys and values.
321     """
322
323     for (name, value) in values.items():
324         assert isinstance(name, str), "%r is not a string" % name
325         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
326         text = text.replace("${%s}" % name, value)
327
328     return text
329
330
331 def check_all_substituted(text):
332     """Make sure that all substitution variables in a string have been replaced.
333     If not, raise an exception.
334
335     :param text: The text to search for substitution variables
336     """
337     if not "${" in text:
338         return
339
340     var_start = text.find("${")
341     var_end = text.find("}", var_start)
342
343     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
344
345
346 def read_and_sub_file(file, subst_vars):
347     """Read a file and sub in variables found in it
348
349     :param file: File to be read (typically from setup directory)
350      param subst_vars: Optional variables to subsitute in the file.
351     """
352     data = open(file, 'r').read()
353     if subst_vars is not None:
354         data = substitute_var(data, subst_vars)
355         check_all_substituted(data)
356     return data
357
358
359 def setup_file(template, fname, subst_vars=None):
360     """Setup a file in the private dir.
361
362     :param template: Path of the template file.
363     :param fname: Path of the file to create.
364     :param subst_vars: Substitution variables.
365     """
366     if os.path.exists(fname):
367         os.unlink(fname)
368
369     data = read_and_sub_file(template, subst_vars)
370     f = open(fname, 'w')
371     try:
372         f.write(data)
373     finally:
374         f.close()
375
376
377 def valid_netbios_name(name):
378     """Check whether a name is valid as a NetBIOS name. """
379     # See crh's book (1.4.1.1)
380     if len(name) > 15:
381         return False
382     for x in name:
383         if not x.isalnum() and not x in " !#$%&'()-.@^_{}~":
384             return False
385     return True
386
387
388 def ensure_external_module(modulename, location):
389     """Add a location to sys.path if an external dependency can't be found.
390
391     :param modulename: Module name to import
392     :param location: Location to add to sys.path (can be relative to 
393         ${srcdir}/lib
394     """
395     try:
396         __import__(modulename)
397     except ImportError:
398         import sys
399         if _in_source_tree():
400             sys.path.insert(0, 
401                 os.path.join(os.path.dirname(__file__),
402                              "../../../../lib", location))
403             __import__(modulename)
404         else:
405             sys.modules[modulename] = __import__(
406                 "samba.external.%s" % modulename, fromlist=["samba.external"])
407
408 version = _glue.version
409 interface_ips = _glue.interface_ips
410 set_debug_level = _glue.set_debug_level
411 unix2nttime = _glue.unix2nttime
412 generate_random_password = _glue.generate_random_password