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