python: Remove unused imports
[Samba.git] / python / samba / __init__.py
blob6eb0d01d1cf9b63cae95c6a45b81c920635ec4f2
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 time
27 import ldb
28 import samba.param
29 from samba import _glue
30 from samba._ldb import Ldb as _Ldb
33 def source_tree_topdir():
34 """Return the top level source directory."""
35 paths = ["../../..", "../../../.."]
36 for p in paths:
37 topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
38 if os.path.exists(os.path.join(topdir, 'source4')):
39 return topdir
40 raise RuntimeError("unable to find top level source directory")
43 def in_source_tree():
44 """Return True if we are running from within the samba source tree"""
45 try:
46 topdir = source_tree_topdir()
47 except RuntimeError:
48 return False
49 return True
52 class Ldb(_Ldb):
53 """Simple Samba-specific LDB subclass that takes care
54 of setting up the modules dir, credentials pointers, etc.
56 Please note that this is intended to be for all Samba LDB files,
57 not necessarily the Sam database. For Sam-specific helper
58 functions see samdb.py.
59 """
61 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
62 credentials=None, flags=0, options=None):
63 """Opens a Samba Ldb file.
65 :param url: Optional LDB URL to open
66 :param lp: Optional loadparm object
67 :param modules_dir: Optional modules directory
68 :param session_info: Optional session information
69 :param credentials: Optional credentials, defaults to anonymous.
70 :param flags: Optional LDB flags
71 :param options: Additional options (optional)
73 This is different from a regular Ldb file in that the Samba-specific
74 modules-dir is used by default and that credentials and session_info
75 can be passed through (required by some modules).
76 """
78 if modules_dir is not None:
79 self.set_modules_dir(modules_dir)
80 else:
81 self.set_modules_dir(os.path.join(samba.param.modules_dir(), "ldb"))
83 if session_info is not None:
84 self.set_session_info(session_info)
86 if credentials is not None:
87 self.set_credentials(credentials)
89 if lp is not None:
90 self.set_loadparm(lp)
92 # This must be done before we load the schema, as these handlers for
93 # objectSid and objectGUID etc must take precedence over the 'binary
94 # attribute' declaration in the schema
95 self.register_samba_handlers()
97 # TODO set debug
98 def msg(l, text):
99 print(text)
100 # self.set_debug(msg)
102 self.set_utf8_casefold()
104 # Allow admins to force non-sync ldb for all databases
105 if lp is not None:
106 nosync_p = lp.get("ldb:nosync")
107 if nosync_p is not None and nosync_p:
108 flags |= ldb.FLG_NOSYNC
110 self.set_create_perms(0o600)
112 if url is not None:
113 self.connect(url, flags, options)
115 def searchone(self, attribute, basedn=None, expression=None,
116 scope=ldb.SCOPE_BASE):
117 """Search for one attribute as a string.
119 :param basedn: BaseDN for the search.
120 :param attribute: Name of the attribute
121 :param expression: Optional search expression.
122 :param scope: Search scope (defaults to base).
123 :return: Value of attribute as a string or None if it wasn't found.
125 res = self.search(basedn, scope, expression, [attribute])
126 if len(res) != 1 or res[0][attribute] is None:
127 return None
128 values = set(res[0][attribute])
129 assert len(values) == 1
130 return self.schema_format_value(attribute, values.pop())
132 def erase_users_computers(self, dn):
133 """Erases user and computer objects from our AD.
135 This is needed since the 'samldb' module denies the deletion of primary
136 groups. Therefore all groups shouldn't be primary somewhere anymore.
139 try:
140 res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
141 expression="(|(objectclass=user)(objectclass=computer))")
142 except ldb.LdbError as error:
143 (errno, estr) = error.args
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 as error:
154 (errno, estr) = error.args
155 if errno != ldb.ERR_NO_SUCH_OBJECT:
156 # Ignore no such object errors
157 raise
159 def erase_except_schema_controlled(self):
160 """Erase this ldb.
162 :note: Removes all records, except those that are controlled by
163 Samba4's schema.
166 basedn = ""
168 # Try to delete user/computer accounts to allow deletion of groups
169 self.erase_users_computers(basedn)
171 # Delete the 'visible' records, and the invisible 'deleted' records (if
172 # this DB supports it)
173 for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
174 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
175 [], controls=["show_deleted:0", "show_recycled:0"]):
176 try:
177 self.delete(msg.dn, ["relax:0"])
178 except ldb.LdbError as error:
179 (errno, estr) = error.args
180 if errno != ldb.ERR_NO_SUCH_OBJECT:
181 # Ignore no such object errors
182 raise
184 res = self.search(basedn, ldb.SCOPE_SUBTREE,
185 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
186 [], controls=["show_deleted:0", "show_recycled:0"])
187 assert len(res) == 0
189 # delete the specials
190 for attr in ["@SUBCLASSES", "@MODULES",
191 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
192 try:
193 self.delete(attr, ["relax:0"])
194 except ldb.LdbError as error:
195 (errno, estr) = error.args
196 if errno != ldb.ERR_NO_SUCH_OBJECT:
197 # Ignore missing dn errors
198 raise
200 def erase(self):
201 """Erase this ldb, removing all records."""
202 self.erase_except_schema_controlled()
204 # delete the specials
205 for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
206 try:
207 self.delete(attr, ["relax:0"])
208 except ldb.LdbError as error:
209 (errno, estr) = error.args
210 if errno != ldb.ERR_NO_SUCH_OBJECT:
211 # Ignore missing dn errors
212 raise
214 def load_ldif_file_add(self, ldif_path):
215 """Load a LDIF file.
217 :param ldif_path: Path to LDIF file.
219 with open(ldif_path, 'r') as ldif_file:
220 self.add_ldif(ldif_file.read())
222 def add_ldif(self, ldif, controls=None):
223 """Add data based on a LDIF string.
225 :param ldif: LDIF text.
227 for changetype, msg in self.parse_ldif(ldif):
228 assert changetype == ldb.CHANGETYPE_NONE
229 self.add(msg, controls)
231 def modify_ldif(self, ldif, controls=None):
232 """Modify database based on a LDIF string.
234 :param ldif: LDIF text.
236 for changetype, msg in self.parse_ldif(ldif):
237 if changetype == ldb.CHANGETYPE_NONE:
238 changetype = ldb.CHANGETYPE_MODIFY
240 if changetype == ldb.CHANGETYPE_ADD:
241 self.add(msg, controls)
242 elif changetype == ldb.CHANGETYPE_MODIFY:
243 self.modify(msg, controls)
244 elif changetype == ldb.CHANGETYPE_DELETE:
245 deldn = msg
246 self.delete(deldn, controls)
247 elif changetype == ldb.CHANGETYPE_MODRDN:
248 olddn = msg["olddn"]
249 deleteoldrdn = msg["deleteoldrdn"]
250 newdn = msg["newdn"]
251 if deleteoldrdn is False:
252 raise ValueError("Invalid ldb.CHANGETYPE_MODRDN with deleteoldrdn=False")
253 self.rename(olddn, newdn, controls)
254 else:
255 raise ValueError("Invalid ldb.CHANGETYPE_%u: %s" % (changetype, msg))
258 def substitute_var(text, values):
259 """Substitute strings of the form ${NAME} in str, replacing
260 with substitutions from values.
262 :param text: Text in which to substitute.
263 :param values: Dictionary with keys and values.
266 for (name, value) in values.items():
267 assert isinstance(name, str), "%r is not a string" % name
268 assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
269 text = text.replace("${%s}" % name, value)
271 return text
274 def check_all_substituted(text):
275 """Check that all substitution variables in a string have been replaced.
277 If not, raise an exception.
279 :param text: The text to search for substitution variables
281 if "${" not in text:
282 return
284 var_start = text.find("${")
285 var_end = text.find("}", var_start)
287 raise Exception("Not all variables substituted: %s" %
288 text[var_start:var_end + 1])
291 def read_and_sub_file(file_name, subst_vars):
292 """Read a file and sub in variables found in it
294 :param file_name: File to be read (typically from setup directory)
295 param subst_vars: Optional variables to substitute in the file.
297 with open(file_name, 'r', encoding="utf-8") as data_file:
298 data = data_file.read()
299 if subst_vars is not None:
300 data = substitute_var(data, subst_vars)
301 check_all_substituted(data)
302 return data
305 def setup_file(template, fname, subst_vars=None):
306 """Setup a file in the private dir.
308 :param template: Path of the template file.
309 :param fname: Path of the file to create.
310 :param subst_vars: Substitution variables.
312 if os.path.exists(fname):
313 os.unlink(fname)
315 data = read_and_sub_file(template, subst_vars)
316 f = open(fname, 'w')
317 try:
318 f.write(data)
319 finally:
320 f.close()
323 MAX_NETBIOS_NAME_LEN = 15
326 def is_valid_netbios_char(c):
327 return (c.isalnum() or c in " !#$%&'()-.@^_{}~")
330 def valid_netbios_name(name):
331 """Check whether a name is valid as a NetBIOS name. """
332 # See crh's book (1.4.1.1)
333 if len(name) > MAX_NETBIOS_NAME_LEN:
334 return False
335 for x in name:
336 if not is_valid_netbios_char(x):
337 return False
338 return True
341 def dn_from_dns_name(dnsdomain):
342 """return a DN from a DNS name domain/forest root"""
343 return "DC=" + ",DC=".join(dnsdomain.split("."))
346 def current_unix_time():
347 return int(time.time())
350 def string_to_byte_array(string):
351 return [c if isinstance(c, int) else ord(c) for c in string]
354 def arcfour_encrypt(key, data):
355 from samba.crypto import arcfour_crypt_blob
356 return arcfour_crypt_blob(data, key)
359 def enable_net_export_keytab():
360 """This function modifies the samba.net.Net class to contain
361 an export_keytab() method."""
362 # This looks very strange because it is.
364 # The dckeytab modules contains nothing, but the act of importing
365 # it pushes a method into samba.net.Net. It ended up this way
366 # because Net.export_keytab() only works on Heimdal builds, and
367 # people sometimes want to compile Samba without Heimdal while
368 # still having a working samba-tool.
370 # There is probably a better way to do this than a magic module
371 # import (yes, that's a FIXME if you can be bothered).
372 from samba import net
373 from samba import dckeytab
376 version = _glue.version
377 interface_ips = _glue.interface_ips
378 fault_setup = _glue.fault_setup
379 set_debug_level = _glue.set_debug_level
380 get_debug_level = _glue.get_debug_level
381 float2nttime = _glue.float2nttime
382 nttime2float = _glue.nttime2float
383 nttime2string = _glue.nttime2string
384 nttime2unix = _glue.nttime2unix
385 unix2nttime = _glue.unix2nttime
386 generate_random_password = _glue.generate_random_password
387 generate_random_machine_password = _glue.generate_random_machine_password
388 check_password_quality = _glue.check_password_quality
389 generate_random_bytes = _glue.generate_random_bytes
390 strcasecmp_m = _glue.strcasecmp_m
391 strstr_m = _glue.strstr_m
392 is_ntvfs_fileserver_built = _glue.is_ntvfs_fileserver_built
393 is_heimdal_built = _glue.is_heimdal_built
394 is_ad_dc_built = _glue.is_ad_dc_built
395 is_selftest_enabled = _glue.is_selftest_enabled
397 NTSTATUSError = _glue.NTSTATUSError
398 HRESULTError = _glue.HRESULTError
399 WERRORError = _glue.WERRORError
400 DsExtendedError = _glue.DsExtendedError