ctdb-tests: add a comment to the generated public_addresses file used by eventscript...
[Samba.git] / python / samba / __init__.py
blob0e6a33322f8cae0b81611530867ce8a0228379f0
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 time
28 import ldb
29 import samba.param
30 from samba import _glue
31 from samba._ldb import Ldb as _Ldb
34 def source_tree_topdir():
35 """Return the top level source directory."""
36 paths = ["../../..", "../../../.."]
37 for p in paths:
38 topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
39 if os.path.exists(os.path.join(topdir, 'source4')):
40 return topdir
41 raise RuntimeError("unable to find top level source directory")
44 def in_source_tree():
45 """Return True if we are running from within the samba source tree"""
46 try:
47 topdir = source_tree_topdir()
48 except RuntimeError:
49 return False
50 return True
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("ldb:nosync")
108 if nosync_p is not None and nosync_p:
109 flags |= ldb.FLG_NOSYNC
111 self.set_create_perms(0o600)
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 as error:
144 (errno, estr) = error.args
145 if errno == ldb.ERR_NO_SUCH_OBJECT:
146 # Ignore no such object errors
147 return
148 else:
149 raise
151 try:
152 for msg in res:
153 self.delete(msg.dn, ["relax:0"])
154 except ldb.LdbError as error:
155 (errno, estr) = error.args
156 if errno != ldb.ERR_NO_SUCH_OBJECT:
157 # Ignore no such object errors
158 raise
160 def erase_except_schema_controlled(self):
161 """Erase this ldb.
163 :note: Removes all records, except those that are controlled by
164 Samba4's schema.
167 basedn = ""
169 # Try to delete user/computer accounts to allow deletion of groups
170 self.erase_users_computers(basedn)
172 # Delete the 'visible' records, and the invisble 'deleted' records (if
173 # this DB supports it)
174 for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
175 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
176 [], controls=["show_deleted:0", "show_recycled:0"]):
177 try:
178 self.delete(msg.dn, ["relax:0"])
179 except ldb.LdbError as error:
180 (errno, estr) = error.args
181 if errno != ldb.ERR_NO_SUCH_OBJECT:
182 # Ignore no such object errors
183 raise
185 res = self.search(basedn, ldb.SCOPE_SUBTREE,
186 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
187 [], controls=["show_deleted:0", "show_recycled:0"])
188 assert len(res) == 0
190 # delete the specials
191 for attr in ["@SUBCLASSES", "@MODULES",
192 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
193 try:
194 self.delete(attr, ["relax:0"])
195 except ldb.LdbError as error:
196 (errno, estr) = error.args
197 if errno != ldb.ERR_NO_SUCH_OBJECT:
198 # Ignore missing dn errors
199 raise
201 def erase(self):
202 """Erase this ldb, removing all records."""
203 self.erase_except_schema_controlled()
205 # delete the specials
206 for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
207 try:
208 self.delete(attr, ["relax:0"])
209 except ldb.LdbError as error:
210 (errno, estr) = error.args
211 if errno != ldb.ERR_NO_SUCH_OBJECT:
212 # Ignore missing dn errors
213 raise
215 def load_ldif_file_add(self, ldif_path):
216 """Load a LDIF file.
218 :param ldif_path: Path to LDIF file.
220 with open(ldif_path, 'r') as ldif_file:
221 self.add_ldif(ldif_file.read())
223 def add_ldif(self, ldif, controls=None):
224 """Add data based on a LDIF string.
226 :param ldif: LDIF text.
228 for changetype, msg in self.parse_ldif(ldif):
229 assert changetype == ldb.CHANGETYPE_NONE
230 self.add(msg, controls)
232 def modify_ldif(self, ldif, controls=None):
233 """Modify database based on a LDIF string.
235 :param ldif: LDIF text.
237 for changetype, msg in self.parse_ldif(ldif):
238 if changetype == ldb.CHANGETYPE_ADD:
239 self.add(msg, controls)
240 else:
241 self.modify(msg, controls)
244 def substitute_var(text, values):
245 """Substitute strings of the form ${NAME} in str, replacing
246 with substitutions from values.
248 :param text: Text in which to subsitute.
249 :param values: Dictionary with keys and values.
252 for (name, value) in values.items():
253 assert isinstance(name, str), "%r is not a string" % name
254 assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
255 text = text.replace("${%s}" % name, value)
257 return text
260 def check_all_substituted(text):
261 """Check that all substitution variables in a string have been replaced.
263 If not, raise an exception.
265 :param text: The text to search for substitution variables
267 if "${" not in text:
268 return
270 var_start = text.find("${")
271 var_end = text.find("}", var_start)
273 raise Exception("Not all variables substituted: %s" %
274 text[var_start:var_end + 1])
277 def read_and_sub_file(file_name, subst_vars):
278 """Read a file and sub in variables found in it
280 :param file_name: File to be read (typically from setup directory)
281 param subst_vars: Optional variables to subsitute in the file.
283 with open(file_name, 'r', encoding="utf-8") as data_file:
284 data = data_file.read()
285 if subst_vars is not None:
286 data = substitute_var(data, subst_vars)
287 check_all_substituted(data)
288 return data
291 def setup_file(template, fname, subst_vars=None):
292 """Setup a file in the private dir.
294 :param template: Path of the template file.
295 :param fname: Path of the file to create.
296 :param subst_vars: Substitution variables.
298 if os.path.exists(fname):
299 os.unlink(fname)
301 data = read_and_sub_file(template, subst_vars)
302 f = open(fname, 'w')
303 try:
304 f.write(data)
305 finally:
306 f.close()
309 MAX_NETBIOS_NAME_LEN = 15
312 def is_valid_netbios_char(c):
313 return (c.isalnum() or c in " !#$%&'()-.@^_{}~")
316 def valid_netbios_name(name):
317 """Check whether a name is valid as a NetBIOS name. """
318 # See crh's book (1.4.1.1)
319 if len(name) > MAX_NETBIOS_NAME_LEN:
320 return False
321 for x in name:
322 if not is_valid_netbios_char(x):
323 return False
324 return True
327 def dn_from_dns_name(dnsdomain):
328 """return a DN from a DNS name domain/forest root"""
329 return "DC=" + ",DC=".join(dnsdomain.split("."))
332 def current_unix_time():
333 return int(time.time())
336 def string_to_byte_array(string):
337 blob = [0] * len(string)
339 for i in range(len(string)):
340 blob[i] = string[i] if isinstance(string[i], int) else ord(string[i])
342 return blob
345 def arcfour_encrypt(key, data):
346 from samba.crypto import arcfour_crypt_blob
347 return arcfour_crypt_blob(data, key)
350 def enable_net_export_keytab():
351 """This function modifies the samba.net.Net class to contain
352 an export_keytab() method."""
353 # This looks very strange because it is.
355 # The dckeytab modules contains nothing, but the act of importing
356 # it pushes a method into samba.net.Net. It ended up this way
357 # because Net.export_keytab() only works on Heimdal builds, and
358 # people sometimes want to compile Samba without Heimdal while
359 # still having a working samba-tool.
361 # There is probably a better way to do this than a magic module
362 # import (yes, that's a FIXME if you can be bothered).
363 from samba import net
364 from samba import dckeytab
367 version = _glue.version
368 interface_ips = _glue.interface_ips
369 fault_setup = _glue.fault_setup
370 set_debug_level = _glue.set_debug_level
371 get_debug_level = _glue.get_debug_level
372 unix2nttime = _glue.unix2nttime
373 float2nttime = _glue.float2nttime
374 nttime2float = _glue.nttime2float
375 nttime2string = _glue.nttime2string
376 nttime2unix = _glue.nttime2unix
377 unix2nttime = _glue.unix2nttime
378 generate_random_password = _glue.generate_random_password
379 generate_random_machine_password = _glue.generate_random_machine_password
380 check_password_quality = _glue.check_password_quality
381 generate_random_bytes = _glue.generate_random_bytes
382 strcasecmp_m = _glue.strcasecmp_m
383 strstr_m = _glue.strstr_m
384 is_ntvfs_fileserver_built = _glue.is_ntvfs_fileserver_built
385 is_heimdal_built = _glue.is_heimdal_built
386 is_ad_dc_built = _glue.is_ad_dc_built
387 is_selftest_enabled = _glue.is_selftest_enabled
389 NTSTATUSError = _glue.NTSTATUSError
390 HRESULTError = _glue.HRESULTError
391 WERRORError = _glue.WERRORError
392 DsExtendedError = _glue.DsExtendedError