1 |
|
2 |
|
3 | const assert = require('assert-plus')
|
4 | const util = require('util')
|
5 |
|
6 | const asn1 = require('asn1')
|
7 |
|
8 | const logger = require('../logger')
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | const BerWriter = asn1.BerWriter
|
17 | const getControl = require('../controls').getControl
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | function LDAPMessage (options) {
|
27 | assert.object(options)
|
28 |
|
29 | this.messageID = options.messageID || 0
|
30 | this.protocolOp = options.protocolOp || undefined
|
31 | this.controls = options.controls ? options.controls.slice(0) : []
|
32 |
|
33 | this.log = options.log || logger
|
34 | }
|
35 | Object.defineProperties(LDAPMessage.prototype, {
|
36 | id: {
|
37 | get: function getId () { return this.messageID },
|
38 | configurable: false
|
39 | },
|
40 | dn: {
|
41 | get: function getDN () { return this._dn || '' },
|
42 | configurable: false
|
43 | },
|
44 | type: {
|
45 | get: function getType () { return 'LDAPMessage' },
|
46 | configurable: false
|
47 | },
|
48 | json: {
|
49 | get: function () {
|
50 | const out = this._json({
|
51 | messageID: this.messageID,
|
52 | protocolOp: this.type
|
53 | })
|
54 | out.controls = this.controls
|
55 | return out
|
56 | },
|
57 | configurable: false
|
58 | }
|
59 | })
|
60 |
|
61 | LDAPMessage.prototype.toString = function () {
|
62 | return JSON.stringify(this.json)
|
63 | }
|
64 |
|
65 | LDAPMessage.prototype.parse = function (ber) {
|
66 | assert.ok(ber)
|
67 |
|
68 | this.log.trace('parse: data=%s', util.inspect(ber.buffer))
|
69 |
|
70 |
|
71 | this._parse(ber, ber.length)
|
72 |
|
73 |
|
74 | if (ber.peek() === 0xa0) {
|
75 | ber.readSequence()
|
76 | const end = ber.offset + ber.length
|
77 | while (ber.offset < end) {
|
78 | const c = getControl(ber)
|
79 | if (c) { this.controls.push(c) }
|
80 | }
|
81 | }
|
82 |
|
83 | this.log.trace('Parsing done: %j', this.json)
|
84 | return true
|
85 | }
|
86 |
|
87 | LDAPMessage.prototype.toBer = function () {
|
88 | let writer = new BerWriter()
|
89 | writer.startSequence()
|
90 | writer.writeInt(this.messageID)
|
91 |
|
92 | writer.startSequence(this.protocolOp)
|
93 | if (this._toBer) { writer = this._toBer(writer) }
|
94 | writer.endSequence()
|
95 |
|
96 | if (this.controls && this.controls.length) {
|
97 | writer.startSequence(0xa0)
|
98 | this.controls.forEach(function (c) {
|
99 | c.toBer(writer)
|
100 | })
|
101 | writer.endSequence()
|
102 | }
|
103 |
|
104 | writer.endSequence()
|
105 | return writer.buffer
|
106 | }
|
107 |
|
108 |
|
109 |
|
110 | module.exports = LDAPMessage
|