Merge branch 'v4-0-test' of ssh://git.samba.org/data/git/samba into v4-0-wsgi
[kai/samba.git] / source / 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 __docformat__ = "restructuredText"
24
25 import os
26
27 def _in_source_tree():
28     """Check whether the script is being run from the source dir. """
29     return os.path.exists("%s/../../../samba4-skip" % os.path.dirname(__file__))
30
31
32 # When running, in-tree, make sure bin/python is in the PYTHONPATH
33 if _in_source_tree():
34     import sys
35     srcdir = "%s/../../.." % os.path.dirname(__file__)
36     sys.path.append("%s/bin/python" % srcdir)
37     default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir
38 else:
39     default_ldb_modules_dir = None
40
41
42 import ldb
43 import credentials
44 import misc
45
46 class Ldb(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     def __init__(self, url=None, session_info=None, credentials=None, 
55                  modules_dir=None, lp=None):
56         """Open a Samba Ldb file. 
57
58         :param url: Optional LDB URL to open
59         :param session_info: Optional session information
60         :param credentials: Optional credentials, defaults to anonymous.
61         :param modules_dir: Modules directory, if not the default.
62         :param lp: Loadparm object, optional.
63
64         This is different from a regular Ldb file in that the Samba-specific
65         modules-dir is used by default and that credentials and session_info 
66         can be passed through (required by some modules).
67         """
68         super(Ldb, self).__init__()
69
70         if modules_dir is not None:
71             self.set_modules_dir(modules_dir)
72         elif default_ldb_modules_dir is not None:
73             self.set_modules_dir(default_ldb_modules_dir)
74
75         if credentials is not None:
76             self.set_credentials(credentials)
77
78         if session_info is not None:
79             self.set_session_info(session_info)
80
81         assert misc.ldb_register_samba_handlers(self) == 0
82
83         if lp is not None:
84             self.set_loadparm(lp)
85
86         def msg(l,text):
87             print text
88         #self.set_debug(msg)
89
90         if url is not None:
91             self.connect(url)
92
93
94     set_credentials = misc.ldb_set_credentials
95     set_session_info = misc.ldb_set_session_info
96     set_loadparm = misc.ldb_set_loadparm
97
98     def searchone(self, attribute, basedn=None, expression=None, 
99                   scope=ldb.SCOPE_BASE):
100         """Search for one attribute as a string.
101         
102         :param basedn: BaseDN for the search.
103         :param attribute: Name of the attribute
104         :param expression: Optional search expression.
105         :param scope: Search scope (defaults to base).
106         :return: Value of attribute as a string or None if it wasn't found.
107         """
108         res = self.search(basedn, scope, expression, [attribute])
109         if len(res) != 1 or res[0][attribute] is None:
110             return None
111         values = set(res[0][attribute])
112         assert len(values) == 1
113         return self.schema_format_value(attribute, values.pop())
114
115     def erase(self):
116         """Erase this ldb, removing all records."""
117         # delete the specials
118         for attr in ["@INDEXLIST", "@ATTRIBUTES", "@SUBCLASSES", "@MODULES", 
119                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
120             try:
121                 self.delete(attr)
122             except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
123                 # Ignore missing dn errors
124                 pass
125
126         basedn = ""
127         # and the rest
128         for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 
129                 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", 
130                 ["distinguishedName"]):
131             try:
132                 self.delete(msg.dn)
133             except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
134                 # Ignore no such object errors
135                 pass
136
137         res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", ["distinguishedName"])
138         assert len(res) == 0
139
140     def erase_partitions(self):
141         """Erase an ldb, removing all records."""
142         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", 
143                          ["namingContexts"])
144         assert len(res) == 1
145         if not "namingContexts" in res[0]:
146             return
147         for basedn in res[0]["namingContexts"]:
148             previous_remaining = 1
149             current_remaining = 0
150
151             k = 0
152             while ++k < 10 and (previous_remaining != current_remaining):
153                 # and the rest
154                 try:
155                     res2 = self.search(basedn, ldb.SCOPE_SUBTREE, "(|(objectclass=*)(distinguishedName=*))", ["distinguishedName"])
156                 except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
157                     # Ignore missing dn errors
158                     return
159
160                 previous_remaining = current_remaining
161                 current_remaining = len(res2)
162                 for msg in res2:
163                     try:
164                         self.delete(msg.dn)
165                     # Ignore no such object errors
166                     except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
167                         pass
168                     # Ignore not allowed on non leaf errors
169                     except ldb.LdbError, (LDB_ERR_NOT_ALLOWED_ON_NON_LEAF, _):
170                         pass
171
172     def load_ldif_file_add(self, ldif_path):
173         """Load a LDIF file.
174
175         :param ldif_path: Path to LDIF file.
176         """
177         self.add_ldif(open(ldif_path, 'r').read())
178
179     def add_ldif(self, ldif):
180         """Add data based on a LDIF string.
181
182         :param ldif: LDIF text.
183         """
184         for changetype, msg in self.parse_ldif(ldif):
185             assert changetype == ldb.CHANGETYPE_NONE
186             self.add(msg)
187
188     def modify_ldif(self, ldif):
189         """Modify database based on a LDIF string.
190
191         :param ldif: LDIF text.
192         """
193         for changetype, msg in self.parse_ldif(ldif):
194             self.modify(msg)
195
196
197 def substitute_var(text, values):
198     """substitute strings of the form ${NAME} in str, replacing
199     with substitutions from subobj.
200     
201     :param text: Text in which to subsitute.
202     :param values: Dictionary with keys and values.
203     """
204
205     for (name, value) in values.items():
206         assert isinstance(name, str), "%r is not a string" % name
207         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
208         text = text.replace("${%s}" % name, value)
209
210     return text
211
212
213 def check_all_substituted(text):
214     """Make sure that all substitution variables in a string have been replaced.
215     If not, raise an exception.
216     
217     :param text: The text to search for substitution variables
218     """
219     if not "${" in text:
220         return
221     
222     var_start = text.find("${")
223     var_end = text.find("}", var_start)
224     
225     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
226
227
228 def valid_netbios_name(name):
229     """Check whether a name is valid as a NetBIOS name. """
230     # FIXME: There are probably more constraints here. 
231     # crh has a paragraph on this in his book (1.4.1.1)
232     if len(name) > 15:
233         return False
234     return True
235
236 version = misc.version