69a0320be78546a53688b5b5cba8fba257eaa960
[ira/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, lp=None, modules_dir=None, session_info=None,
56                  credentials=None, flags=0, options=None):
57         """Opens a Samba Ldb file.
58
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)
66
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).
70         """
71
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)
76         elif lp is not None:
77             self.set_modules_dir(os.path.join(lp.get("modules dir"), "ldb"))
78
79         if session_info is not None:
80             self.set_session_info(session_info)
81
82         if credentials is not None:
83             self.set_credentials(credentials)
84
85         if lp is not None:
86             self.set_loadparm(lp)
87
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)
92
93         # TODO set debug
94         def msg(l,text):
95             print text
96         #self.set_debug(msg)
97
98         glue.ldb_set_utf8_casefold(self)
99
100         # Allow admins to force non-sync ldb for all databases
101         if lp is not None:
102             nosync_p = lp.get("nosync", "ldb")
103             if nosync_p is not None and nosync_p == true:
104                 flags |= FLG_NOSYNC
105
106         if url is not None:
107             self.connect(url, flags, options)
108
109     def set_credentials(self, credentials):
110         glue.ldb_set_credentials(self, credentials)
111
112     def set_session_info(self, session_info):
113         glue.ldb_set_session_info(self, session_info)
114
115     def set_loadparm(self, lp_ctx):
116         glue.ldb_set_loadparm(self, lp_ctx)
117
118     def searchone(self, attribute, basedn=None, expression=None, 
119                   scope=ldb.SCOPE_BASE):
120         """Search for one attribute as a string.
121         
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.
127         """
128         res = self.search(basedn, scope, expression, [attribute])
129         if len(res) != 1 or res[0][attribute] is None:
130             return None
131         values = set(res[0][attribute])
132         assert len(values) == 1
133         return self.schema_format_value(attribute, values.pop())
134
135     def erase_except_schema_controlled(self):
136         """Erase this ldb, removing all records, except those that are controlled by Samba4's schema."""
137         basedn = ""
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"]):
142             try:
143                 self.delete(msg.dn)
144             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
145                 # Ignore no such object errors
146                 pass
147             
148         res = self.search(basedn, ldb.SCOPE_SUBTREE, 
149                           "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
150                           [], controls=["show_deleted:0"])
151         assert len(res) == 0
152
153         # delete the specials
154         for attr in ["@SUBCLASSES", "@MODULES", 
155                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
156             try:
157                 self.delete(attr)
158             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
159                 # Ignore missing dn errors
160                 pass
161
162     def erase(self):
163         """Erase this ldb, removing all records."""
164         
165         self.erase_except_schema_controlled()
166
167         # delete the specials
168         for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
169             try:
170                 self.delete(attr)
171             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
172                 # Ignore missing dn errors
173                 pass
174
175     def erase_partitions(self):
176         """Erase an ldb, removing all records."""
177
178         def erase_recursive(self, dn):
179             try:
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
184                 return
185                 pass
186             
187             for msg in res:
188                 erase_recursive(self, msg.dn)
189
190             try:
191                 self.delete(dn)
192             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
193                 # Ignore no such object errors
194                 pass
195
196         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", 
197                          ["namingContexts"])
198         assert len(res) == 1
199         if not "namingContexts" in res[0]:
200             return
201         for basedn in res[0]["namingContexts"]:
202             # Try and erase from the bottom-up in the tree
203             erase_recursive(self, basedn)
204
205     def load_ldif_file_add(self, ldif_path):
206         """Load a LDIF file.
207
208         :param ldif_path: Path to LDIF file.
209         """
210         self.add_ldif(open(ldif_path, 'r').read())
211
212     def add_ldif(self, ldif):
213         """Add data based on a LDIF string.
214
215         :param ldif: LDIF text.
216         """
217         for changetype, msg in self.parse_ldif(ldif):
218             assert changetype == ldb.CHANGETYPE_NONE
219             self.add(msg)
220
221     def modify_ldif(self, ldif):
222         """Modify database based on a LDIF string.
223
224         :param ldif: LDIF text.
225         """
226         for changetype, msg in self.parse_ldif(ldif):
227             self.modify(msg)
228
229     def set_domain_sid(self, sid):
230         """Change the domain SID used by this LDB.
231
232         :param sid: The new domain sid to use.
233         """
234         glue.samdb_set_domain_sid(self, sid)
235
236     def set_schema_from_ldif(self, pf, df):
237         glue.dsdb_set_schema_from_ldif(self, pf, df)
238
239     def set_schema_from_ldb(self, ldb):
240         glue.dsdb_set_schema_from_ldb(self, ldb)
241
242     def convert_schema_to_openldap(self, target, mapping):
243         return glue.dsdb_convert_schema_to_openldap(self, target, mapping)
244
245     def set_invocation_id(self, invocation_id):
246         """Set the invocation id for this SamDB handle.
247         
248         :param invocation_id: GUID of the invocation id.
249         """
250         glue.dsdb_set_ntds_invocation_id(self, invocation_id)
251
252     def set_opaque_integer(self, name, value):
253         """Set an integer as an opaque (a flag or other value) value on the database
254         
255         :param name: The name for the opaque value
256         :param value: The integer value
257         """
258         glue.dsdb_set_opaque_integer(self, name, value)
259
260
261 def substitute_var(text, values):
262     """substitute strings of the form ${NAME} in str, replacing
263     with substitutions from subobj.
264     
265     :param text: Text in which to subsitute.
266     :param values: Dictionary with keys and values.
267     """
268
269     for (name, value) in values.items():
270         assert isinstance(name, str), "%r is not a string" % name
271         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
272         text = text.replace("${%s}" % name, value)
273
274     return text
275
276
277 def check_all_substituted(text):
278     """Make sure that all substitution variables in a string have been replaced.
279     If not, raise an exception.
280     
281     :param text: The text to search for substitution variables
282     """
283     if not "${" in text:
284         return
285     
286     var_start = text.find("${")
287     var_end = text.find("}", var_start)
288     
289     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
290
291
292 def valid_netbios_name(name):
293     """Check whether a name is valid as a NetBIOS name. """
294     # See crh's book (1.4.1.1)
295     if len(name) > 15:
296         return False
297     for x in name:
298         if not x.isalnum() and not x in " !#$%&'()-.@^_{}~":
299             return False
300     return True
301
302
303 def dom_sid_to_rid(sid_str):
304     """Converts a domain SID to the relative RID.
305
306     :param sid_str: The domain SID formatted as string
307     """
308
309     return glue.dom_sid_to_rid(sid_str)
310
311
312 version = glue.version
313
314 DS_BEHAVIOR_WIN2000 = glue.DS_BEHAVIOR_WIN2000
315 DS_BEHAVIOR_WIN2003_INTERIM = glue.DS_BEHAVIOR_WIN2003_INTERIM
316 DS_BEHAVIOR_WIN2003 = glue.DS_BEHAVIOR_WIN2003
317 DS_BEHAVIOR_WIN2008 = glue.DS_BEHAVIOR_WIN2008