UNPKG

2.45 kBJavaScriptView Raw
1// Copyright 2011 Mark Cavage, Inc. All rights reserved.
2
3const assert = require('assert-plus')
4const util = require('util')
5
6const asn1 = require('asn1')
7
8const logger = require('../logger')
9// var Control = require('../controls').Control
10// var Protocol = require('../protocol')
11
12/// --- Globals
13
14// var Ber = asn1.Ber
15// var BerReader = asn1.BerReader
16const BerWriter = asn1.BerWriter
17const getControl = require('../controls').getControl
18
19/// --- API
20
21/**
22 * LDAPMessage structure.
23 *
24 * @param {Object} options stuff.
25 */
26function 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}
35Object.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
61LDAPMessage.prototype.toString = function () {
62 return JSON.stringify(this.json)
63}
64
65LDAPMessage.prototype.parse = function (ber) {
66 assert.ok(ber)
67
68 this.log.trace('parse: data=%s', util.inspect(ber.buffer))
69
70 // Delegate off to the specific type to parse
71 this._parse(ber, ber.length)
72
73 // Look for controls
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
87LDAPMessage.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/// --- Exports
109
110module.exports = LDAPMessage