Merge commit 'release-4-0-0alpha15' into master4-tmp
[ira/wip.git] / source4 / scripting / python / samba / __init__.py
1 #!/usr/bin/env 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 import sys
29 import samba.param
30
31 def source_tree_topdir():
32     '''return the top level directory (the one containing the source4 directory)'''
33     paths = [ "../../..", "../../../.." ]
34     for p in paths:
35         topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
36         if os.path.exists(os.path.join(topdir, 'source4')):
37             return topdir
38     raise RuntimeError("unable to find top level source directory")
39
40 def in_source_tree():
41     '''return True if we are running from within the samba source tree'''
42     try:
43         topdir = source_tree_topdir()
44     except RuntimeError:
45         return False
46     return True
47
48
49
50 import ldb
51 from samba._ldb import Ldb as _Ldb
52
53 class Ldb(_Ldb):
54     """Simple Samba-specific LDB subclass that takes care
55     of setting up the modules dir, credentials pointers, etc.
56
57     Please note that this is intended to be for all Samba LDB files,
58     not necessarily the Sam database. For Sam-specific helper
59     functions see samdb.py.
60     """
61
62     def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
63                  credentials=None, flags=0, options=None):
64         """Opens a Samba Ldb file.
65
66         :param url: Optional LDB URL to open
67         :param lp: Optional loadparm object
68         :param modules_dir: Optional modules directory
69         :param session_info: Optional session information
70         :param credentials: Optional credentials, defaults to anonymous.
71         :param flags: Optional LDB flags
72         :param options: Additional options (optional)
73
74         This is different from a regular Ldb file in that the Samba-specific
75         modules-dir is used by default and that credentials and session_info
76         can be passed through (required by some modules).
77         """
78
79         if modules_dir is not None:
80             self.set_modules_dir(modules_dir)
81         else:
82             self.set_modules_dir(os.path.join(samba.param.modules_dir(), "ldb"))
83
84         if session_info is not None:
85             self.set_session_info(session_info)
86
87         if credentials is not None:
88             self.set_credentials(credentials)
89
90         if lp is not None:
91             self.set_loadparm(lp)
92
93         # This must be done before we load the schema, as these handlers for
94         # objectSid and objectGUID etc must take precedence over the 'binary
95         # attribute' declaration in the schema
96         self.register_samba_handlers()
97
98         # TODO set debug
99         def msg(l, text):
100             print text
101         #self.set_debug(msg)
102
103         self.set_utf8_casefold()
104
105         # Allow admins to force non-sync ldb for all databases
106         if lp is not None:
107             nosync_p = lp.get("nosync", "ldb")
108             if nosync_p is not None and nosync_p == True:
109                 flags |= ldb.FLG_NOSYNC
110
111         self.set_create_perms(0600)
112
113         if url is not None:
114             self.connect(url, flags, options)
115
116     def searchone(self, attribute, basedn=None, expression=None,
117                   scope=ldb.SCOPE_BASE):
118         """Search for one attribute as a string.
119
120         :param basedn: BaseDN for the search.
121         :param attribute: Name of the attribute
122         :param expression: Optional search expression.
123         :param scope: Search scope (defaults to base).
124         :return: Value of attribute as a string or None if it wasn't found.
125         """
126         res = self.search(basedn, scope, expression, [attribute])
127         if len(res) != 1 or res[0][attribute] is None:
128             return None
129         values = set(res[0][attribute])
130         assert len(values) == 1
131         return self.schema_format_value(attribute, values.pop())
132
133     def erase_users_computers(self, dn):
134         """Erases user and computer objects from our AD.
135
136         This is needed since the 'samldb' module denies the deletion of primary
137         groups. Therefore all groups shouldn't be primary somewhere anymore.
138         """
139
140         try:
141             res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
142                       expression="(|(objectclass=user)(objectclass=computer))")
143         except ldb.LdbError, (errno, _):
144             if errno == ldb.ERR_NO_SUCH_OBJECT:
145                 # Ignore no such object errors
146                 return
147             else:
148                 raise
149
150         try:
151             for msg in res:
152                 self.delete(msg.dn, ["relax:0"])
153         except ldb.LdbError, (errno, _):
154             if errno != ldb.ERR_NO_SUCH_OBJECT:
155                 # Ignore no such object errors
156                 raise
157
158     def erase_except_schema_controlled(self):
159         """Erase this ldb.
160
161         :note: Removes all records, except those that are controlled by
162             Samba4's schema.
163         """
164
165         basedn = ""
166
167         # Try to delete user/computer accounts to allow deletion of groups
168         self.erase_users_computers(basedn)
169
170         # Delete the 'visible' records, and the invisble 'deleted' records (if this DB supports it)
171         for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
172                        "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
173                        [], controls=["show_deleted:0", "show_recycled:0"]):
174             try:
175                 self.delete(msg.dn, ["relax:0"])
176             except ldb.LdbError, (errno, _):
177                 if errno != ldb.ERR_NO_SUCH_OBJECT:
178                     # Ignore no such object errors
179                     raise
180
181         res = self.search(basedn, ldb.SCOPE_SUBTREE,
182             "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", [], controls=["show_deleted:0", "show_recycled:0"])
183         assert len(res) == 0
184
185         # delete the specials
186         for attr in ["@SUBCLASSES", "@MODULES",
187                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
188             try:
189                 self.delete(attr, ["relax:0"])
190             except ldb.LdbError, (errno, _):
191                 if errno != ldb.ERR_NO_SUCH_OBJECT:
192                     # Ignore missing dn errors
193                     raise
194
195     def erase(self):
196         """Erase this ldb, removing all records."""
197         self.erase_except_schema_controlled()
198
199         # delete the specials
200         for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
201             try:
202                 self.delete(attr, ["relax:0"])
203             except ldb.LdbError, (errno, _):
204                 if errno != ldb.ERR_NO_SUCH_OBJECT:
205                     # Ignore missing dn errors
206                     raise
207
208     def load_ldif_file_add(self, ldif_path):
209         """Load a LDIF file.
210
211         :param ldif_path: Path to LDIF file.
212         """
213         self.add_ldif(open(ldif_path, 'r').read())
214
215     def add_ldif(self, ldif, controls=None):
216         """Add data based on a LDIF string.
217
218         :param ldif: LDIF text.
219         """
220         for changetype, msg in self.parse_ldif(ldif):
221             assert changetype == ldb.CHANGETYPE_NONE
222             self.add(msg, controls)
223
224     def modify_ldif(self, ldif, controls=None):
225         """Modify database based on a LDIF string.
226
227         :param ldif: LDIF text.
228         """
229         for changetype, msg in self.parse_ldif(ldif):
230             if changetype == ldb.CHANGETYPE_ADD:
231                 self.add(msg, controls)
232             else:
233                 self.modify(msg, controls)
234
235
236 def substitute_var(text, values):
237     """Substitute strings of the form ${NAME} in str, replacing
238     with substitutions from values.
239
240     :param text: Text in which to subsitute.
241     :param values: Dictionary with keys and values.
242     """
243
244     for (name, value) in values.items():
245         assert isinstance(name, str), "%r is not a string" % name
246         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
247         text = text.replace("${%s}" % name, value)
248
249     return text
250
251
252 def check_all_substituted(text):
253     """Check that all substitution variables in a string have been replaced.
254
255     If not, raise an exception.
256
257     :param text: The text to search for substitution variables
258     """
259     if not "${" in text:
260         return
261
262     var_start = text.find("${")
263     var_end = text.find("}", var_start)
264
265     raise Exception("Not all variables substituted: %s" %
266         text[var_start:var_end+1])
267
268
269 def read_and_sub_file(file_name, subst_vars):
270     """Read a file and sub in variables found in it
271
272     :param file_name: File to be read (typically from setup directory)
273      param subst_vars: Optional variables to subsitute in the file.
274     """
275     data = open(file_name, 'r').read()
276     if subst_vars is not None:
277         data = substitute_var(data, subst_vars)
278         check_all_substituted(data)
279     return data
280
281
282 def setup_file(template, fname, subst_vars=None):
283     """Setup a file in the private dir.
284
285     :param template: Path of the template file.
286     :param fname: Path of the file to create.
287     :param subst_vars: Substitution variables.
288     """
289     if os.path.exists(fname):
290         os.unlink(fname)
291
292     data = read_and_sub_file(template, subst_vars)
293     f = open(fname, 'w')
294     try:
295         f.write(data)
296     finally:
297         f.close()
298
299
300 def valid_netbios_name(name):
301     """Check whether a name is valid as a NetBIOS name. """
302     # See crh's book (1.4.1.1)
303     if len(name) > 15:
304         return False
305     for x in name:
306         if not x.isalnum() and not x in " !#$%&'()-.@^_{}~":
307             return False
308     return True
309
310
311 def import_bundled_package(modulename, location):
312     """Import the bundled version of a package.
313
314     :note: This should only be called if the system version of the package
315         is not adequate.
316
317     :param modulename: Module name to import
318     :param location: Location to add to sys.path (can be relative to
319         ${srcdir}/lib)
320     """
321     if in_source_tree():
322         sys.path.insert(0, os.path.join(source_tree_topdir(), "lib", location))
323         sys.modules[modulename] = __import__(modulename)
324     else:
325         sys.modules[modulename] = __import__(
326             "samba.external.%s" % modulename, fromlist=["samba.external"])
327
328
329 def ensure_external_module(modulename, location):
330     """Add a location to sys.path if an external dependency can't be found.
331
332     :param modulename: Module name to import
333     :param location: Location to add to sys.path (can be relative to
334         ${srcdir}/lib)
335     """
336     try:
337         __import__(modulename)
338     except ImportError:
339         import_bundled_package(modulename, location)
340
341
342 from samba import _glue
343 version = _glue.version
344 interface_ips = _glue.interface_ips
345 set_debug_level = _glue.set_debug_level
346 get_debug_level = _glue.get_debug_level
347 unix2nttime = _glue.unix2nttime
348 nttime2string = _glue.nttime2string
349 nttime2unix = _glue.nttime2unix
350 unix2nttime = _glue.unix2nttime
351 generate_random_password = _glue.generate_random_password
352 strcasecmp_m = _glue.strcasecmp_m
353 strstr_m = _glue.strstr_m