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