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