python/samba: port some isinstance str checks (to cater for unicode)
[nivanova/samba-autobuild/.git] / python / samba / ms_schema.py
1 # create schema.ldif (as a string) from WSPP documentation
2 #
3 # based on minschema.py and minschema_wspp
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import print_function
19 """Generate LDIF from WSPP documentation."""
20
21 import re
22 import base64
23 import uuid
24 from samba.compat import string_types
25
26 bitFields = {}
27
28 # ADTS: 2.2.9
29 # bit positions as labeled in the docs
30 bitFields["searchflags"] = {
31     'fATTINDEX': 31,         # IX
32     'fPDNTATTINDEX': 30,     # PI
33     'fANR': 29,  # AR
34     'fPRESERVEONDELETE': 28,         # PR
35     'fCOPY': 27,     # CP
36     'fTUPLEINDEX': 26,       # TP
37     'fSUBTREEATTINDEX': 25,  # ST
38     'fCONFIDENTIAL': 24,     # CF
39     'fNEVERVALUEAUDIT': 23,  # NV
40     'fRODCAttribute': 22,    # RO
41
42
43     # missing in ADTS but required by LDIF
44     'fRODCFilteredAttribute': 22,    # RO ?
45     'fCONFIDENTAIL': 24, # typo
46     'fRODCFILTEREDATTRIBUTE': 22 # case
47     }
48
49 # ADTS: 2.2.10
50 bitFields["systemflags"] = {
51     'FLAG_ATTR_NOT_REPLICATED': 31, 'FLAG_CR_NTDS_NC': 31,     # NR
52     'FLAG_ATTR_REQ_PARTIAL_SET_MEMBER': 30, 'FLAG_CR_NTDS_DOMAIN': 30,     # PS
53     'FLAG_ATTR_IS_CONSTRUCTED': 29, 'FLAG_CR_NTDS_NOT_GC_REPLICATED': 29,     # CS
54     'FLAG_ATTR_IS_OPERATIONAL': 28,     # OP
55     'FLAG_SCHEMA_BASE_OBJECT': 27,     # BS
56     'FLAG_ATTR_IS_RDN': 26,     # RD
57     'FLAG_DISALLOW_MOVE_ON_DELETE': 6,     # DE
58     'FLAG_DOMAIN_DISALLOW_MOVE': 5,     # DM
59     'FLAG_DOMAIN_DISALLOW_RENAME': 4,     # DR
60     'FLAG_CONFIG_ALLOW_LIMITED_MOVE': 3,     # AL
61     'FLAG_CONFIG_ALLOW_MOVE': 2,     # AM
62     'FLAG_CONFIG_ALLOW_RENAME': 1,     # AR
63     'FLAG_DISALLOW_DELETE': 0     # DD
64     }
65
66 # ADTS: 2.2.11
67 bitFields["schemaflagsex"] = {
68     'FLAG_ATTR_IS_CRITICAL': 31
69     }
70
71 # ADTS: 3.1.1.2.2.2
72 oMObjectClassBER = {
73     '1.3.12.2.1011.28.0.702' : base64.b64encode(b'\x2B\x0C\x02\x87\x73\x1C\x00\x85\x3E').decode('utf8'),
74     '1.2.840.113556.1.1.1.12': base64.b64encode(b'\x2A\x86\x48\x86\xF7\x14\x01\x01\x01\x0C').decode('utf8'),
75     '2.6.6.1.2.5.11.29'      : base64.b64encode(b'\x56\x06\x01\x02\x05\x0B\x1D').decode('utf8'),
76     '1.2.840.113556.1.1.1.11': base64.b64encode(b'\x2A\x86\x48\x86\xF7\x14\x01\x01\x01\x0B').decode('utf8'),
77     '1.3.12.2.1011.28.0.714' : base64.b64encode(b'\x2B\x0C\x02\x87\x73\x1C\x00\x85\x4A').decode('utf8'),
78     '1.3.12.2.1011.28.0.732' : base64.b64encode(b'\x2B\x0C\x02\x87\x73\x1C\x00\x85\x5C').decode('utf8'),
79     '1.2.840.113556.1.1.1.6' : base64.b64encode(b'\x2A\x86\x48\x86\xF7\x14\x01\x01\x01\x06').decode('utf8')
80 }
81
82 # separated by commas in docs, and must be broken up
83 multivalued_attrs = set(["auxiliaryclass","maycontain","mustcontain","posssuperiors",
84                          "systemauxiliaryclass","systemmaycontain","systemmustcontain",
85                          "systemposssuperiors"])
86
87 def __read_folded_line(f, buffer):
88     """ reads a line from an LDIF file, unfolding it"""
89     line = buffer
90
91     while True:
92         l = f.readline()
93
94         if l[:1] == " ":
95             # continued line
96
97             # cannot fold an empty line
98             assert(line != "" and line != "\n")
99
100             # preserves '\n '
101             line = line + l
102         else:
103             # non-continued line
104             if line == "":
105                 line = l
106
107                 if l == "":
108                     # eof, definitely won't be folded
109                     break
110             else:
111                 # marks end of a folded line
112                 # line contains the now unfolded line
113                 # buffer contains the start of the next possibly folded line
114                 buffer = l
115                 break
116
117     return (line, buffer)
118
119
120 def __read_raw_entries(f):
121     """reads an LDIF entry, only unfolding lines"""
122     import sys
123
124     # will not match options after the attribute type
125     attr_type_re = re.compile("^([A-Za-z]+[A-Za-z0-9-]*):")
126
127     buffer = ""
128
129     while True:
130         entry = []
131
132         while True:
133             (l, buffer) = __read_folded_line(f, buffer)
134
135             if l[:1] == "#":
136                 continue
137
138             if l == "\n" or l == "":
139                 break
140
141             m = attr_type_re.match(l)
142
143             if m:
144                 if l[-1:] == "\n":
145                     l = l[:-1]
146
147                 entry.append(l)
148             else:
149                 print("Invalid line: %s" % l, end=' ', file=sys.stderr)
150                 sys.exit(1)
151
152         if len(entry):
153             yield entry
154
155         if l == "":
156             break
157
158
159 def fix_dn(dn):
160     """fix a string DN to use ${SCHEMADN}"""
161
162     # folding?
163     if dn.find("<RootDomainDN>") != -1:
164         dn = dn.replace("\n ", "")
165         dn = dn.replace(" ", "")
166         return dn.replace("CN=Schema,CN=Configuration,<RootDomainDN>", "${SCHEMADN}")
167     elif dn.endswith("DC=X"):
168         return dn.replace("CN=Schema,CN=Configuration,DC=X", "${SCHEMADN}")
169     elif dn.endswith("CN=X"):
170         return dn.replace("CN=Schema,CN=Configuration,CN=X", "${SCHEMADN}")
171     else:
172         return dn
173
174 def __convert_bitfield(key, value):
175     """Evaluate the OR expression in 'value'"""
176     assert(isinstance(value, string_types))
177
178     value = value.replace("\n ", "")
179     value = value.replace(" ", "")
180
181     try:
182         # some attributes already have numeric values
183         o = int(value)
184     except ValueError:
185         o = 0
186         flags = value.split("|")
187         for f in flags:
188             bitpos = bitFields[key][f]
189             o = o | (1 << (31 - bitpos))
190
191     return str(o)
192
193 def __write_ldif_one(entry):
194     """Write out entry as LDIF"""
195     out = []
196
197     for l in entry:
198         if isinstance(l[1], string_types):
199             vl = [l[1]]
200         else:
201             vl = l[1]
202
203         if l[2]:
204             out.append("%s:: %s" % (l[0], l[1]))
205             continue
206
207         for v in vl:
208             out.append("%s: %s" % (l[0], v))
209
210
211     return "\n".join(out)
212
213 def __transform_entry(entry, objectClass):
214     """Perform transformations required to convert the LDIF-like schema
215        file entries to LDIF, including Samba-specific stuff."""
216
217     entry = [l.split(":", 1) for l in entry]
218
219     cn = ""
220     skip_dn = skip_objectclass = skip_admin_description = skip_admin_display_name = False
221
222     for l in entry:
223         if l[1].startswith(': '):
224             l.append(True)
225             l[1] = l[1][2:]
226         else:
227             l.append(False)
228
229         key = l[0].lower()
230         l[1] = l[1].lstrip()
231         l[1] = l[1].rstrip()
232
233         if not cn and key == "cn":
234             cn = l[1]
235
236         if key in multivalued_attrs:
237             # unlike LDIF, these are comma-separated
238             l[1] = l[1].replace("\n ", "")
239             l[1] = l[1].replace(" ", "")
240
241             l[1] = l[1].split(",")
242
243         if key in bitFields:
244             l[1] = __convert_bitfield(key, l[1])
245
246         if key == "omobjectclass":
247             if not l[2]:
248                 l[1] = oMObjectClassBER[l[1].strip()]
249                 l[2] = True
250
251         if isinstance(l[1], string_types):
252             l[1] = fix_dn(l[1])
253
254         if key == 'dn':
255             skip_dn = True
256             dn = l[1]
257
258         if key == 'objectclass':
259             skip_objectclass = True
260         elif key == 'admindisplayname':
261             skip_admin_display_name = True
262         elif key == 'admindescription':
263             skip_admin_description = True
264
265     assert(cn)
266
267     header = []
268     if not skip_dn:
269         header.append(["dn", "CN=%s,${SCHEMADN}" % cn, False])
270     else:
271         header.append(["dn", dn, False])
272
273     if not skip_objectclass:
274         header.append(["objectClass", ["top", objectClass], False])
275     if not skip_admin_description:
276         header.append(["adminDescription", cn, False])
277     if not skip_admin_display_name:
278         header.append(["adminDisplayName", cn, False])
279
280     header.append(["objectGUID", str(uuid.uuid4()), False])
281
282     entry = header + [x for x in entry if x[0].lower() not in set(['dn', 'changetype', 'objectcategory'])]
283
284     return entry
285
286 def __parse_schema_file(filename, objectClass):
287     """Load and transform a schema file."""
288
289     out = []
290
291     f = open(filename, "rU")
292     for entry in __read_raw_entries(f):
293         out.append(__write_ldif_one(__transform_entry(entry, objectClass)))
294
295     return "\n\n".join(out)
296
297
298 def read_ms_schema(attr_file, classes_file, dump_attributes = True, dump_classes = True, debug = False):
299     """Read WSPP documentation-derived schema files."""
300
301     attr_ldif = ""
302     classes_ldif = ""
303
304     if dump_attributes:
305         attr_ldif =  __parse_schema_file(attr_file, "attributeSchema")
306     if dump_classes:
307         classes_ldif = __parse_schema_file(classes_file, "classSchema")
308
309     return attr_ldif + "\n\n" + classes_ldif + "\n\n"
310
311 if __name__ == '__main__':
312     import sys
313
314     try:
315         attr_file = sys.argv[1]
316         classes_file = sys.argv[2]
317     except IndexError:
318         print("Usage: %s attr-file.txt classes-file.txt" % (sys.argv[0]), file=sys.stderr)
319         sys.exit(1)
320
321     print(read_ms_schema(attr_file, classes_file))