r26496: Move some provision functions to a new SamDB class, support setting session_i...
[amitay/samba.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 misc
37 import ldb
38 ldb.Ldb.set_credentials = misc.ldb_set_credentials
39 ldb.Ldb.set_session_info = misc.ldb_set_session_info
40 ldb.Ldb.set_loadparm = misc.ldb_set_loadparm
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__(url, session_info=None, credentials=None, modules_dir=None, 
51             lp=None):
52         """Open a Samba Ldb file. 
53
54         :param url: 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, automatically set if not specified.
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(self, Ldb).__init__()
65         import ldb
66         ret = ldb.Ldb()
67         if modules_dir is None:
68             modules_dir = default_ldb_modules_dir
69         if modules_dir is not None:
70             ret.set_modules_dir(modules_dir)
71         def samba_debug(level,text):
72             print "%d %s" % (level, text)
73         if credentials is not None:
74             ldb.set_credentials(credentials)
75         if session_info is not None:
76             ldb.set_session_info(session_info)
77         if lp is not None:
78             ldb.set_loadparm(lp)
79         #ret.set_debug(samba_debug)
80         ret.connect(url)
81         return ret
82
83     def searchone(self, basedn, expression, attribute):
84         """Search for one attribute as a string."""
85         res = self.search(basedn, SCOPE_SUBTREE, expression, [attribute])
86         if len(res) != 1 or res[0][attribute] is None:
87             return None
88         return res[0][attribute]
89
90     def erase(self):
91         """Erase an ldb, removing all records."""
92         # delete the specials
93         for attr in ["@INDEXLIST", "@ATTRIBUTES", "@SUBCLASSES", "@MODULES", 
94                      "@OPTIONS", "@PARTITION", "@KLUDGEACL"]:
95             try:
96                 self.delete(Dn(self, attr))
97             except LdbError, (LDB_ERR_NO_SUCH_OBJECT, _):
98                 # Ignore missing dn errors
99                 pass
100
101         basedn = Dn(self, "")
102         # and the rest
103         for msg in self.search(basedn, SCOPE_SUBTREE, 
104                 "(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", 
105                 ["dn"]):
106             self.delete(msg.dn)
107
108         res = self.search(basedn, SCOPE_SUBTREE, "(&(|(objectclass=*)(dn=*))(!(dn=@BASEINFO)))", ["dn"])
109         assert len(res) == 0
110
111
112 def substitute_var(text, values):
113     """substitute strings of the form ${NAME} in str, replacing
114     with substitutions from subobj.
115     
116     :param text: Text in which to subsitute.
117     :param values: Dictionary with keys and values.
118     """
119
120     for (name, value) in values.items():
121         text = text.replace("${%s}" % name, value)
122
123     return text
124
125
126 def valid_netbios_name(name):
127     """Check whether a name is valid as a NetBIOS name. """
128     # FIXME: There are probably more constraints here. 
129     # crh has a paragraph on this in his book (1.4.1.1)
130     if len(name) > 13:
131         return False
132     return True
133