-
Notifications
You must be signed in to change notification settings - Fork 3
/
ldif.go
345 lines (321 loc) · 8.55 KB
/
ldif.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// +build ignore
package ldap
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"io"
"log"
"regexp"
"strings"
)
const (
AddRecord = 0
ModifyRecord = 1
ModDnRecord = 2
ModRdnRecord = 3
DeleteRecord = 4
EntryRecord = 255
)
var LDIFDebug bool = false
var attrValueSep []byte = []byte{':'}
var versionRegex *regexp.Regexp
var charsetRegex *regexp.Regexp
var stdBase64 *base64.Encoding
func init() {
versionRegex = regexp.MustCompile(`^version:\s+(\d+)`)
charsetRegex = regexp.MustCompile(`^charset:\s+([^ ]+)`)
stdBase64 = base64.StdEncoding
}
type LDIFRecord interface {
RecordType() uint8
}
type LDIFReader struct {
Version string
Charset string
Reader *bufio.Reader
NoMoreEntries bool
EntryCount uint64
LineCount uint64
}
func NewLDIFReader(reader io.Reader) (*LDIFReader, error) {
lr := &LDIFReader{Reader: bufio.NewReader(reader)}
return lr, nil
}
func (lr *LDIFReader) ReadLDIFEntry() (LDIFRecord, error) {
if lr.NoMoreEntries {
return nil, nil
}
ldiflines, err := lr.readLDIFEntryIntoSlice()
if err != nil {
return nil, err
}
if ldiflines == nil {
return nil, nil
}
if bytes.EqualFold(ldiflines[0][0:7], []byte("version")) {
lr.Version = string(versionRegex.Find(ldiflines[0]))
return lr.ReadLDIFEntry()
}
if bytes.EqualFold(ldiflines[0][0:7], []byte("charset")) {
lr.Charset = string(charsetRegex.Find(ldiflines[0]))
return lr.ReadLDIFEntry()
}
return sliceToLDIFRecord(ldiflines)
}
func sliceToLDIFRecord(lines [][]byte) (LDIFRecord, error) {
var dn string
var dataLineStart int // better name, after dn/controls/changetype
controls := make([]Control, 0)
recordtype := EntryRecord
LINES:
for i, line := range lines {
attrName, value, _, err := findAttrAndValue(line)
if err != nil {
return nil, err
}
switch {
case i == 0 && bytes.EqualFold(attrName, []byte("dn")):
dn = string(value)
continue LINES
case i == 0 && !bytes.EqualFold(attrName, []byte("dn")):
return nil, newError(ErrorLDIFRead, "'dn:' not at the start of line in LDIF record")
case bytes.EqualFold(attrName, []byte("changetype")):
switch strings.ToLower(string(value)) {
// check the record type, if one.
case "add":
recordtype = AddRecord
case "modify":
recordtype = ModifyRecord
case "moddn":
recordtype = ModDnRecord
case "modrdn":
recordtype = ModRdnRecord
case "delete":
recordtype = DeleteRecord
}
continue LINES
case bytes.EqualFold(attrName, []byte("control")):
//TODO handle controls
continue LINES
}
dataLineStart = i
break
}
// TODO - add the missing record types
unsupportedError := newError(ErrorLDIFRead, "Unsupported LDIF record type")
switch recordtype {
case AddRecord:
addEntry, err := ldifLinesToEntryRecord(dn, lines[dataLineStart:])
if err != nil {
return nil, err
}
addRequest := AddRequest{Entry: addEntry, Controls: controls}
if LDIFDebug {
log.Printf("dn: %s, changetype: %d, datastart: %d\n", dn, AddRecord, dataLineStart)
}
return &addRequest, nil
case ModifyRecord:
if LDIFDebug {
log.Printf("dn: %s, changetype: %d, datastart: %d\n", dn, ModifyRecord, dataLineStart)
}
modRequest, err := ldifLinesToModifyRecord(dn, lines[dataLineStart:])
if err != nil {
return nil, err
}
modRequest.Controls = controls
return modRequest, nil
case ModDnRecord:
if LDIFDebug {
log.Printf("dn: %s, changetype: %d, datastart: %d\n", dn, ModDnRecord, dataLineStart)
}
return nil, unsupportedError
case ModRdnRecord:
if LDIFDebug {
log.Printf("dn: %s, changetype: %d, datastart: %d\n", dn, ModRdnRecord, dataLineStart)
}
return nil, unsupportedError
case DeleteRecord:
if LDIFDebug {
log.Printf("dn: %s, changetype: %d, datastart: %d\n", dn, DeleteRecord, dataLineStart)
}
deleteRequest := NewDeleteRequest(dn)
for _, control := range controls {
deleteRequest.AddControl(control)
}
return deleteRequest, nil
case EntryRecord:
if LDIFDebug {
log.Printf("dn: %s, changetype: %d, datastart: %d\n", dn, EntryRecord, dataLineStart)
}
return ldifLinesToEntryRecord(dn, lines[dataLineStart:])
}
return nil, newError(ErrorLDIFRead, "Unkown LDIF record type")
}
func ldifLinesToModifyRecord(dn string, lines [][]byte) (*ModifyRequest, error) {
modReq := NewModifyRequest(dn)
var currentModType uint8
var currentAttrName string
var newMod *Mod
isNewMod := true
for _, line := range lines {
bAttr, bValue, sep, err := findAttrAndValue(line)
if err != nil {
return nil, err
}
if sep {
if newMod == nil {
return nil, newError(ErrorLDIFRead, "Misplaced '-'?")
}
modReq.AddMod(newMod)
isNewMod = true
continue
}
attrOrOpLower := strings.ToLower(string(bAttr))
if isNewMod { // current line should be "operation: attr"
switch {
case attrOrOpLower == "add":
currentModType = ModAdd
case attrOrOpLower == "delete":
currentModType = ModDelete
case attrOrOpLower == "replace":
currentModType = ModReplace
case attrOrOpLower == "increment":
currentModType = ModIncrement
case true:
return nil, newError(ErrorLDIFRead, "Expecting Modtype, not found.")
}
currentAttrName = string(bValue)
isNewMod = false
newMod = NewMod(currentModType, currentAttrName, nil)
} else {
attrName := string(bAttr)
if currentAttrName != attrName {
return nil, newError(ErrorLDIFRead,
fmt.Sprintf("AttrName mismatch %s != %s", currentAttrName, attrName))
}
attrValue := string(bValue)
// could check for empty values but some servers accept them
newMod.Modification.Values = append(newMod.Modification.Values, attrValue)
}
}
if isNewMod == false {
modReq.AddMod(newMod)
}
return modReq, nil
}
func ldifLinesToEntryRecord(dn string, lines [][]byte) (*Entry, error) {
entry := NewEntry(dn)
for _, line := range lines {
bAttr, bValue, separator, err := findAttrAndValue(line)
if err != nil {
return nil, err
}
if separator {
continue // -
}
attributeName := string(bAttr)
entry.AddAttributeValue(attributeName, string(bValue))
//log.Printf("processed: %s: %s\n", attr, string(bValue))
}
//fmt.Println(entry)
return entry, nil
}
func findAttrAndValue(line []byte) (attr []byte, value []byte, separator bool, err error) {
var valueStart int
colonLoc := bytes.Index(line, attrValueSep)
base64 := false
if line[0] == '-' {
separator = true
return
}
// find the location of first ':'
if colonLoc == -1 {
return nil, nil, false, newError(ErrorLDIFRead, ": not found in LDIF attr line.")
} else if line[colonLoc+1] == ':' { // base64 attr
valueStart = colonLoc + 2
if line[colonLoc+2] == ' ' {
valueStart = colonLoc + 3
}
base64 = true
} else { // normal
valueStart = colonLoc + 1
if line[colonLoc+1] == ' ' { // accomidate attr:value
valueStart = colonLoc + 2
}
}
attr = line[:colonLoc]
if base64 {
value, err = decodeBase64(line[valueStart:])
if err != nil {
return nil, nil, false, newError(ErrorLDIFRead, "Error decoding base64 value")
}
} else {
value = line[valueStart:]
}
if LDIFDebug {
log.Printf("findAttrAndValue: attr: [%s]", attr)
log.Printf("findAttrAndValue:value: [%s]", string(value))
}
return
}
func (lr *LDIFReader) readLDIFEntryIntoSlice() ([][]byte, error) {
entry := make([][]byte, 0, 10)
linecount := -1
ENTRY:
for {
line, err := lr.Reader.ReadBytes('\n')
// fmt.Printf("len=%d, err=%v, %s", len(line), err, line)
if err != nil {
if err == io.EOF {
lr.NoMoreEntries = true
if len(entry) == 0 {
return nil, nil
}
break
}
return nil, err
}
lr.LineCount++
if line[0] == '\n' || (line[0] == '\r' && line[1] == '\n') {
if len(entry) == 0 {
continue ENTRY
}
break
}
if line[0] == '#' { // comments
continue ENTRY
}
if line[0] == ' ' || line[0] == '\t' { // continuation
if line[len(line)-2] == '\r' {
entry[linecount] = append(entry[linecount], line[1:len(line)-2]...) // strip two bytes
} else {
entry[linecount] = append(entry[linecount], line[1:len(line)-1]...)
}
continue ENTRY
}
linecount++
if line[len(line)-2] == '\r' {
entry = append(entry, line[:len(line)-2]) // strip two bytes
} else {
entry = append(entry, line[:len(line)-1])
}
if err != nil {
break ENTRY
}
}
//for i, line := range entry {
// fmt.Println(i)
// fmt.Println(hex.Dump(line))
//}
return entry, nil
}
func decodeBase64(encodedBytes []byte) ([]byte, error) {
decodedValue := make([]byte, stdBase64.DecodedLen(len(encodedBytes)))
count, err := stdBase64.Decode(decodedValue, encodedBytes)
if err != nil || count == 0 {
return nil, newError(ErrorLDIFRead, "Error decoding base64 value")
}
return decodedValue[:count], nil
}