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/../../../samba4-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
49 """Simple Samba-specific LDB subclass that takes care
50 of setting up the modules dir, credentials pointers, etc.
52 Please note that this is intended to be for all Samba LDB files,
53 not necessarily the Sam database. For Sam-specific helper
54 functions see samdb.py.
56 def __init__(self, url=None, session_info=None, credentials=None,
57 modules_dir=None, lp=None, options=None):
58 """Open a Samba Ldb file.
60 :param url: Optional LDB URL to open
61 :param session_info: Optional session information
62 :param credentials: Optional credentials, defaults to anonymous.
63 :param modules_dir: Modules directory, if not the default.
64 :param lp: Loadparm object, optional.
66 This is different from a regular Ldb file in that the Samba-specific
67 modules-dir is used by default and that credentials and session_info
68 can be passed through (required by some modules).
70 super(Ldb, self).__init__(options=options)
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 if credentials is not None:
78 self.set_credentials(credentials)
80 if session_info is not None:
81 self.set_session_info(session_info)
83 glue.ldb_register_samba_handlers(self)
93 self.connect(url, options=options)
95 def set_credentials(self, credentials):
96 glue.ldb_set_credentials(self, credentials)
98 def set_session_info(self, session_info):
99 glue.ldb_set_session_info(self, session_info)
101 def set_loadparm(self, lp_ctx):
102 glue.ldb_set_loadparm(self, lp_ctx)
104 def searchone(self, attribute, basedn=None, expression=None,
105 scope=ldb.SCOPE_BASE):
106 """Search for one attribute as a string.
108 :param basedn: BaseDN for the search.
109 :param attribute: Name of the attribute
110 :param expression: Optional search expression.
111 :param scope: Search scope (defaults to base).
112 :return: Value of attribute as a string or None if it wasn't found.
114 res = self.search(basedn, scope, expression, [attribute])
115 if len(res) != 1 or res[0][attribute] is None:
117 values = set(res[0][attribute])
118 assert len(values) == 1
119 return self.schema_format_value(attribute, values.pop())
122 """Erase this ldb, removing all records."""
123 # delete the specials
124 for attr in ["@INDEXLIST", "@ATTRIBUTES", "@SUBCLASSES", "@MODULES",
125 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
128 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
129 # Ignore missing dn errors
134 for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
135 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
136 ["distinguishedName"]):
139 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
140 # Ignore no such object errors
143 res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", ["distinguishedName"])
146 def erase_partitions(self):
147 """Erase an ldb, removing all records."""
148 res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)",
151 if not "namingContexts" in res[0]:
153 for basedn in res[0]["namingContexts"]:
154 previous_remaining = 1
155 current_remaining = 0
158 while ++k < 10 and (previous_remaining != current_remaining):
161 res2 = self.search(basedn, ldb.SCOPE_SUBTREE, "(|(objectclass=*)(distinguishedName=*))", ["distinguishedName"])
162 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
163 # Ignore missing dn errors
166 previous_remaining = current_remaining
167 current_remaining = len(res2)
171 # Ignore no such object errors
172 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
174 # Ignore not allowed on non leaf errors
175 except ldb.LdbError, (LDB_ERR_NOT_ALLOWED_ON_NON_LEAF, _):
178 def load_ldif_file_add(self, ldif_path):
181 :param ldif_path: Path to LDIF file.
183 self.add_ldif(open(ldif_path, 'r').read())
185 def add_ldif(self, ldif):
186 """Add data based on a LDIF string.
188 :param ldif: LDIF text.
190 for changetype, msg in self.parse_ldif(ldif):
191 assert changetype == ldb.CHANGETYPE_NONE
194 def modify_ldif(self, ldif):
195 """Modify database based on a LDIF string.
197 :param ldif: LDIF text.
199 for changetype, msg in self.parse_ldif(ldif):
203 def substitute_var(text, values):
204 """substitute strings of the form ${NAME} in str, replacing
205 with substitutions from subobj.
207 :param text: Text in which to subsitute.
208 :param values: Dictionary with keys and values.
211 for (name, value) in values.items():
212 assert isinstance(name, str), "%r is not a string" % name
213 assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
214 text = text.replace("${%s}" % name, value)
219 def check_all_substituted(text):
220 """Make sure that all substitution variables in a string have been replaced.
221 If not, raise an exception.
223 :param text: The text to search for substitution variables
228 var_start = text.find("${")
229 var_end = text.find("}", var_start)
231 raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
234 def valid_netbios_name(name):
235 """Check whether a name is valid as a NetBIOS name. """
236 # FIXME: There are probably more constraints here.
237 # crh has a paragraph on this in his book (1.4.1.1)
242 version = glue.version