s4:provision Avoid one more call to ltdb_reindex
[metze/samba/wip.git] / source4 / scripting / python / samba / __init__.py
1 #!/usr/bin/python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
5
6 # Based on the original in EJS:
7 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
8 #   
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.
13 #   
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.
18 #   
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/>.
21 #
22
23 """Samba 4."""
24
25 __docformat__ = "restructuredText"
26
27 import os
28
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__))
32
33
34 # When running, in-tree, make sure bin/python is in the PYTHONPATH
35 if _in_source_tree():
36     import sys
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
40 else:
41     default_ldb_modules_dir = None
42
43
44 import ldb
45 import glue
46
47 class Ldb(ldb.Ldb):
48     """Simple Samba-specific LDB subclass that takes care 
49     of setting up the modules dir, credentials pointers, etc.
50     
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.
54     """
55     def __init__(self, url=None, session_info=None, credentials=None, 
56                  modules_dir=None, lp=None, options=None):
57         """Open a Samba Ldb file. 
58
59         :param url: Optional LDB URL to open
60         :param session_info: Optional session information
61         :param credentials: Optional credentials, defaults to anonymous.
62         :param modules_dir: Modules directory, if not the default.
63         :param lp: Loadparm object, optional.
64
65         This is different from a regular Ldb file in that the Samba-specific
66         modules-dir is used by default and that credentials and session_info 
67         can be passed through (required by some modules).
68         """
69         super(Ldb, self).__init__(options=options)
70
71         if modules_dir is not None:
72             self.set_modules_dir(modules_dir)
73         elif default_ldb_modules_dir is not None:
74             self.set_modules_dir(default_ldb_modules_dir)
75         elif lp is not None:
76             self.set_modules_dir(os.path.join(lp.get("modules dir"), "ldb"))
77
78         if credentials is not None:
79             self.set_credentials(credentials)
80
81         if session_info is not None:
82             self.set_session_info(session_info)
83
84         glue.ldb_register_samba_handlers(self)
85
86         if lp is not None:
87             self.set_loadparm(lp)
88
89         def msg(l,text):
90             print text
91         #self.set_debug(msg)
92
93         if url is not None:
94             self.connect(url, options=options)
95
96     def set_credentials(self, credentials):
97         glue.ldb_set_credentials(self, credentials)
98
99     def set_session_info(self, session_info):
100         glue.ldb_set_session_info(self, session_info)
101
102     def set_loadparm(self, lp_ctx):
103         glue.ldb_set_loadparm(self, lp_ctx)
104
105     def searchone(self, attribute, basedn=None, expression=None, 
106                   scope=ldb.SCOPE_BASE):
107         """Search for one attribute as a string.
108         
109         :param basedn: BaseDN for the search.
110         :param attribute: Name of the attribute
111         :param expression: Optional search expression.
112         :param scope: Search scope (defaults to base).
113         :return: Value of attribute as a string or None if it wasn't found.
114         """
115         res = self.search(basedn, scope, expression, [attribute])
116         if len(res) != 1 or res[0][attribute] is None:
117             return None
118         values = set(res[0][attribute])
119         assert len(values) == 1
120         return self.schema_format_value(attribute, values.pop())
121
122     def erase_except_schema_controlled(self):
123         """Erase this ldb, removing all records, except those that are controlled by Samba4's schema."""
124         basedn = ""
125         # Delete the 'visible' records
126         for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 
127                 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", 
128                 ["distinguishedName"]):
129             try:
130                 self.delete(msg.dn)
131             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
132                 # Ignore no such object errors
133                 pass
134
135         res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", ["distinguishedName"])
136         assert len(res) == 0
137
138         # delete the specials
139         for attr in ["@SUBCLASSES", "@MODULES", 
140                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
141             try:
142                 self.delete(attr)
143             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
144                 # Ignore missing dn errors
145                 pass
146
147     def erase(self):
148         """Erase this ldb, removing all records."""
149         
150         self.erase_except_schema_controlled()
151
152         # delete the specials
153         for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
154             try:
155                 self.delete(attr)
156             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
157                 # Ignore missing dn errors
158                 pass
159
160     def erase_partitions(self):
161         """Erase an ldb, removing all records."""
162
163         def erase_recursive(self, dn):
164             try:
165                 res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[])
166             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
167                 # Ignore no such object errors
168                 return
169                 pass
170             
171             for msg in res:
172                 erase_recursive(self, msg.dn)
173
174             try:
175                 self.delete(dn)
176             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
177                 # Ignore no such object errors
178                 pass
179
180         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", 
181                          ["namingContexts"])
182         assert len(res) == 1
183         if not "namingContexts" in res[0]:
184             return
185         for basedn in res[0]["namingContexts"]:
186             # Try and erase from the bottom-up in the tree
187             erase_recursive(self, basedn)
188
189     def load_ldif_file_add(self, ldif_path):
190         """Load a LDIF file.
191
192         :param ldif_path: Path to LDIF file.
193         """
194         self.add_ldif(open(ldif_path, 'r').read())
195
196     def add_ldif(self, ldif):
197         """Add data based on a LDIF string.
198
199         :param ldif: LDIF text.
200         """
201         for changetype, msg in self.parse_ldif(ldif):
202             assert changetype == ldb.CHANGETYPE_NONE
203             self.add(msg)
204
205     def modify_ldif(self, ldif):
206         """Modify database based on a LDIF string.
207
208         :param ldif: LDIF text.
209         """
210         for changetype, msg in self.parse_ldif(ldif):
211             self.modify(msg)
212
213     def set_domain_sid(self, sid):
214         """Change the domain SID used by this LDB.
215
216         :param sid: The new domain sid to use.
217         """
218         glue.samdb_set_domain_sid(self, sid)
219
220     def set_schema_from_ldif(self, pf, df):
221         glue.dsdb_set_schema_from_ldif(self, pf, df)
222
223     def set_schema_from_ldb(self, ldb):
224         glue.dsdb_set_schema_from_ldb(self, ldb)
225
226     def convert_schema_to_openldap(self, target, mapping):
227         return glue.dsdb_convert_schema_to_openldap(self, target, mapping)
228
229     def set_invocation_id(self, invocation_id):
230         """Set the invocation id for this SamDB handle.
231         
232         :param invocation_id: GUID of the invocation id.
233         """
234         glue.dsdb_set_ntds_invocation_id(self, invocation_id)
235
236     def set_opaque_integer(self, name, value):
237         """Set an integer as an opaque (a flag or other value) value on the database
238         
239         :param name: The name for the opaque value
240         :param value: The integer value
241         """
242         glue.dsdb_set_opaque_integer(self, name, value)
243
244
245 def substitute_var(text, values):
246     """substitute strings of the form ${NAME} in str, replacing
247     with substitutions from subobj.
248     
249     :param text: Text in which to subsitute.
250     :param values: Dictionary with keys and values.
251     """
252
253     for (name, value) in values.items():
254         assert isinstance(name, str), "%r is not a string" % name
255         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
256         text = text.replace("${%s}" % name, value)
257
258     return text
259
260
261 def check_all_substituted(text):
262     """Make sure that all substitution variables in a string have been replaced.
263     If not, raise an exception.
264     
265     :param text: The text to search for substitution variables
266     """
267     if not "${" in text:
268         return
269     
270     var_start = text.find("${")
271     var_end = text.find("}", var_start)
272     
273     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
274
275
276 def valid_netbios_name(name):
277     """Check whether a name is valid as a NetBIOS name. """
278     # See crh's book (1.4.1.1)
279     if len(name) > 15:
280         return False
281     for x in name:
282         if not x.isalnum() and not x in " !#$%&'()-.@^_{}~":
283             return False
284     return True
285
286
287 def dom_sid_to_rid(sid_str):
288     """Converts a domain SID to the relative RID.
289
290     :param sid_str: The domain SID formatted as string
291     """
292
293     return glue.dom_sid_to_rid(sid_str)
294
295
296 version = glue.version
297
298 DS_BEHAVIOR_WIN2000 = glue.DS_BEHAVIOR_WIN2000
299 DS_BEHAVIOR_WIN2003_INTERIM = glue.DS_BEHAVIOR_WIN2003_INTERIM
300 DS_BEHAVIOR_WIN2003 = glue.DS_BEHAVIOR_WIN2003
301 DS_BEHAVIOR_WIN2008 = glue.DS_BEHAVIOR_WIN2008