s4:provision: add get_empty_descriptor()
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / __init__.py
blobcd2a309fc0aea445139081ec4e2117fd1b95bea0
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
4 # Based on the original in EJS:
5 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 """Samba 4."""
23 __docformat__ = "restructuredText"
25 import os
26 import sys
27 import samba.param
30 def source_tree_topdir():
31 """Return the top level source directory."""
32 paths = ["../../..", "../../../.."]
33 for p in paths:
34 topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
35 if os.path.exists(os.path.join(topdir, 'source4')):
36 return topdir
37 raise RuntimeError("unable to find top level source directory")
40 def in_source_tree():
41 """Return True if we are running from within the samba source tree"""
42 try:
43 topdir = source_tree_topdir()
44 except RuntimeError:
45 return False
46 return True
49 import ldb
50 from samba._ldb import Ldb as _Ldb
53 class Ldb(_Ldb):
54 """Simple Samba-specific LDB subclass that takes care
55 of setting up the modules dir, credentials pointers, etc.
57 Please note that this is intended to be for all Samba LDB files,
58 not necessarily the Sam database. For Sam-specific helper
59 functions see samdb.py.
60 """
62 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
63 credentials=None, flags=0, options=None):
64 """Opens a Samba Ldb file.
66 :param url: Optional LDB URL to open
67 :param lp: Optional loadparm object
68 :param modules_dir: Optional modules directory
69 :param session_info: Optional session information
70 :param credentials: Optional credentials, defaults to anonymous.
71 :param flags: Optional LDB flags
72 :param options: Additional options (optional)
74 This is different from a regular Ldb file in that the Samba-specific
75 modules-dir is used by default and that credentials and session_info
76 can be passed through (required by some modules).
77 """
79 if modules_dir is not None:
80 self.set_modules_dir(modules_dir)
81 else:
82 self.set_modules_dir(os.path.join(samba.param.modules_dir(), "ldb"))
84 if session_info is not None:
85 self.set_session_info(session_info)
87 if credentials is not None:
88 self.set_credentials(credentials)
90 if lp is not None:
91 self.set_loadparm(lp)
93 # This must be done before we load the schema, as these handlers for
94 # objectSid and objectGUID etc must take precedence over the 'binary
95 # attribute' declaration in the schema
96 self.register_samba_handlers()
98 # TODO set debug
99 def msg(l, text):
100 print text
101 #self.set_debug(msg)
103 self.set_utf8_casefold()
105 # Allow admins to force non-sync ldb for all databases
106 if lp is not None:
107 nosync_p = lp.get("nosync", "ldb")
108 if nosync_p is not None and nosync_p:
109 flags |= ldb.FLG_NOSYNC
111 self.set_create_perms(0600)
113 if url is not None:
114 self.connect(url, flags, options)
116 def searchone(self, attribute, basedn=None, expression=None,
117 scope=ldb.SCOPE_BASE):
118 """Search for one attribute as a string.
120 :param basedn: BaseDN for the search.
121 :param attribute: Name of the attribute
122 :param expression: Optional search expression.
123 :param scope: Search scope (defaults to base).
124 :return: Value of attribute as a string or None if it wasn't found.
126 res = self.search(basedn, scope, expression, [attribute])
127 if len(res) != 1 or res[0][attribute] is None:
128 return None
129 values = set(res[0][attribute])
130 assert len(values) == 1
131 return self.schema_format_value(attribute, values.pop())
133 def erase_users_computers(self, dn):
134 """Erases user and computer objects from our AD.
136 This is needed since the 'samldb' module denies the deletion of primary
137 groups. Therefore all groups shouldn't be primary somewhere anymore.
140 try:
141 res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
142 expression="(|(objectclass=user)(objectclass=computer))")
143 except ldb.LdbError, (errno, _):
144 if errno == ldb.ERR_NO_SUCH_OBJECT:
145 # Ignore no such object errors
146 return
147 else:
148 raise
150 try:
151 for msg in res:
152 self.delete(msg.dn, ["relax:0"])
153 except ldb.LdbError, (errno, _):
154 if errno != ldb.ERR_NO_SUCH_OBJECT:
155 # Ignore no such object errors
156 raise
158 def erase_except_schema_controlled(self):
159 """Erase this ldb.
161 :note: Removes all records, except those that are controlled by
162 Samba4's schema.
165 basedn = ""
167 # Try to delete user/computer accounts to allow deletion of groups
168 self.erase_users_computers(basedn)
170 # Delete the 'visible' records, and the invisble 'deleted' records (if
171 # this DB supports it)
172 for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
173 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
174 [], controls=["show_deleted:0", "show_recycled:0"]):
175 try:
176 self.delete(msg.dn, ["relax:0"])
177 except ldb.LdbError, (errno, _):
178 if errno != ldb.ERR_NO_SUCH_OBJECT:
179 # Ignore no such object errors
180 raise
182 res = self.search(basedn, ldb.SCOPE_SUBTREE,
183 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
184 [], controls=["show_deleted:0", "show_recycled:0"])
185 assert len(res) == 0
187 # delete the specials
188 for attr in ["@SUBCLASSES", "@MODULES",
189 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
190 try:
191 self.delete(attr, ["relax:0"])
192 except ldb.LdbError, (errno, _):
193 if errno != ldb.ERR_NO_SUCH_OBJECT:
194 # Ignore missing dn errors
195 raise
197 def erase(self):
198 """Erase this ldb, removing all records."""
199 self.erase_except_schema_controlled()
201 # delete the specials
202 for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
203 try:
204 self.delete(attr, ["relax:0"])
205 except ldb.LdbError, (errno, _):
206 if errno != ldb.ERR_NO_SUCH_OBJECT:
207 # Ignore missing dn errors
208 raise
210 def load_ldif_file_add(self, ldif_path):
211 """Load a LDIF file.
213 :param ldif_path: Path to LDIF file.
215 self.add_ldif(open(ldif_path, 'r').read())
217 def add_ldif(self, ldif, controls=None):
218 """Add data based on a LDIF string.
220 :param ldif: LDIF text.
222 for changetype, msg in self.parse_ldif(ldif):
223 assert changetype == ldb.CHANGETYPE_NONE
224 self.add(msg, controls)
226 def modify_ldif(self, ldif, controls=None):
227 """Modify database based on a LDIF string.
229 :param ldif: LDIF text.
231 for changetype, msg in self.parse_ldif(ldif):
232 if changetype == ldb.CHANGETYPE_ADD:
233 self.add(msg, controls)
234 else:
235 self.modify(msg, controls)
238 def substitute_var(text, values):
239 """Substitute strings of the form ${NAME} in str, replacing
240 with substitutions from values.
242 :param text: Text in which to subsitute.
243 :param values: Dictionary with keys and values.
246 for (name, value) in values.items():
247 assert isinstance(name, str), "%r is not a string" % name
248 assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
249 text = text.replace("${%s}" % name, value)
251 return text
254 def check_all_substituted(text):
255 """Check that all substitution variables in a string have been replaced.
257 If not, raise an exception.
259 :param text: The text to search for substitution variables
261 if not "${" in text:
262 return
264 var_start = text.find("${")
265 var_end = text.find("}", var_start)
267 raise Exception("Not all variables substituted: %s" %
268 text[var_start:var_end+1])
271 def read_and_sub_file(file_name, subst_vars):
272 """Read a file and sub in variables found in it
274 :param file_name: File to be read (typically from setup directory)
275 param subst_vars: Optional variables to subsitute in the file.
277 data = open(file_name, 'r').read()
278 if subst_vars is not None:
279 data = substitute_var(data, subst_vars)
280 check_all_substituted(data)
281 return data
284 def setup_file(template, fname, subst_vars=None):
285 """Setup a file in the private dir.
287 :param template: Path of the template file.
288 :param fname: Path of the file to create.
289 :param subst_vars: Substitution variables.
291 if os.path.exists(fname):
292 os.unlink(fname)
294 data = read_and_sub_file(template, subst_vars)
295 f = open(fname, 'w')
296 try:
297 f.write(data)
298 finally:
299 f.close()
301 MAX_NETBIOS_NAME_LEN = 15
302 def is_valid_netbios_char(c):
303 return (c.isalnum() or c in " !#$%&'()-.@^_{}~")
306 def valid_netbios_name(name):
307 """Check whether a name is valid as a NetBIOS name. """
308 # See crh's book (1.4.1.1)
309 if len(name) > MAX_NETBIOS_NAME_LEN:
310 return False
311 for x in name:
312 if not is_valid_netbios_char(x):
313 return False
314 return True
317 def import_bundled_package(modulename, location):
318 """Import the bundled version of a package.
320 :note: This should only be called if the system version of the package
321 is not adequate.
323 :param modulename: Module name to import
324 :param location: Location to add to sys.path (can be relative to
325 ${srcdir}/lib)
327 if in_source_tree():
328 sys.path.insert(0, os.path.join(source_tree_topdir(), "lib", location))
329 sys.modules[modulename] = __import__(modulename)
330 else:
331 sys.modules[modulename] = __import__(
332 "samba.external.%s" % modulename, fromlist=["samba.external"])
335 def ensure_external_module(modulename, location):
336 """Add a location to sys.path if an external dependency can't be found.
338 :param modulename: Module name to import
339 :param location: Location to add to sys.path (can be relative to
340 ${srcdir}/lib)
342 try:
343 __import__(modulename)
344 except ImportError:
345 import_bundled_package(modulename, location)
348 def dn_from_dns_name(dnsdomain):
349 """return a DN from a DNS name domain/forest root"""
350 return "DC=" + ",DC=".join(dnsdomain.split("."))
352 import _glue
353 version = _glue.version
354 interface_ips = _glue.interface_ips
355 set_debug_level = _glue.set_debug_level
356 get_debug_level = _glue.get_debug_level
357 unix2nttime = _glue.unix2nttime
358 nttime2string = _glue.nttime2string
359 nttime2unix = _glue.nttime2unix
360 unix2nttime = _glue.unix2nttime
361 generate_random_password = _glue.generate_random_password
362 strcasecmp_m = _glue.strcasecmp_m
363 strstr_m = _glue.strstr_m