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