90f85851256d2f0d5f51724e333d3af85f2479dd
[nivanova/samba-autobuild/.git] / python / samba / __init__.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
3 #
4 # Based on the original in EJS:
5 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 """Samba 4."""
22
23 __docformat__ = "restructuredText"
24
25 import os
26 import sys
27 import time
28 import ldb
29 import samba.param
30 from samba import _glue
31 from samba._ldb import Ldb as _Ldb
32 from samba.compat import string_types
33
34
35 def source_tree_topdir():
36     """Return the top level source directory."""
37     paths = ["../../..", "../../../.."]
38     for p in paths:
39         topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
40         if os.path.exists(os.path.join(topdir, 'source4')):
41             return topdir
42     raise RuntimeError("unable to find top level source directory")
43
44
45 def in_source_tree():
46     """Return True if we are running from within the samba source tree"""
47     try:
48         topdir = source_tree_topdir()
49     except RuntimeError:
50         return False
51     return True
52
53
54 class Ldb(_Ldb):
55     """Simple Samba-specific LDB subclass that takes care
56     of setting up the modules dir, credentials pointers, etc.
57
58     Please note that this is intended to be for all Samba LDB files,
59     not necessarily the Sam database. For Sam-specific helper
60     functions see samdb.py.
61     """
62
63     def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
64                  credentials=None, flags=0, options=None):
65         """Opens a Samba Ldb file.
66
67         :param url: Optional LDB URL to open
68         :param lp: Optional loadparm object
69         :param modules_dir: Optional modules directory
70         :param session_info: Optional session information
71         :param credentials: Optional credentials, defaults to anonymous.
72         :param flags: Optional LDB flags
73         :param options: Additional options (optional)
74
75         This is different from a regular Ldb file in that the Samba-specific
76         modules-dir is used by default and that credentials and session_info
77         can be passed through (required by some modules).
78         """
79
80         if modules_dir is not None:
81             self.set_modules_dir(modules_dir)
82         else:
83             self.set_modules_dir(os.path.join(samba.param.modules_dir(), "ldb"))
84
85         if session_info is not None:
86             self.set_session_info(session_info)
87
88         if credentials is not None:
89             self.set_credentials(credentials)
90
91         if lp is not None:
92             self.set_loadparm(lp)
93
94         # This must be done before we load the schema, as these handlers for
95         # objectSid and objectGUID etc must take precedence over the 'binary
96         # attribute' declaration in the schema
97         self.register_samba_handlers()
98
99         # TODO set debug
100         def msg(l, text):
101             print(text)
102         # self.set_debug(msg)
103
104         self.set_utf8_casefold()
105
106         # Allow admins to force non-sync ldb for all databases
107         if lp is not None:
108             nosync_p = lp.get("ldb:nosync")
109             if nosync_p is not None and nosync_p:
110                 flags |= ldb.FLG_NOSYNC
111
112         self.set_create_perms(0o600)
113
114         if url is not None:
115             self.connect(url, flags, options)
116
117     def searchone(self, attribute, basedn=None, expression=None,
118                   scope=ldb.SCOPE_BASE):
119         """Search for one attribute as a string.
120
121         :param basedn: BaseDN for the search.
122         :param attribute: Name of the attribute
123         :param expression: Optional search expression.
124         :param scope: Search scope (defaults to base).
125         :return: Value of attribute as a string or None if it wasn't found.
126         """
127         res = self.search(basedn, scope, expression, [attribute])
128         if len(res) != 1 or res[0][attribute] is None:
129             return None
130         values = set(res[0][attribute])
131         assert len(values) == 1
132         return self.schema_format_value(attribute, values.pop())
133
134     def erase_users_computers(self, dn):
135         """Erases user and computer objects from our AD.
136
137         This is needed since the 'samldb' module denies the deletion of primary
138         groups. Therefore all groups shouldn't be primary somewhere anymore.
139         """
140
141         try:
142             res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
143                               expression="(|(objectclass=user)(objectclass=computer))")
144         except ldb.LdbError as error:
145             (errno, estr) = error.args
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 as error:
156             (errno, estr) = error.args
157             if errno != ldb.ERR_NO_SUCH_OBJECT:
158                 # Ignore no such object errors
159                 raise
160
161     def erase_except_schema_controlled(self):
162         """Erase this ldb.
163
164         :note: Removes all records, except those that are controlled by
165             Samba4's schema.
166         """
167
168         basedn = ""
169
170         # Try to delete user/computer accounts to allow deletion of groups
171         self.erase_users_computers(basedn)
172
173         # Delete the 'visible' records, and the invisble 'deleted' records (if
174         # this DB supports it)
175         for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
176                                "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
177                                [], controls=["show_deleted:0", "show_recycled:0"]):
178             try:
179                 self.delete(msg.dn, ["relax:0"])
180             except ldb.LdbError as error:
181                 (errno, estr) = error.args
182                 if errno != ldb.ERR_NO_SUCH_OBJECT:
183                     # Ignore no such object errors
184                     raise
185
186         res = self.search(basedn, ldb.SCOPE_SUBTREE,
187                           "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
188                           [], controls=["show_deleted:0", "show_recycled:0"])
189         assert len(res) == 0
190
191         # delete the specials
192         for attr in ["@SUBCLASSES", "@MODULES",
193                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
194             try:
195                 self.delete(attr, ["relax:0"])
196             except ldb.LdbError as error:
197                 (errno, estr) = error.args
198                 if errno != ldb.ERR_NO_SUCH_OBJECT:
199                     # Ignore missing dn errors
200                     raise
201
202     def erase(self):
203         """Erase this ldb, removing all records."""
204         self.erase_except_schema_controlled()
205
206         # delete the specials
207         for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
208             try:
209                 self.delete(attr, ["relax:0"])
210             except ldb.LdbError as error:
211                 (errno, estr) = error.args
212                 if errno != ldb.ERR_NO_SUCH_OBJECT:
213                     # Ignore missing dn errors
214                     raise
215
216     def load_ldif_file_add(self, ldif_path):
217         """Load a LDIF file.
218
219         :param ldif_path: Path to LDIF file.
220         """
221         self.add_ldif(open(ldif_path, 'r').read())
222
223     def add_ldif(self, ldif, controls=None):
224         """Add data based on a LDIF string.
225
226         :param ldif: LDIF text.
227         """
228         for changetype, msg in self.parse_ldif(ldif):
229             assert changetype == ldb.CHANGETYPE_NONE
230             self.add(msg, controls)
231
232     def modify_ldif(self, ldif, controls=None):
233         """Modify database based on a LDIF string.
234
235         :param ldif: LDIF text.
236         """
237         for changetype, msg in self.parse_ldif(ldif):
238             if changetype == ldb.CHANGETYPE_ADD:
239                 self.add(msg, controls)
240             else:
241                 self.modify(msg, controls)
242
243
244 def substitute_var(text, values):
245     """Substitute strings of the form ${NAME} in str, replacing
246     with substitutions from values.
247
248     :param text: Text in which to subsitute.
249     :param values: Dictionary with keys and values.
250     """
251
252     for (name, value) in values.items():
253         assert isinstance(name, string_types), "%r is not a string" % name
254         assert isinstance(value, string_types), "Value %r for %s is not a string" % (value, name)
255         text = text.replace("${%s}" % name, value)
256
257     return text
258
259
260 def check_all_substituted(text):
261     """Check that all substitution variables in a string have been replaced.
262
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" %
274                     text[var_start:var_end + 1])
275
276
277 def read_and_sub_file(file_name, subst_vars):
278     """Read a file and sub in variables found in it
279
280     :param file_name: File to be read (typically from setup directory)
281      param subst_vars: Optional variables to subsitute in the file.
282     """
283     data = open(file_name, 'r').read()
284     if subst_vars is not None:
285         data = substitute_var(data, subst_vars)
286         check_all_substituted(data)
287     return data
288
289
290 def setup_file(template, fname, subst_vars=None):
291     """Setup a file in the private dir.
292
293     :param template: Path of the template file.
294     :param fname: Path of the file to create.
295     :param subst_vars: Substitution variables.
296     """
297     if os.path.exists(fname):
298         os.unlink(fname)
299
300     data = read_and_sub_file(template, subst_vars)
301     f = open(fname, 'w')
302     try:
303         f.write(data)
304     finally:
305         f.close()
306
307 MAX_NETBIOS_NAME_LEN = 15
308
309
310 def is_valid_netbios_char(c):
311     return (c.isalnum() or c in " !#$%&'()-.@^_{}~")
312
313
314 def valid_netbios_name(name):
315     """Check whether a name is valid as a NetBIOS name. """
316     # See crh's book (1.4.1.1)
317     if len(name) > MAX_NETBIOS_NAME_LEN:
318         return False
319     for x in name:
320         if not is_valid_netbios_char(x):
321             return False
322     return True
323
324
325 def import_bundled_package(modulename, location, source_tree_container,
326                            namespace):
327     """Import the bundled version of a package.
328
329     :note: This should only be called if the system version of the package
330         is not adequate.
331
332     :param modulename: Module name to import
333     :param location: Location to add to sys.path (can be relative to
334         ${srcdir}/${source_tree_container})
335     :param source_tree_container: Directory under source root that
336         contains the bundled third party modules.
337     :param namespace: Namespace to import module from, when not in source tree
338     """
339     if in_source_tree():
340         extra_path = os.path.join(source_tree_topdir(), source_tree_container,
341                                   location)
342         if not extra_path in sys.path:
343             sys.path.insert(0, extra_path)
344         sys.modules[modulename] = __import__(modulename)
345     else:
346         sys.modules[modulename] = __import__(
347             "%s.%s" % (namespace, modulename), fromlist=[namespace])
348
349
350 def ensure_third_party_module(modulename, location):
351     """Add a location to sys.path if a third party dependency can't be found.
352
353     :param modulename: Module name to import
354     :param location: Location to add to sys.path (can be relative to
355         ${srcdir}/third_party)
356     """
357     try:
358         __import__(modulename)
359     except ImportError:
360         import_bundled_package(modulename, location,
361                                source_tree_container="third_party",
362                                namespace="samba.third_party")
363
364
365 def dn_from_dns_name(dnsdomain):
366     """return a DN from a DNS name domain/forest root"""
367     return "DC=" + ",DC=".join(dnsdomain.split("."))
368
369
370 def current_unix_time():
371     return int(time.time())
372
373
374 def string_to_byte_array(string):
375     blob = [0] * len(string)
376
377     for i in range(len(string)):
378         blob[i] = ord(string[i])
379
380     return blob
381
382
383 def arcfour_encrypt(key, data):
384     from samba.crypto import arcfour_crypt_blob
385     return arcfour_crypt_blob(data, key)
386
387 version = _glue.version
388 interface_ips = _glue.interface_ips
389 fault_setup = _glue.fault_setup
390 set_debug_level = _glue.set_debug_level
391 get_debug_level = _glue.get_debug_level
392 unix2nttime = _glue.unix2nttime
393 nttime2string = _glue.nttime2string
394 nttime2unix = _glue.nttime2unix
395 unix2nttime = _glue.unix2nttime
396 generate_random_password = _glue.generate_random_password
397 generate_random_machine_password = _glue.generate_random_machine_password
398 check_password_quality = _glue.check_password_quality
399 generate_random_bytes = _glue.generate_random_bytes
400 strcasecmp_m = _glue.strcasecmp_m
401 strstr_m = _glue.strstr_m
402 is_ntvfs_fileserver_built = _glue.is_ntvfs_fileserver_built
403 is_heimdal_built = _glue.is_heimdal_built
404
405 NTSTATUSError = _glue.NTSTATUSError
406 HRESULTError = _glue.HRESULTError
407 WERRORError = _glue.WERRORError
408 DsExtendedError = _glue.DsExtendedError