3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
6 # Based on the original in EJS:
7 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
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.
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.
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/>.
25 __docformat__ = "restructuredText"
29 def _in_source_tree():
30 """Check whether the script is being run from the source dir. """
31 return os.path.exists("%s/../../../selftest/skip" % os.path.dirname(__file__))
34 # When running, in-tree, make sure bin/python is in the PYTHONPATH
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
41 default_ldb_modules_dir = None
48 """Simple Samba-specific LDB subclass that takes care
49 of setting up the modules dir, credentials pointers, etc.
51 Please note that this is intended to be for all Samba LDB files,
52 not necessarily the Sam database. For Sam-specific helper
53 functions see samdb.py.
55 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
56 credentials=None, flags=0, options=None):
57 """Opens a Samba Ldb file.
59 :param url: Optional LDB URL to open
60 :param lp: Optional loadparm object
61 :param modules_dir: Optional modules directory
62 :param session_info: Optional session information
63 :param credentials: Optional credentials, defaults to anonymous.
64 :param flags: Optional LDB flags
65 :param options: Additional options (optional)
67 This is different from a regular Ldb file in that the Samba-specific
68 modules-dir is used by default and that credentials and session_info
69 can be passed through (required by some modules).
72 if modules_dir is not None:
73 self.set_modules_dir(modules_dir)
74 elif default_ldb_modules_dir is not None:
75 self.set_modules_dir(default_ldb_modules_dir)
77 self.set_modules_dir(os.path.join(lp.get("modules dir"), "ldb"))
79 if session_info is not None:
80 self.set_session_info(session_info)
82 if credentials is not None:
83 self.set_credentials(credentials)
88 # This must be done before we load the schema, as these handlers for
89 # objectSid and objectGUID etc must take precedence over the 'binary
90 # attribute' declaration in the schema
91 glue.ldb_register_samba_handlers(self)
98 glue.ldb_set_utf8_casefold(self)
100 # Allow admins to force non-sync ldb for all databases
102 nosync_p = lp.get("nosync", "ldb")
103 if nosync_p is not None and nosync_p == true:
107 self.connect(url, flags, options)
109 def set_credentials(self, credentials):
110 glue.ldb_set_credentials(self, credentials)
112 def set_session_info(self, session_info):
113 glue.ldb_set_session_info(self, session_info)
115 def set_loadparm(self, lp_ctx):
116 glue.ldb_set_loadparm(self, lp_ctx)
118 def searchone(self, attribute, basedn=None, expression=None,
119 scope=ldb.SCOPE_BASE):
120 """Search for one attribute as a string.
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.
128 res = self.search(basedn, scope, expression, [attribute])
129 if len(res) != 1 or res[0][attribute] is None:
131 values = set(res[0][attribute])
132 assert len(values) == 1
133 return self.schema_format_value(attribute, values.pop())
135 def erase_except_schema_controlled(self):
136 """Erase this ldb, removing all records, except those that are controlled by Samba4's schema."""
138 # Delete the 'visible' records, and the invisble 'deleted' records (if this DB supports it)
139 for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
140 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
141 [], controls=["show_deleted:0"]):
144 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
145 # Ignore no such object errors
148 res = self.search(basedn, ldb.SCOPE_SUBTREE,
149 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
150 [], controls=["show_deleted:0"])
153 # delete the specials
154 for attr in ["@SUBCLASSES", "@MODULES",
155 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
158 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
159 # Ignore missing dn errors
163 """Erase this ldb, removing all records."""
165 self.erase_except_schema_controlled()
167 # delete the specials
168 for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
171 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
172 # Ignore missing dn errors
175 def erase_partitions(self):
176 """Erase an ldb, removing all records."""
178 def erase_recursive(self, dn):
180 res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[],
181 controls=["show_deleted:0"])
182 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
183 # Ignore no such object errors
188 erase_recursive(self, msg.dn)
192 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
193 # Ignore no such object errors
196 res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)",
199 if not "namingContexts" in res[0]:
201 for basedn in res[0]["namingContexts"]:
202 # Try and erase from the bottom-up in the tree
203 erase_recursive(self, basedn)
205 def load_ldif_file_add(self, ldif_path):
208 :param ldif_path: Path to LDIF file.
210 self.add_ldif(open(ldif_path, 'r').read())
212 def add_ldif(self, ldif):
213 """Add data based on a LDIF string.
215 :param ldif: LDIF text.
217 for changetype, msg in self.parse_ldif(ldif):
218 assert changetype == ldb.CHANGETYPE_NONE
221 def modify_ldif(self, ldif):
222 """Modify database based on a LDIF string.
224 :param ldif: LDIF text.
226 for changetype, msg in self.parse_ldif(ldif):
229 def set_domain_sid(self, sid):
230 """Change the domain SID used by this LDB.
232 :param sid: The new domain sid to use.
234 glue.samdb_set_domain_sid(self, sid)
236 def set_schema_from_ldif(self, pf, df):
237 glue.dsdb_set_schema_from_ldif(self, pf, df)
239 def set_schema_from_ldb(self, ldb):
240 glue.dsdb_set_schema_from_ldb(self, ldb)
242 def write_prefixes_from_schema(self):
243 glue.dsdb_write_prefixes_from_schema_to_ldb(self)
245 def convert_schema_to_openldap(self, target, mapping):
246 return glue.dsdb_convert_schema_to_openldap(self, target, mapping)
248 def set_invocation_id(self, invocation_id):
249 """Set the invocation id for this SamDB handle.
251 :param invocation_id: GUID of the invocation id.
253 glue.dsdb_set_ntds_invocation_id(self, invocation_id)
255 def set_opaque_integer(self, name, value):
256 """Set an integer as an opaque (a flag or other value) value on the database
258 :param name: The name for the opaque value
259 :param value: The integer value
261 glue.dsdb_set_opaque_integer(self, name, value)
264 def substitute_var(text, values):
265 """substitute strings of the form ${NAME} in str, replacing
266 with substitutions from subobj.
268 :param text: Text in which to subsitute.
269 :param values: Dictionary with keys and values.
272 for (name, value) in values.items():
273 assert isinstance(name, str), "%r is not a string" % name
274 assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
275 text = text.replace("${%s}" % name, value)
280 def check_all_substituted(text):
281 """Make sure that all substitution variables in a string have been replaced.
282 If not, raise an exception.
284 :param text: The text to search for substitution variables
289 var_start = text.find("${")
290 var_end = text.find("}", var_start)
292 raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
295 def valid_netbios_name(name):
296 """Check whether a name is valid as a NetBIOS name. """
297 # See crh's book (1.4.1.1)
301 if not x.isalnum() and not x in " !#$%&'()-.@^_{}~":
306 def dom_sid_to_rid(sid_str):
307 """Converts a domain SID to the relative RID.
309 :param sid_str: The domain SID formatted as string
312 return glue.dom_sid_to_rid(sid_str)
315 version = glue.version
317 DS_BEHAVIOR_WIN2000 = glue.DS_BEHAVIOR_WIN2000
318 DS_BEHAVIOR_WIN2003_INTERIM = glue.DS_BEHAVIOR_WIN2003_INTERIM
319 DS_BEHAVIOR_WIN2003 = glue.DS_BEHAVIOR_WIN2003
320 DS_BEHAVIOR_WIN2008 = glue.DS_BEHAVIOR_WIN2008