r26628: python: Add more documentation, simplify code in Samba3 module.
[ira/wip.git] / source4 / scripting / python / samba / __init__.py
1 #!/usr/bin/python
2
3 # Unix SMB/CIFS implementation.
4 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
5 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
6 #   
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #   
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #   
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 import os
22
23 def _in_source_tree():
24     """Check whether the script is being run from the source dir. """
25     return os.path.exists("%s/../../../samba4-skip" % os.path.dirname(__file__))
26
27
28 # When running, in-tree, make sure bin/python is in the PYTHONPATH
29 if _in_source_tree():
30     import sys
31     srcdir = "%s/../../.." % os.path.dirname(__file__)
32     sys.path.append("%s/bin/python" % srcdir)
33     default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir
34
35
36 import ldb
37 import credentials
38 import misc
39
40 class Ldb(ldb.Ldb):
41     """Simple Samba-specific LDB subclass that takes care 
42     of setting up the modules dir, credentials pointers, etc.
43     
44     Please note that this is intended to be for all Samba LDB files, 
45     not necessarily the Sam database. For Sam-specific helper 
46     functions see samdb.py.
47     """
48     def __init__(self, url=None, session_info=None, credentials=None, 
49                  modules_dir=None, lp=None):
50         """Open a Samba Ldb file. 
51
52         :param url: Optional LDB URL to open
53         :param session_info: Optional session information
54         :param credentials: Optional credentials, defaults to anonymous.
55         :param modules_dir: Modules directory, if not the default.
56         :param lp: Loadparm object, optional.
57
58         This is different from a regular Ldb file in that the Samba-specific
59         modules-dir is used by default and that credentials and session_info 
60         can be passed through (required by some modules).
61         """
62         super(Ldb, self).__init__()
63
64         if modules_dir is not None:
65             self.set_modules_dir(modules_dir)
66         elif default_ldb_modules_dir is not None:
67             self.set_modules_dir(default_ldb_modules_dir)
68
69         if credentials is not None:
70             self.set_credentials(self, credentials)
71
72         if session_info is not None:
73             self.set_session_info(self, session_info)
74
75         assert misc.ldb_register_samba_handlers(self) == 0
76
77         if lp is not None:
78             self.set_loadparm(self, lp)
79
80         def msg(l,text):
81             print text
82         #self.set_debug(msg)
83
84         if url is not None:
85             self.connect(url)
86
87
88     set_credentials = misc.ldb_set_credentials
89     set_session_info = misc.ldb_set_session_info
90     set_loadparm = misc.ldb_set_loadparm
91
92     def searchone(self, basedn, attribute, expression=None, 
93                   scope=ldb.SCOPE_BASE):
94         """Search for one attribute as a string.
95         
96         :param basedn: BaseDN for the search.
97         :param attribute: Name of the attribute
98         :param expression: Optional search expression.
99         :param scope: Search scope (defaults to base).
100         :return: Value of attribute as a string or None if it wasn't found.
101         """
102         res = self.search(basedn, scope, expression, [attribute])
103         if len(res) != 1 or res[0][attribute] is None:
104             return None
105         values = set(res[0][attribute])
106         assert len(values) == 1
107         return values.pop()
108
109     def erase(self):
110         """Erase this ldb, removing all records."""
111         # delete the specials
112         for attr in ["@INDEXLIST", "@ATTRIBUTES", "@SUBCLASSES", "@MODULES", 
113                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
114             try:
115                 self.delete(ldb.Dn(self, attr))
116             except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
117                 # Ignore missing dn errors
118                 pass
119
120         basedn = ldb.Dn(self, "")
121         # and the rest
122         for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 
123                 "(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", 
124                 ["dn"]):
125             try:
126                 self.delete(msg.dn)
127             except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
128                 # Ignor eno such object errors
129                 pass
130
131         res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", ["dn"])
132         assert len(res) == 0
133
134     def erase_partitions(self):
135         """Erase an ldb, removing all records."""
136         res = self.search(ldb.Dn(self, ""), ldb.SCOPE_BASE, "(objectClass=*)", 
137                          ["namingContexts"])
138         assert len(res) == 1
139         if not "namingContexts" in res[0]:
140             return
141         for basedn in res[0]["namingContexts"]:
142             previous_remaining = 1
143             current_remaining = 0
144
145             k = 0
146             while ++k < 10 and (previous_remaining != current_remaining):
147                 # and the rest
148                 res2 = self.search(ldb.Dn(self, basedn), ldb.SCOPE_SUBTREE, "(|(objectclass=*)(dn=*))", ["dn"])
149                 previous_remaining = current_remaining
150                 current_remaining = len(res2)
151                 for msg in res2:
152                     self.delete(msg.dn)
153
154     def load_ldif_file_add(self, ldif_path):
155         """Load a LDIF file.
156
157         :param ldif_path: Path to LDIF file.
158         """
159         self.add_ldif(open(ldif_path, 'r').read())
160
161     def add_ldif(self, ldif):
162         """Add data based on a LDIF string.
163
164         :param ldif: LDIF text.
165         """
166         for changetype, msg in self.parse_ldif(ldif):
167             assert changetype == ldb.CHANGETYPE_NONE
168             self.add(msg)
169
170     def modify_ldif(self, ldif):
171         """Modify database based on a LDIF string.
172
173         :param ldif: LDIF text.
174         """
175         for (changetype, msg) in self.parse_ldif(ldif):
176             assert changetype == ldb.CHANGETYPE_MODIFY
177             self.modify(msg)
178
179
180 def substitute_var(text, values):
181     """substitute strings of the form ${NAME} in str, replacing
182     with substitutions from subobj.
183     
184     :param text: Text in which to subsitute.
185     :param values: Dictionary with keys and values.
186     """
187
188     for (name, value) in values.items():
189         assert isinstance(name, str), "%r is not a string" % name
190         assert isinstance(value, str), "Value %r for %s is not a string" % (value, name)
191         text = text.replace("${%s}" % name, value)
192
193     return text
194
195
196 def valid_netbios_name(name):
197     """Check whether a name is valid as a NetBIOS name. """
198     # FIXME: There are probably more constraints here. 
199     # crh has a paragraph on this in his book (1.4.1.1)
200     if len(name) > 13:
201         return False
202     return True
203
204 version = misc.version