fixed the build
[metze/samba/wip.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/../../../selftest/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 glue
46
47 class Ldb(ldb.Ldb):
48     """Simple Samba-specific LDB subclass that takes care 
49     of setting up the modules dir, credentials pointers, etc.
50     
51     Please note that this is intended to be for all Samba LDB files, 
52     not necessarily the Sam database. For Sam-specific helper 
53     functions see samdb.py.
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         glue.ldb_register_samba_handlers(self)
92
93         # TODO set debug
94         def msg(l,text):
95             print text
96         #self.set_debug(msg)
97
98         glue.ldb_set_utf8_casefold(self)
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 |= FLG_NOSYNC
105
106         if url is not None:
107             self.connect(url, flags, options)
108
109     def set_credentials(self, credentials):
110         glue.ldb_set_credentials(self, credentials)
111
112     def set_session_info(self, session_info):
113         glue.ldb_set_session_info(self, session_info)
114
115     def set_loadparm(self, lp_ctx):
116         glue.ldb_set_loadparm(self, lp_ctx)
117
118     def searchone(self, attribute, basedn=None, expression=None, 
119                   scope=ldb.SCOPE_BASE):
120         """Search for one attribute as a string.
121         
122         :param basedn: BaseDN for the search.
123         :param attribute: Name of the attribute
124         :param expression: Optional search expression.
125         :param scope: Search scope (defaults to base).
126         :return: Value of attribute as a string or None if it wasn't found.
127         """
128         res = self.search(basedn, scope, expression, [attribute])
129         if len(res) != 1 or res[0][attribute] is None:
130             return None
131         values = set(res[0][attribute])
132         assert len(values) == 1
133         return self.schema_format_value(attribute, values.pop())
134
135     def erase_except_schema_controlled(self):
136         """Erase this ldb, removing all records, except those that are controlled by Samba4's schema."""
137         basedn = ""
138         # Delete the 'visible' records
139         for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 
140                 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", 
141                 ["distinguishedName"]):
142             try:
143                 self.delete(msg.dn)
144             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
145                 # Ignore no such object errors
146                 pass
147
148         res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", ["distinguishedName"])
149         assert len(res) == 0
150
151         # delete the specials
152         for attr in ["@SUBCLASSES", "@MODULES", 
153                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
154             try:
155                 self.delete(attr)
156             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
157                 # Ignore missing dn errors
158                 pass
159
160     def erase(self):
161         """Erase this ldb, removing all records."""
162         
163         self.erase_except_schema_controlled()
164
165         # delete the specials
166         for attr in ["@INDEXLIST", "@ATTRIBUTES"]:
167             try:
168                 self.delete(attr)
169             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
170                 # Ignore missing dn errors
171                 pass
172
173     def erase_partitions(self):
174         """Erase an ldb, removing all records."""
175
176         def erase_recursive(self, dn):
177             try:
178                 res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[])
179             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
180                 # Ignore no such object errors
181                 return
182                 pass
183             
184             for msg in res:
185                 erase_recursive(self, msg.dn)
186
187             try:
188                 self.delete(dn)
189             except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _):
190                 # Ignore no such object errors
191                 pass
192
193         res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", 
194                          ["namingContexts"])
195         assert len(res) == 1
196         if not "namingContexts" in res[0]:
197             return
198         for basedn in res[0]["namingContexts"]:
199             # Try and erase from the bottom-up in the tree
200             erase_recursive(self, basedn)
201
202     def load_ldif_file_add(self, ldif_path):
203         """Load a LDIF file.
204
205         :param ldif_path: Path to LDIF file.
206         """
207         self.add_ldif(open(ldif_path, 'r').read())
208
209     def add_ldif(self, ldif):
210         """Add data based on a LDIF string.
211
212         :param ldif: LDIF text.
213         """
214         for changetype, msg in self.parse_ldif(ldif):
215             assert changetype == ldb.CHANGETYPE_NONE
216             self.add(msg)
217
218     def modify_ldif(self, ldif):
219         """Modify database based on a LDIF string.
220
221         :param ldif: LDIF text.
222         """
223         for changetype, msg in self.parse_ldif(ldif):
224             self.modify(msg)
225
226     def set_domain_sid(self, sid):
227         """Change the domain SID used by this LDB.
228
229         :param sid: The new domain sid to use.
230         """
231         glue.samdb_set_domain_sid(self, sid)
232
233     def set_schema_from_ldif(self, pf, df):
234         glue.dsdb_set_schema_from_ldif(self, pf, df)
235
236     def set_schema_from_ldb(self, ldb):
237         glue.dsdb_set_schema_from_ldb(self, ldb)
238
239     def convert_schema_to_openldap(self, target, mapping):
240         return glue.dsdb_convert_schema_to_openldap(self, target, mapping)
241
242     def set_invocation_id(self, invocation_id):
243         """Set the invocation id for this SamDB handle.
244         
245         :param invocation_id: GUID of the invocation id.
246         """
247         glue.dsdb_set_ntds_invocation_id(self, invocation_id)
248
249     def set_opaque_integer(self, name, value):
250         """Set an integer as an opaque (a flag or other value) value on the database
251         
252         :param name: The name for the opaque value
253         :param value: The integer value
254         """
255         glue.dsdb_set_opaque_integer(self, name, value)
256
257
258 def substitute_var(text, values):
259     """substitute strings of the form ${NAME} in str, replacing
260     with substitutions from subobj.
261     
262     :param text: Text in which to subsitute.
263     :param values: Dictionary with keys and values.
264     """
265
266     for (name, value) in values.items():
267         assert isinstance(name, str), "%r is not a string" % name
268         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
269         text = text.replace("${%s}" % name, value)
270
271     return text
272
273
274 def check_all_substituted(text):
275     """Make sure that all substitution variables in a string have been replaced.
276     If not, raise an exception.
277     
278     :param text: The text to search for substitution variables
279     """
280     if not "${" in text:
281         return
282     
283     var_start = text.find("${")
284     var_end = text.find("}", var_start)
285     
286     raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1])
287
288
289 def valid_netbios_name(name):
290     """Check whether a name is valid as a NetBIOS name. """
291     # See crh's book (1.4.1.1)
292     if len(name) > 15:
293         return False
294     for x in name:
295         if not x.isalnum() and not x in " !#$%&'()-.@^_{}~":
296             return False
297     return True
298
299
300 def dom_sid_to_rid(sid_str):
301     """Converts a domain SID to the relative RID.
302
303     :param sid_str: The domain SID formatted as string
304     """
305
306     return glue.dom_sid_to_rid(sid_str)
307
308
309 version = glue.version
310
311 DS_BEHAVIOR_WIN2000 = glue.DS_BEHAVIOR_WIN2000
312 DS_BEHAVIOR_WIN2003_INTERIM = glue.DS_BEHAVIOR_WIN2003_INTERIM
313 DS_BEHAVIOR_WIN2003 = glue.DS_BEHAVIOR_WIN2003
314 DS_BEHAVIOR_WIN2008 = glue.DS_BEHAVIOR_WIN2008