General cleanups of python code, hinted by pyflakes.
[nivanova/samba-autobuild/.git] / source4 / scripting / python / samba / schema.py
1 #
2 # Unix SMB/CIFS implementation.
3 # backend code for provisioning a Samba4 server
4 #
5 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
6 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008-2009
7 # Copyright (C) Oliver Liebel <oliver@itc.li> 2008-2009
8 #
9 # Based on the original in EJS:
10 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
11 #
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 3 of the License, or
15 # (at your option) any later version.
16 #   
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21 #   
22 # You should have received a copy of the GNU General Public License
23 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 #
25
26 """Functions for setting up a Samba Schema."""
27
28 from base64 import b64encode
29 from ms_schema import read_ms_schema
30 from samba.dcerpc import security
31 from samba import read_and_sub_file, substitute_var, check_all_substituted
32 from samba import Ldb
33 from samba.ndr import ndr_pack
34 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL
35 import os
36
37 def get_schema_descriptor(domain_sid):
38     sddl = "O:SAG:SAD:AI(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c" \
39            ";;ER)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ER)(OA;;CR;1131f6ad-9c07-1" \
40            "1d1-f79f-00c04fc2dcd2;;ER)(OA;;CR;e12b56b6-0a95-11d1-adbb-00c04fd8d5cd;;SA)(O" \
41            "A;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)(OA;;CR;1131f6aa-9c07-11d1-f79" \
42            "f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1" \
43            "131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04" \
44            "fc2dcd2;;BA)(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)(OA;;CR;1131f6aa" \
45            "-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2" \
46            ";;ED)(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ad-9c07-1" \
47            "1d1-f79f-00c04fc2dcd2;;ED)(A;;RPWPCCDCLCLORCWOWDSDDTSW;;;LA)(A;CI;RPWPCRCCLCL" \
48            "ORCWOWDSW;;;SA)(A;CI;RPLCLORC;;;AU)(A;CI;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)S:(O" \
49            "U;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)(OU;SA;CR;e12b56b6-0a95-11d1" \
50            "-adbb-00c04fd8d5cd;;WD)(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPCCDCWOWDSDDTSW;" \
51            ";;WD)(AU;CISA;WP;;;WD)"
52     sec = security.descriptor.from_sddl(sddl, domain_sid)
53     return ndr_pack(sec)
54
55    
56 class Schema(object):
57     def __init__(self, setup_path, domain_sid, schemadn=None,
58                  serverdn=None, files=None, prefixmap=None):
59         """Load schema for the SamDB from the AD schema files and samba4_schema.ldif
60         
61         :param samdb: Load a schema into a SamDB.
62         :param setup_path: Setup path function.
63         :param schemadn: DN of the schema
64         :param serverdn: DN of the server
65         
66         Returns the schema data loaded, to avoid double-parsing when then needing to add it to the db
67         """
68
69         self.schemadn = schemadn
70         self.ldb = Ldb()
71         self.schema_data = read_ms_schema(setup_path('ad-schema/MS-AD_Schema_2K8_R2_Attributes.txt'),
72                                           setup_path('ad-schema/MS-AD_Schema_2K8_R2_Classes.txt'))
73
74         if files is not None:
75             for file in files:
76                 self.schema_data += open(file, 'r').read()
77
78         self.schema_data = substitute_var(self.schema_data, {"SCHEMADN": schemadn})
79         check_all_substituted(self.schema_data)
80
81         self.schema_dn_modify = read_and_sub_file(setup_path("provision_schema_basedn_modify.ldif"),
82                                                   {"SCHEMADN": schemadn,
83                                                    "SERVERDN": serverdn,
84                                                    })
85
86         descr = b64encode(get_schema_descriptor(domain_sid))
87         self.schema_dn_add = read_and_sub_file(setup_path("provision_schema_basedn.ldif"),
88                                                {"SCHEMADN": schemadn,
89                                                 "DESCRIPTOR": descr
90                                                 })
91
92         self.prefixmap_data = open(setup_path("prefixMap.txt"), 'r').read()
93
94         if prefixmap is not None:
95             for map in prefixmap:
96                 self.prefixmap_data += "%s\n" % map
97
98         self.prefixmap_data = b64encode(self.prefixmap_data)
99
100         
101
102         # We don't actually add this ldif, just parse it
103         prefixmap_ldif = "dn: cn=schema\nprefixMap:: %s\n\n" % self.prefixmap_data
104         self.ldb.set_schema_from_ldif(prefixmap_ldif, self.schema_data)
105
106     def write_to_tmp_ldb(self, schemadb_path):
107         self.ldb.connect(schemadb_path)
108         self.ldb.transaction_start()
109     
110         self.ldb.add_ldif("""dn: @ATTRIBUTES
111 linkID: INTEGER
112
113 dn: @INDEXLIST
114 @IDXATTR: linkID
115 @IDXATTR: attributeSyntax
116 """)
117         # These bits of LDIF are supplied when the Schema object is created
118         self.ldb.add_ldif(self.schema_dn_add)
119         self.ldb.modify_ldif(self.schema_dn_modify)
120         self.ldb.add_ldif(self.schema_data)
121         self.ldb.transaction_commit()
122
123     # Return a hash with the forward attribute as a key and the back as the value 
124     def linked_attributes(self):
125         return get_linked_attributes(self.schemadn, self.ldb)
126
127     def dnsyntax_attributes(self):
128         return get_dnsyntax_attributes(self.schemadn, self.ldb)
129
130 # Return a hash with the forward attribute as a key and the back as the value 
131 def get_linked_attributes(schemadn,schemaldb):
132     attrs = ["linkID", "lDAPDisplayName"]
133     res = schemaldb.search(expression="(&(linkID=*)(!(linkID:1.2.840.113556.1.4.803:=1))(objectclass=attributeSchema)(attributeSyntax=2.5.5.1))", base=schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
134     attributes = {}
135     for i in range (0, len(res)):
136         expression = "(&(objectclass=attributeSchema)(linkID=%d)(attributeSyntax=2.5.5.1))" % (int(res[i]["linkID"][0])+1)
137         target = schemaldb.searchone(basedn=schemadn, 
138                                      expression=expression, 
139                                      attribute="lDAPDisplayName", 
140                                      scope=SCOPE_SUBTREE)
141         if target is not None:
142             attributes[str(res[i]["lDAPDisplayName"])]=str(target)
143             
144     return attributes
145
146 def get_dnsyntax_attributes(schemadn,schemaldb):
147     attrs = ["linkID", "lDAPDisplayName"]
148     res = schemaldb.search(expression="(&(!(linkID=*))(objectclass=attributeSchema)(attributeSyntax=2.5.5.1))", base=schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
149     attributes = []
150     for i in range (0, len(res)):
151         attributes.append(str(res[i]["lDAPDisplayName"]))
152         
153     return attributes
154
155 def ldb_with_schema(setup_dir=None, schemadn="cn=schema,cn=configuration,dc=example,dc=com", 
156                     serverdn="cn=server,cn=servers,cn=default-first-site-name,cn=sites,cn=cn=configuration,dc=example,dc=com",
157                     domainsid=None):
158     """Load schema for the SamDB from the AD schema files and samba4_schema.ldif
159     
160     :param setup_dir: Setup path
161     :param schemadn: DN of the schema
162     :param serverdn: DN of the server
163     
164     Returns the schema data loaded as an object, with .ldb being a
165     new ldb with the schema loaded.  This allows certain tests to
166     operate without a remote or local schema.
167     """
168     
169     def setup_path(file):
170         return os.path.join(setup_dir, file)
171
172     if domainsid is None:
173         domainsid = security.random_sid()
174     else:
175         domainsid = security.dom_sid(domainsid)
176     return Schema(setup_path, domainsid, schemadn=schemadn, serverdn=serverdn)