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/>.
23 __docformat__ = "restructuredText"
27 def _in_source_tree():
28 """Check whether the script is being run from the source dir. """
29 return os.path.exists("%s/../../../samba4-skip" % os.path.dirname(__file__))
32 # When running, in-tree, make sure bin/python is in the PYTHONPATH
35 srcdir = "%s/../../.." % os.path.dirname(__file__)
36 sys.path.append("%s/bin/python" % srcdir)
37 default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir
39 default_ldb_modules_dir = None
47 """Simple Samba-specific LDB subclass that takes care
48 of setting up the modules dir, credentials pointers, etc.
50 Please note that this is intended to be for all Samba LDB files,
51 not necessarily the Sam database. For Sam-specific helper
52 functions see samdb.py.
54 def __init__(self, url=None, session_info=None, credentials=None,
55 modules_dir=None, lp=None):
56 """Open a Samba Ldb file.
58 :param url: Optional LDB URL to open
59 :param session_info: Optional session information
60 :param credentials: Optional credentials, defaults to anonymous.
61 :param modules_dir: Modules directory, if not the default.
62 :param lp: Loadparm object, optional.
64 This is different from a regular Ldb file in that the Samba-specific
65 modules-dir is used by default and that credentials and session_info
66 can be passed through (required by some modules).
68 super(Ldb, self).__init__()
70 if modules_dir is not None:
71 self.set_modules_dir(modules_dir)
72 elif default_ldb_modules_dir is not None:
73 self.set_modules_dir(default_ldb_modules_dir)
75 if credentials is not None:
76 self.set_credentials(credentials)
78 if session_info is not None:
79 self.set_session_info(session_info)
81 assert misc.ldb_register_samba_handlers(self) == 0
94 set_credentials = misc.ldb_set_credentials
95 set_session_info = misc.ldb_set_session_info
96 set_loadparm = misc.ldb_set_loadparm
98 def searchone(self, attribute, basedn=None, expression=None,
99 scope=ldb.SCOPE_BASE):
100 """Search for one attribute as a string.
102 :param basedn: BaseDN for the search.
103 :param attribute: Name of the attribute
104 :param expression: Optional search expression.
105 :param scope: Search scope (defaults to base).
106 :return: Value of attribute as a string or None if it wasn't found.
108 res = self.search(basedn, scope, expression, [attribute])
109 if len(res) != 1 or res[0][attribute] is None:
111 values = set(res[0][attribute])
112 assert len(values) == 1
113 return self.schema_format_value(attribute, values.pop())
116 """Erase this ldb, removing all records."""
117 # delete the specials
118 for attr in ["@INDEXLIST", "@ATTRIBUTES", "@SUBCLASSES", "@MODULES",
119 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
122 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
123 # Ignore missing dn errors
128 for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
129 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
130 ["distinguishedName"]):
133 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
134 # Ignore no such object errors
137 res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", ["distinguishedName"])
140 def erase_partitions(self):
141 """Erase an ldb, removing all records."""
142 res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)",
145 if not "namingContexts" in res[0]:
147 for basedn in res[0]["namingContexts"]:
148 previous_remaining = 1
149 current_remaining = 0
152 while ++k < 10 and (previous_remaining != current_remaining):
155 res2 = self.search(basedn, ldb.SCOPE_SUBTREE, "(|(objectclass=*)(distinguishedName=*))", ["distinguishedName"])
156 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
157 # Ignore missing dn errors
160 previous_remaining = current_remaining
161 current_remaining = len(res2)
165 # Ignore no such object errors
166 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
168 # Ignore not allowed on non leaf errors
169 except ldb.LdbError, (LDB_ERR_NOT_ALLOWED_ON_NON_LEAF, _):
172 def load_ldif_file_add(self, ldif_path):
175 :param ldif_path: Path to LDIF file.
177 self.add_ldif(open(ldif_path, 'r').read())
179 def add_ldif(self, ldif):
180 """Add data based on a LDIF string.
182 :param ldif: LDIF text.
184 for changetype, msg in self.parse_ldif(ldif):
185 assert changetype == ldb.CHANGETYPE_NONE
188 def modify_ldif(self, ldif):
189 """Modify database based on a LDIF string.
191 :param ldif: LDIF text.
193 for changetype, msg in self.parse_ldif(ldif):
197 def substitute_var(text, values):
198 """substitute strings of the form ${NAME} in str, replacing
199 with substitutions from subobj.
201 :param text: Text in which to subsitute.
202 :param values: Dictionary with keys and values.
205 for (name, value) in values.items():
206 assert isinstance(name, str), "%r is not a string" % name
207 assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
208 text = text.replace("${%s}" % name, value)
213 def check_all_substituted(text):
214 """Make sure that all substitution variables in a string have been replaced.
215 If not, raise an exception.
217 :param text: The text to search for substitution variables
222 var_start = text.find("${")
223 var_end = text.find("}", var_start)
225 raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
228 def valid_netbios_name(name):
229 """Check whether a name is valid as a NetBIOS name. """
230 # FIXME: There are probably more constraints here.
231 # crh has a paragraph on this in his book (1.4.1.1)
236 version = misc.version