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