r26521: Fix newlines.
[kai/samba.git] / source / 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         if lp is not None:
76             self.set_loadparm(self, lp)
77
78         if url:
79             self.connect(url)
80
81         def msg(l,text):
82             print text
83         self.set_debug(msg)
84
85     set_credentials = misc.ldb_set_credentials
86     set_session_info = misc.ldb_set_session_info
87     set_loadparm = misc.ldb_set_loadparm
88
89     def searchone(self, basedn, expression, attribute):
90         """Search for one attribute as a string."""
91         res = self.search(basedn, SCOPE_SUBTREE, expression, [attribute])
92         if len(res) != 1 or res[0][attribute] is None:
93             return None
94         return res[0][attribute]
95
96     def erase(self):
97         """Erase an ldb, removing all records."""
98         # delete the specials
99         for attr in ["@INDEXLIST", "@ATTRIBUTES", "@SUBCLASSES", "@MODULES", 
100                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
101             try:
102                 self.delete(ldb.Dn(self, attr))
103             except ldb.LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
104                 # Ignore missing dn errors
105                 pass
106
107         basedn = ldb.Dn(self, "")
108         # and the rest
109         for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 
110                 "(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", 
111                 ["dn"]):
112             self.delete(msg.dn)
113
114         res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", ["dn"])
115         assert len(res) == 0
116
117
118 def substitute_var(text, values):
119     """substitute strings of the form ${NAME} in str, replacing
120     with substitutions from subobj.
121     
122     :param text: Text in which to subsitute.
123     :param values: Dictionary with keys and values.
124     """
125
126     for (name, value) in values.items():
127         text = text.replace("${%s}" % name, value)
128
129     assert "${" not in text, text
130
131     return text
132
133
134 def valid_netbios_name(name):
135     """Check whether a name is valid as a NetBIOS name. """
136     # FIXME: There are probably more constraints here. 
137     # crh has a paragraph on this in his book (1.4.1.1)
138     if len(name) > 13:
139         return False
140     return True
141
142 version = misc.version