1 | 'use strict'
|
2 |
|
3 | const requestQueueFactory = require('./request-queue')
|
4 | const messageTrackerFactory = require('./message-tracker')
|
5 | const { MAX_MSGID } = require('./constants')
|
6 |
|
7 | const EventEmitter = require('events').EventEmitter
|
8 | const net = require('net')
|
9 | const tls = require('tls')
|
10 | const util = require('util')
|
11 |
|
12 | const once = require('once')
|
13 | const backoff = require('backoff')
|
14 | const vasync = require('vasync')
|
15 | const assert = require('assert-plus')
|
16 | const VError = require('verror').VError
|
17 |
|
18 | const Attribute = require('../attribute')
|
19 | const Change = require('../change')
|
20 | const Control = require('../controls/index').Control
|
21 | const SearchPager = require('./search_pager')
|
22 | const Protocol = require('../protocol')
|
23 | const dn = require('../dn')
|
24 | const errors = require('../errors')
|
25 | const filters = require('../filters')
|
26 | const messages = require('../messages')
|
27 | const url = require('../url')
|
28 | const CorkedEmitter = require('../corked_emitter')
|
29 |
|
30 |
|
31 |
|
32 | const AbandonRequest = messages.AbandonRequest
|
33 | const AddRequest = messages.AddRequest
|
34 | const BindRequest = messages.BindRequest
|
35 | const CompareRequest = messages.CompareRequest
|
36 | const DeleteRequest = messages.DeleteRequest
|
37 | const ExtendedRequest = messages.ExtendedRequest
|
38 | const ModifyRequest = messages.ModifyRequest
|
39 | const ModifyDNRequest = messages.ModifyDNRequest
|
40 | const SearchRequest = messages.SearchRequest
|
41 | const UnbindRequest = messages.UnbindRequest
|
42 | const UnbindResponse = messages.UnbindResponse
|
43 |
|
44 | const LDAPResult = messages.LDAPResult
|
45 | const SearchEntry = messages.SearchEntry
|
46 | const SearchReference = messages.SearchReference
|
47 |
|
48 | const Parser = messages.Parser
|
49 |
|
50 | const PresenceFilter = filters.PresenceFilter
|
51 |
|
52 | const ConnectionError = errors.ConnectionError
|
53 |
|
54 | const CMP_EXPECT = [errors.LDAP_COMPARE_TRUE, errors.LDAP_COMPARE_FALSE]
|
55 |
|
56 |
|
57 | let CLIENT_ID = 0
|
58 |
|
59 |
|
60 |
|
61 | function nextClientId () {
|
62 | if (++CLIENT_ID === MAX_MSGID) { return 1 }
|
63 |
|
64 | return CLIENT_ID
|
65 | }
|
66 |
|
67 | function validateControls (controls) {
|
68 | if (Array.isArray(controls)) {
|
69 | controls.forEach(function (c) {
|
70 | if (!(c instanceof Control)) { throw new TypeError('controls must be [Control]') }
|
71 | })
|
72 | } else if (controls instanceof Control) {
|
73 | controls = [controls]
|
74 | } else {
|
75 | throw new TypeError('controls must be [Control]')
|
76 | }
|
77 |
|
78 | return controls
|
79 | }
|
80 |
|
81 | function ensureDN (input, strict) {
|
82 | if (dn.DN.isDN(input)) {
|
83 | return dn
|
84 | } else if (strict) {
|
85 | return dn.parse(input)
|
86 | } else if (typeof (input) === 'string') {
|
87 | return input
|
88 | } else {
|
89 | throw new Error('invalid DN')
|
90 | }
|
91 | }
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 | function Client (options) {
|
108 | assert.ok(options)
|
109 |
|
110 | EventEmitter.call(this, options)
|
111 |
|
112 | const self = this
|
113 | this.urls = options.url ? [].concat(options.url).map(url.parse) : []
|
114 | this._nextServer = 0
|
115 |
|
116 | this.host = undefined
|
117 | this.port = undefined
|
118 | this.secure = undefined
|
119 | this.url = undefined
|
120 | this.tlsOptions = options.tlsOptions
|
121 | this.socketPath = options.socketPath || false
|
122 |
|
123 | this.log = options.log.child({ clazz: 'Client' }, true)
|
124 |
|
125 | this.timeout = parseInt((options.timeout || 0), 10)
|
126 | this.connectTimeout = parseInt((options.connectTimeout || 0), 10)
|
127 | this.idleTimeout = parseInt((options.idleTimeout || 0), 10)
|
128 | if (options.reconnect) {
|
129 |
|
130 | const rOpts = (typeof (options.reconnect) === 'object')
|
131 | ? options.reconnect
|
132 | : {}
|
133 | this.reconnect = {
|
134 | initialDelay: parseInt(rOpts.initialDelay || 100, 10),
|
135 | maxDelay: parseInt(rOpts.maxDelay || 10000, 10),
|
136 | failAfter: parseInt(rOpts.failAfter, 10) || Infinity
|
137 | }
|
138 | }
|
139 | this.strictDN = (options.strictDN !== undefined) ? options.strictDN : true
|
140 |
|
141 | this.queue = requestQueueFactory({
|
142 | size: parseInt((options.queueSize || 0), 10),
|
143 | timeout: parseInt((options.queueTimeout || 0), 10)
|
144 | })
|
145 | if (options.queueDisable) {
|
146 | this.queue.freeze()
|
147 | }
|
148 |
|
149 |
|
150 |
|
151 |
|
152 | if (options.bindDN !== undefined &&
|
153 | options.bindCredentials !== undefined) {
|
154 | this.on('setup', function (clt, cb) {
|
155 | clt.bind(options.bindDN, options.bindCredentials, function (err) {
|
156 | if (err) {
|
157 | if (self._socket) {
|
158 | self._socket.destroy()
|
159 | }
|
160 | self.emit('error', err)
|
161 | }
|
162 | cb(err)
|
163 | })
|
164 | })
|
165 | }
|
166 |
|
167 | this._socket = null
|
168 | this.connected = false
|
169 | this.connect()
|
170 | }
|
171 | util.inherits(Client, EventEmitter)
|
172 | module.exports = Client
|
173 |
|
174 |
|
175 |
|
176 |
|
177 |
|
178 |
|
179 |
|
180 |
|
181 |
|
182 |
|
183 |
|
184 |
|
185 | Client.prototype.abandon = function abandon (messageID, controls, callback) {
|
186 | assert.number(messageID, 'messageID')
|
187 | if (typeof (controls) === 'function') {
|
188 | callback = controls
|
189 | controls = []
|
190 | } else {
|
191 | controls = validateControls(controls)
|
192 | }
|
193 | assert.func(callback, 'callback')
|
194 |
|
195 | const req = new AbandonRequest({
|
196 | abandonID: messageID,
|
197 | controls: controls
|
198 | })
|
199 |
|
200 | return this._send(req, 'abandon', null, callback)
|
201 | }
|
202 |
|
203 |
|
204 |
|
205 |
|
206 |
|
207 |
|
208 |
|
209 |
|
210 |
|
211 |
|
212 |
|
213 |
|
214 |
|
215 |
|
216 | Client.prototype.add = function add (name, entry, controls, callback) {
|
217 | assert.ok(name !== undefined, 'name')
|
218 | assert.object(entry, 'entry')
|
219 | if (typeof (controls) === 'function') {
|
220 | callback = controls
|
221 | controls = []
|
222 | } else {
|
223 | controls = validateControls(controls)
|
224 | }
|
225 | assert.func(callback, 'callback')
|
226 |
|
227 | if (Array.isArray(entry)) {
|
228 | entry.forEach(function (a) {
|
229 | if (!Attribute.isAttribute(a)) { throw new TypeError('entry must be an Array of Attributes') }
|
230 | })
|
231 | } else {
|
232 | const save = entry
|
233 |
|
234 | entry = []
|
235 | Object.keys(save).forEach(function (k) {
|
236 | const attr = new Attribute({ type: k })
|
237 | if (Array.isArray(save[k])) {
|
238 | save[k].forEach(function (v) {
|
239 | attr.addValue(v.toString())
|
240 | })
|
241 | } else {
|
242 | attr.addValue(save[k].toString())
|
243 | }
|
244 | entry.push(attr)
|
245 | })
|
246 | }
|
247 |
|
248 | const req = new AddRequest({
|
249 | entry: ensureDN(name, this.strictDN),
|
250 | attributes: entry,
|
251 | controls: controls
|
252 | })
|
253 |
|
254 | return this._send(req, [errors.LDAP_SUCCESS], null, callback)
|
255 | }
|
256 |
|
257 |
|
258 |
|
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 |
|
265 |
|
266 | Client.prototype.bind = function bind (name,
|
267 | credentials,
|
268 | controls,
|
269 | callback,
|
270 | _bypass) {
|
271 | if (typeof (name) !== 'string' && !(name instanceof dn.DN)) { throw new TypeError('name (string) required') }
|
272 | assert.optionalString(credentials, 'credentials')
|
273 | if (typeof (controls) === 'function') {
|
274 | callback = controls
|
275 | controls = []
|
276 | } else {
|
277 | controls = validateControls(controls)
|
278 | }
|
279 | assert.func(callback, 'callback')
|
280 |
|
281 | const req = new BindRequest({
|
282 | name: name || '',
|
283 | authentication: 'Simple',
|
284 | credentials: credentials || '',
|
285 | controls: controls
|
286 | })
|
287 |
|
288 |
|
289 | const self = this
|
290 | function callbackWrapper (err, ret) {
|
291 | self.removeListener('connectError', callbackWrapper)
|
292 | callback(err, ret)
|
293 | }
|
294 | this.addListener('connectError', callbackWrapper)
|
295 |
|
296 | return this._send(req, [errors.LDAP_SUCCESS], null, callbackWrapper, _bypass)
|
297 | }
|
298 |
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 | Client.prototype.compare = function compare (name,
|
310 | attr,
|
311 | value,
|
312 | controls,
|
313 | callback) {
|
314 | assert.ok(name !== undefined, 'name')
|
315 | assert.string(attr, 'attr')
|
316 | assert.string(value, 'value')
|
317 | if (typeof (controls) === 'function') {
|
318 | callback = controls
|
319 | controls = []
|
320 | } else {
|
321 | controls = validateControls(controls)
|
322 | }
|
323 | assert.func(callback, 'callback')
|
324 |
|
325 | const req = new CompareRequest({
|
326 | entry: ensureDN(name, this.strictDN),
|
327 | attribute: attr,
|
328 | value: value,
|
329 | controls: controls
|
330 | })
|
331 |
|
332 | return this._send(req, CMP_EXPECT, null, function (err, res) {
|
333 | if (err) { return callback(err) }
|
334 |
|
335 | return callback(null, (res.status === errors.LDAP_COMPARE_TRUE), res)
|
336 | })
|
337 | }
|
338 |
|
339 |
|
340 |
|
341 |
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 | Client.prototype.del = function del (name, controls, callback) {
|
348 | assert.ok(name !== undefined, 'name')
|
349 | if (typeof (controls) === 'function') {
|
350 | callback = controls
|
351 | controls = []
|
352 | } else {
|
353 | controls = validateControls(controls)
|
354 | }
|
355 | assert.func(callback, 'callback')
|
356 |
|
357 | const req = new DeleteRequest({
|
358 | entry: ensureDN(name, this.strictDN),
|
359 | controls: controls
|
360 | })
|
361 |
|
362 | return this._send(req, [errors.LDAP_SUCCESS], null, callback)
|
363 | }
|
364 |
|
365 |
|
366 |
|
367 |
|
368 |
|
369 |
|
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 |
|
378 | Client.prototype.exop = function exop (name, value, controls, callback) {
|
379 | assert.string(name, 'name')
|
380 | if (typeof (value) === 'function') {
|
381 | callback = value
|
382 | controls = []
|
383 | value = undefined
|
384 | }
|
385 | if (typeof (controls) === 'function') {
|
386 | callback = controls
|
387 | controls = []
|
388 | } else {
|
389 | controls = validateControls(controls)
|
390 | }
|
391 | assert.func(callback, 'callback')
|
392 |
|
393 | const req = new ExtendedRequest({
|
394 | requestName: name,
|
395 | requestValue: value,
|
396 | controls: controls
|
397 | })
|
398 |
|
399 | return this._send(req, [errors.LDAP_SUCCESS], null, function (err, res) {
|
400 | if (err) { return callback(err) }
|
401 |
|
402 | return callback(null, res.responseValue || '', res)
|
403 | })
|
404 | }
|
405 |
|
406 |
|
407 |
|
408 |
|
409 |
|
410 |
|
411 |
|
412 |
|
413 |
|
414 |
|
415 | Client.prototype.modify = function modify (name, change, controls, callback) {
|
416 | assert.ok(name !== undefined, 'name')
|
417 | assert.object(change, 'change')
|
418 |
|
419 | const changes = []
|
420 |
|
421 | function changeFromObject (change) {
|
422 | if (!change.operation && !change.type) { throw new Error('change.operation required') }
|
423 | if (typeof (change.modification) !== 'object') { throw new Error('change.modification (object) required') }
|
424 |
|
425 | if (Object.keys(change.modification).length === 2 &&
|
426 | typeof (change.modification.type) === 'string' &&
|
427 | Array.isArray(change.modification.vals)) {
|
428 |
|
429 | changes.push(new Change({
|
430 | operation: change.operation || change.type,
|
431 | modification: change.modification
|
432 | }))
|
433 | } else {
|
434 |
|
435 | Object.keys(change.modification).forEach(function (k) {
|
436 | const mod = {}
|
437 | mod[k] = change.modification[k]
|
438 | changes.push(new Change({
|
439 | operation: change.operation || change.type,
|
440 | modification: mod
|
441 | }))
|
442 | })
|
443 | }
|
444 | }
|
445 |
|
446 | if (Change.isChange(change)) {
|
447 | changes.push(change)
|
448 | } else if (Array.isArray(change)) {
|
449 | change.forEach(function (c) {
|
450 | if (Change.isChange(c)) {
|
451 | changes.push(c)
|
452 | } else {
|
453 | changeFromObject(c)
|
454 | }
|
455 | })
|
456 | } else {
|
457 | changeFromObject(change)
|
458 | }
|
459 |
|
460 | if (typeof (controls) === 'function') {
|
461 | callback = controls
|
462 | controls = []
|
463 | } else {
|
464 | controls = validateControls(controls)
|
465 | }
|
466 | assert.func(callback, 'callback')
|
467 |
|
468 | const req = new ModifyRequest({
|
469 | object: ensureDN(name, this.strictDN),
|
470 | changes: changes,
|
471 | controls: controls
|
472 | })
|
473 |
|
474 | return this._send(req, [errors.LDAP_SUCCESS], null, callback)
|
475 | }
|
476 |
|
477 |
|
478 |
|
479 |
|
480 |
|
481 |
|
482 |
|
483 |
|
484 |
|
485 |
|
486 |
|
487 |
|
488 |
|
489 |
|
490 |
|
491 | Client.prototype.modifyDN = function modifyDN (name,
|
492 | newName,
|
493 | controls,
|
494 | callback) {
|
495 | assert.ok(name !== undefined, 'name')
|
496 | assert.string(newName, 'newName')
|
497 | if (typeof (controls) === 'function') {
|
498 | callback = controls
|
499 | controls = []
|
500 | } else {
|
501 | controls = validateControls(controls)
|
502 | }
|
503 | assert.func(callback)
|
504 |
|
505 | const DN = ensureDN(name)
|
506 |
|
507 | const newDN = dn.parse(newName)
|
508 |
|
509 | const req = new ModifyDNRequest({
|
510 | entry: DN,
|
511 | deleteOldRdn: true,
|
512 | controls: controls
|
513 | })
|
514 |
|
515 | if (newDN.length !== 1) {
|
516 | req.newRdn = dn.parse(newDN.rdns.shift().toString())
|
517 | req.newSuperior = newDN
|
518 | } else {
|
519 | req.newRdn = newDN
|
520 | }
|
521 |
|
522 | return this._send(req, [errors.LDAP_SUCCESS], null, callback)
|
523 | }
|
524 |
|
525 |
|
526 |
|
527 |
|
528 |
|
529 |
|
530 |
|
531 |
|
532 |
|
533 |
|
534 |
|
535 |
|
536 |
|
537 |
|
538 |
|
539 |
|
540 |
|
541 |
|
542 |
|
543 |
|
544 |
|
545 |
|
546 |
|
547 |
|
548 | Client.prototype.search = function search (base,
|
549 | options,
|
550 | controls,
|
551 | callback,
|
552 | _bypass) {
|
553 | assert.ok(base !== undefined, 'search base')
|
554 | if (Array.isArray(options) || (options instanceof Control)) {
|
555 | controls = options
|
556 | options = {}
|
557 | } else if (typeof (options) === 'function') {
|
558 | callback = options
|
559 | controls = []
|
560 | options = {
|
561 | filter: new PresenceFilter({ attribute: 'objectclass' })
|
562 | }
|
563 | } else if (typeof (options) === 'string') {
|
564 | options = { filter: filters.parseString(options) }
|
565 | } else if (typeof (options) !== 'object') {
|
566 | throw new TypeError('options (object) required')
|
567 | }
|
568 | if (typeof (options.filter) === 'string') {
|
569 | options.filter = filters.parseString(options.filter)
|
570 | } else if (!options.filter) {
|
571 | options.filter = new PresenceFilter({ attribute: 'objectclass' })
|
572 | } else if (!filters.isFilter(options.filter)) {
|
573 | throw new TypeError('options.filter (Filter) required')
|
574 | }
|
575 | if (typeof (controls) === 'function') {
|
576 | callback = controls
|
577 | controls = []
|
578 | } else {
|
579 | controls = validateControls(controls)
|
580 | }
|
581 | assert.func(callback, 'callback')
|
582 |
|
583 | if (options.attributes) {
|
584 | if (!Array.isArray(options.attributes)) {
|
585 | if (typeof (options.attributes) === 'string') {
|
586 | options.attributes = [options.attributes]
|
587 | } else {
|
588 | throw new TypeError('options.attributes must be an Array of Strings')
|
589 | }
|
590 | }
|
591 | }
|
592 |
|
593 | const self = this
|
594 | const baseDN = ensureDN(base, this.strictDN)
|
595 |
|
596 | function sendRequest (ctrls, emitter, cb) {
|
597 | const req = new SearchRequest({
|
598 | baseObject: baseDN,
|
599 | scope: options.scope || 'base',
|
600 | filter: options.filter,
|
601 | derefAliases: options.derefAliases || Protocol.NEVER_DEREF_ALIASES,
|
602 | sizeLimit: options.sizeLimit || 0,
|
603 | timeLimit: options.timeLimit || 10,
|
604 | typesOnly: options.typesOnly || false,
|
605 | attributes: options.attributes || [],
|
606 | controls: ctrls
|
607 | })
|
608 |
|
609 | return self._send(req,
|
610 | [errors.LDAP_SUCCESS],
|
611 | emitter,
|
612 | cb,
|
613 | _bypass)
|
614 | }
|
615 |
|
616 | if (options.paged) {
|
617 |
|
618 | const pageOpts = typeof (options.paged) === 'object' ? options.paged : {}
|
619 | let size = 100
|
620 | if (pageOpts.pageSize > 0) {
|
621 | size = pageOpts.pageSize
|
622 | } else if (options.sizeLimit > 1) {
|
623 |
|
624 |
|
625 |
|
626 | size = options.sizeLimit - 1
|
627 | }
|
628 |
|
629 | const pager = new SearchPager({
|
630 | callback: callback,
|
631 | controls: controls,
|
632 | pageSize: size,
|
633 | pagePause: pageOpts.pagePause
|
634 | })
|
635 | pager.on('search', sendRequest)
|
636 | pager.begin()
|
637 | } else {
|
638 | sendRequest(controls, new CorkedEmitter(), callback)
|
639 | }
|
640 | }
|
641 |
|
642 |
|
643 |
|
644 |
|
645 |
|
646 |
|
647 |
|
648 |
|
649 |
|
650 |
|
651 | Client.prototype.unbind = function unbind (callback) {
|
652 | if (!callback) { callback = function () {} }
|
653 |
|
654 | if (typeof (callback) !== 'function') { throw new TypeError('callback must be a function') }
|
655 |
|
656 |
|
657 |
|
658 | this.unbound = true
|
659 |
|
660 | if (!this._socket) { return callback() }
|
661 |
|
662 | const req = new UnbindRequest()
|
663 | return this._send(req, 'unbind', null, callback)
|
664 | }
|
665 |
|
666 |
|
667 |
|
668 |
|
669 | Client.prototype.starttls = function starttls (options,
|
670 | controls,
|
671 | callback,
|
672 | _bypass) {
|
673 | assert.optionalObject(options)
|
674 | options = options || {}
|
675 | callback = once(callback)
|
676 | const self = this
|
677 |
|
678 | if (this._starttls) {
|
679 | return callback(new Error('STARTTLS already in progress or active'))
|
680 | }
|
681 |
|
682 | function onSend (err, emitter) {
|
683 | if (err) {
|
684 | callback(err)
|
685 | return
|
686 | }
|
687 | |
688 |
|
689 |
|
690 |
|
691 |
|
692 | self._starttls = {
|
693 | started: true
|
694 | }
|
695 |
|
696 | emitter.on('error', function (err) {
|
697 | self._starttls = null
|
698 | callback(err)
|
699 | })
|
700 | emitter.on('end', function (res) {
|
701 | const sock = self._socket
|
702 | |
703 |
|
704 |
|
705 |
|
706 |
|
707 | sock.removeAllListeners('data')
|
708 |
|
709 | options.socket = sock
|
710 | const secure = tls.connect(options)
|
711 | secure.once('secureConnect', function () {
|
712 | |
713 |
|
714 |
|
715 |
|
716 |
|
717 | secure.removeAllListeners('error')
|
718 | secure.on('data', function onData (data) {
|
719 | self.log.trace('data event: %s', util.inspect(data))
|
720 |
|
721 | self._tracker.parser.write(data)
|
722 | })
|
723 | secure.on('error', function (err) {
|
724 | self.log.trace({ err: err }, 'error event: %s', new Error().stack)
|
725 |
|
726 | self.emit('error', err)
|
727 | sock.destroy()
|
728 | })
|
729 | callback(null)
|
730 | })
|
731 | secure.once('error', function (err) {
|
732 |
|
733 | self._starttls = null
|
734 | secure.removeAllListeners()
|
735 | callback(err)
|
736 | })
|
737 | self._starttls.success = true
|
738 | self._socket = secure
|
739 | })
|
740 | }
|
741 |
|
742 | const req = new ExtendedRequest({
|
743 | requestName: '1.3.6.1.4.1.1466.20037',
|
744 | requestValue: null,
|
745 | controls: controls
|
746 | })
|
747 |
|
748 | return this._send(req,
|
749 | [errors.LDAP_SUCCESS],
|
750 | new EventEmitter(),
|
751 | onSend,
|
752 | _bypass)
|
753 | }
|
754 |
|
755 |
|
756 |
|
757 |
|
758 |
|
759 |
|
760 |
|
761 |
|
762 |
|
763 |
|
764 |
|
765 |
|
766 | Client.prototype.destroy = function destroy (err) {
|
767 | this.destroyed = true
|
768 | this.queue.freeze()
|
769 |
|
770 | this.queue.flush(function (msg, expect, emitter, cb) {
|
771 | if (typeof (cb) === 'function') {
|
772 | cb(new Error('client destroyed'))
|
773 | }
|
774 | })
|
775 | if (this.connected) {
|
776 | this.unbind()
|
777 | } else if (this._socket) {
|
778 | this._socket.destroy()
|
779 | }
|
780 | this.emit('destroy', err)
|
781 | }
|
782 |
|
783 |
|
784 |
|
785 |
|
786 | Client.prototype.connect = function connect () {
|
787 | if (this.connecting || this.connected) {
|
788 | return
|
789 | }
|
790 | const self = this
|
791 | const log = this.log
|
792 | let socket
|
793 | let tracker
|
794 |
|
795 |
|
796 | function connectSocket (cb) {
|
797 | const server = self.urls[self._nextServer]
|
798 | self._nextServer = (self._nextServer + 1) % self.urls.length
|
799 |
|
800 | cb = once(cb)
|
801 |
|
802 | function onResult (err, res) {
|
803 | if (err) {
|
804 | if (self.connectTimer) {
|
805 | clearTimeout(self.connectTimer)
|
806 | self.connectTimer = null
|
807 | }
|
808 | self.emit('connectError', err)
|
809 | }
|
810 | cb(err, res)
|
811 | }
|
812 | function onConnect () {
|
813 | if (self.connectTimer) {
|
814 | clearTimeout(self.connectTimer)
|
815 | self.connectTimer = null
|
816 | }
|
817 | socket.removeAllListeners('error')
|
818 | .removeAllListeners('connect')
|
819 | .removeAllListeners('secureConnect')
|
820 |
|
821 | tracker.id = nextClientId() + '__' + tracker.id
|
822 | self.log = self.log.child({ ldap_id: tracker.id }, true)
|
823 |
|
824 |
|
825 | setupClient(cb)
|
826 | }
|
827 |
|
828 | const port = (server && server.port) || self.socketPath
|
829 | const host = server && server.hostname
|
830 | if (server && server.secure) {
|
831 | socket = tls.connect(port, host, self.tlsOptions)
|
832 | socket.once('secureConnect', onConnect)
|
833 | } else {
|
834 | socket = net.connect(port, host)
|
835 | socket.once('connect', onConnect)
|
836 | }
|
837 | socket.once('error', onResult)
|
838 | initSocket(server)
|
839 |
|
840 |
|
841 | if (self.connectTimeout) {
|
842 | self.connectTimer = setTimeout(function onConnectTimeout () {
|
843 | if (!socket || !socket.readable || !socket.writeable) {
|
844 | socket.destroy()
|
845 | self._socket = null
|
846 | onResult(new ConnectionError('connection timeout'))
|
847 | }
|
848 | }, self.connectTimeout)
|
849 | }
|
850 | }
|
851 |
|
852 |
|
853 | function initSocket (url) {
|
854 | tracker = messageTrackerFactory({
|
855 | id: url ? url.href : self.socketPath,
|
856 | parser: new Parser({ log: log })
|
857 | })
|
858 |
|
859 |
|
860 | if (typeof (socket.setKeepAlive) !== 'function') {
|
861 | socket.setKeepAlive = function setKeepAlive (enable, delay) {
|
862 | return socket.socket
|
863 | ? socket.socket.setKeepAlive(enable, delay)
|
864 | : false
|
865 | }
|
866 | }
|
867 |
|
868 | socket.on('data', function onData (data) {
|
869 | log.trace('data event: %s', util.inspect(data))
|
870 |
|
871 | tracker.parser.write(data)
|
872 | })
|
873 |
|
874 |
|
875 | tracker.parser.on('message', function onMessage (message) {
|
876 | message.connection = self._socket
|
877 | const callback = tracker.fetch(message.messageID)
|
878 |
|
879 | if (!callback) {
|
880 | log.error({ message: message.json }, 'unsolicited message')
|
881 | return false
|
882 | }
|
883 |
|
884 | return callback(message)
|
885 | })
|
886 |
|
887 | tracker.parser.on('error', function onParseError (err) {
|
888 | self.emit('error', new VError(err, 'Parser error for %s',
|
889 | tracker.id))
|
890 | self.connected = false
|
891 | socket.end()
|
892 | })
|
893 | }
|
894 |
|
895 |
|
896 | function setupClient (cb) {
|
897 | cb = once(cb)
|
898 |
|
899 |
|
900 | function bail (err) {
|
901 | socket.destroy()
|
902 | cb(err || new Error('client error during setup'))
|
903 | }
|
904 |
|
905 | ((socket.socket) ? socket.socket : socket).once('close', bail)
|
906 | socket.once('error', bail)
|
907 | socket.once('end', bail)
|
908 | socket.once('timeout', bail)
|
909 | socket.once('cleanupSetupListeners', function onCleanup () {
|
910 | socket.removeListener('error', bail)
|
911 | .removeListener('close', bail)
|
912 | .removeListener('end', bail)
|
913 | .removeListener('timeout', bail)
|
914 | })
|
915 |
|
916 | self._socket = socket
|
917 | self._tracker = tracker
|
918 |
|
919 |
|
920 |
|
921 |
|
922 |
|
923 |
|
924 | const basicClient = {
|
925 | bind: function bindBypass (name, credentials, controls, callback) {
|
926 | return self.bind(name, credentials, controls, callback, true)
|
927 | },
|
928 | search: function searchBypass (base, options, controls, callback) {
|
929 | return self.search(base, options, controls, callback, true)
|
930 | },
|
931 | starttls: function starttlsBypass (options, controls, callback) {
|
932 | return self.starttls(options, controls, callback, true)
|
933 | },
|
934 | unbind: self.unbind.bind(self)
|
935 | }
|
936 | vasync.forEachPipeline({
|
937 | func: function (f, callback) {
|
938 | f(basicClient, callback)
|
939 | },
|
940 | inputs: self.listeners('setup')
|
941 | }, function (err, res) {
|
942 | if (err) {
|
943 | self.emit('setupError', err)
|
944 | }
|
945 | cb(err)
|
946 | })
|
947 | }
|
948 |
|
949 |
|
950 | function postSetup () {
|
951 |
|
952 | socket.emit('cleanupSetupListeners');
|
953 |
|
954 |
|
955 | ((socket.socket) ? socket.socket : socket).once('close',
|
956 | self._onClose.bind(self))
|
957 | socket.on('end', function onEnd () {
|
958 | log.trace('end event')
|
959 |
|
960 | self.emit('end')
|
961 | socket.end()
|
962 | })
|
963 | socket.on('error', function onSocketError (err) {
|
964 | log.trace({ err: err }, 'error event: %s', new Error().stack)
|
965 |
|
966 | self.emit('error', err)
|
967 | socket.destroy()
|
968 | })
|
969 | socket.on('timeout', function onTimeout () {
|
970 | log.trace('timeout event')
|
971 |
|
972 | self.emit('socketTimeout')
|
973 | socket.end()
|
974 | })
|
975 |
|
976 | const server = self.urls[self._nextServer]
|
977 | if (server) {
|
978 | self.host = server.hostname
|
979 | self.port = server.port
|
980 | self.secure = server.secure
|
981 | }
|
982 | }
|
983 |
|
984 | let retry
|
985 | let failAfter
|
986 | if (this.reconnect) {
|
987 | retry = backoff.exponential({
|
988 | initialDelay: this.reconnect.initialDelay,
|
989 | maxDelay: this.reconnect.maxDelay
|
990 | })
|
991 | failAfter = this.reconnect.failAfter
|
992 | if (this.urls.length > 1 && failAfter) {
|
993 | failAfter *= this.urls.length
|
994 | }
|
995 | } else {
|
996 | retry = backoff.exponential({
|
997 | initialDelay: 1,
|
998 | maxDelay: 2
|
999 | })
|
1000 | failAfter = this.urls.length || 1
|
1001 | }
|
1002 | retry.failAfter(failAfter)
|
1003 |
|
1004 | retry.on('ready', function (num, delay) {
|
1005 | if (self.destroyed) {
|
1006 |
|
1007 | return
|
1008 | }
|
1009 | connectSocket(function (err) {
|
1010 | if (!err) {
|
1011 | postSetup()
|
1012 | self.connecting = false
|
1013 | self.connected = true
|
1014 | self.emit('connect', socket)
|
1015 | self.log.debug('connected after %d attempt(s)', num + 1)
|
1016 |
|
1017 | self._flushQueue()
|
1018 | self._connectRetry = null
|
1019 | } else {
|
1020 | retry.backoff(err)
|
1021 | }
|
1022 | })
|
1023 | })
|
1024 | retry.on('fail', function (err) {
|
1025 | if (self.destroyed) {
|
1026 |
|
1027 | return
|
1028 | }
|
1029 | self.log.debug('failed to connect after %d attempts', failAfter)
|
1030 |
|
1031 | if (err instanceof ConnectionError) {
|
1032 | self.emit('connectTimeout', err)
|
1033 | } else if (err.code === 'ECONNREFUSED') {
|
1034 | self.emit('connectRefused', err)
|
1035 | } else {
|
1036 | self.emit('error', err)
|
1037 | }
|
1038 | })
|
1039 |
|
1040 | this._connectRetry = retry
|
1041 | this.connecting = true
|
1042 | retry.backoff()
|
1043 | }
|
1044 |
|
1045 |
|
1046 |
|
1047 |
|
1048 |
|
1049 |
|
1050 | Client.prototype._flushQueue = function _flushQueue () {
|
1051 |
|
1052 | this.queue.flush(this._send.bind(this))
|
1053 | }
|
1054 |
|
1055 |
|
1056 |
|
1057 |
|
1058 | Client.prototype._onClose = function _onClose (closeError) {
|
1059 | const socket = this._socket
|
1060 | const tracker = this._tracker
|
1061 | socket.removeAllListeners('connect')
|
1062 | .removeAllListeners('data')
|
1063 | .removeAllListeners('drain')
|
1064 | .removeAllListeners('end')
|
1065 | .removeAllListeners('error')
|
1066 | .removeAllListeners('timeout')
|
1067 | this._socket = null
|
1068 | this.connected = false;
|
1069 |
|
1070 | ((socket.socket) ? socket.socket : socket).removeAllListeners('close')
|
1071 |
|
1072 | this.log.trace('close event had_err=%s', closeError ? 'yes' : 'no')
|
1073 |
|
1074 | this.emit('close', closeError)
|
1075 |
|
1076 |
|
1077 | tracker.purge(function (msgid, cb) {
|
1078 | if (socket.unbindMessageID !== msgid) {
|
1079 | return cb(new ConnectionError(tracker.id + ' closed'))
|
1080 | } else {
|
1081 |
|
1082 | const unbind = new UnbindResponse({ messageID: msgid })
|
1083 | unbind.status = 'unbind'
|
1084 | return cb(unbind)
|
1085 | }
|
1086 | })
|
1087 |
|
1088 |
|
1089 | this._tracker = null
|
1090 | delete this._starttls
|
1091 |
|
1092 |
|
1093 |
|
1094 | if (this.reconnect && !this.unbound) {
|
1095 | this.connect()
|
1096 | }
|
1097 | this.unbound = false
|
1098 | return false
|
1099 | }
|
1100 |
|
1101 |
|
1102 |
|
1103 |
|
1104 |
|
1105 |
|
1106 |
|
1107 |
|
1108 |
|
1109 | Client.prototype._updateIdle = function _updateIdle (override) {
|
1110 | if (this.idleTimeout === 0) {
|
1111 | return
|
1112 | }
|
1113 |
|
1114 | const self = this
|
1115 | function isIdle (disable) {
|
1116 | return ((disable !== true) &&
|
1117 | (self._socket && self.connected) &&
|
1118 | (self._tracker.pending === 0))
|
1119 | }
|
1120 | if (isIdle(override)) {
|
1121 | if (!this._idleTimer) {
|
1122 | this._idleTimer = setTimeout(function () {
|
1123 |
|
1124 | if (isIdle()) {
|
1125 | self.emit('idle')
|
1126 | }
|
1127 | }, this.idleTimeout)
|
1128 | }
|
1129 | } else {
|
1130 | if (this._idleTimer) {
|
1131 | clearTimeout(this._idleTimer)
|
1132 | this._idleTimer = null
|
1133 | }
|
1134 | }
|
1135 | }
|
1136 |
|
1137 |
|
1138 |
|
1139 |
|
1140 | Client.prototype._send = function _send (message,
|
1141 | expect,
|
1142 | emitter,
|
1143 | callback,
|
1144 | _bypass) {
|
1145 | assert.ok(message)
|
1146 | assert.ok(expect)
|
1147 | assert.optionalObject(emitter)
|
1148 | assert.ok(callback)
|
1149 |
|
1150 |
|
1151 | if (_bypass && this._socket && this._socket.writable) {
|
1152 | return this._sendSocket(message, expect, emitter, callback)
|
1153 | }
|
1154 | if (!this._socket || !this.connected) {
|
1155 | if (!this.queue.enqueue(message, expect, emitter, callback)) {
|
1156 | callback(new ConnectionError('connection unavailable'))
|
1157 | }
|
1158 |
|
1159 | if (this.reconnect) {
|
1160 | this.connect()
|
1161 | }
|
1162 | return false
|
1163 | } else {
|
1164 | this._flushQueue()
|
1165 | return this._sendSocket(message, expect, emitter, callback)
|
1166 | }
|
1167 | }
|
1168 |
|
1169 | Client.prototype._sendSocket = function _sendSocket (message,
|
1170 | expect,
|
1171 | emitter,
|
1172 | callback) {
|
1173 | const conn = this._socket
|
1174 | const tracker = this._tracker
|
1175 | const log = this.log
|
1176 | const self = this
|
1177 | let timer = false
|
1178 | let sentEmitter = false
|
1179 |
|
1180 | function sendResult (event, obj) {
|
1181 | if (event === 'error') {
|
1182 | self.emit('resultError', obj)
|
1183 | }
|
1184 | if (emitter) {
|
1185 | if (event === 'error') {
|
1186 |
|
1187 |
|
1188 | if (!sentEmitter) { return callback(obj) }
|
1189 | }
|
1190 | return emitter.emit(event, obj)
|
1191 | }
|
1192 |
|
1193 | if (event === 'error') { return callback(obj) }
|
1194 |
|
1195 | return callback(null, obj)
|
1196 | }
|
1197 |
|
1198 | function messageCallback (msg) {
|
1199 | if (timer) { clearTimeout(timer) }
|
1200 |
|
1201 | log.trace({ msg: msg ? msg.json : null }, 'response received')
|
1202 |
|
1203 | if (expect === 'abandon') { return sendResult('end', null) }
|
1204 |
|
1205 | if (msg instanceof SearchEntry || msg instanceof SearchReference) {
|
1206 | let event = msg.constructor.name
|
1207 | event = event[0].toLowerCase() + event.slice(1)
|
1208 | return sendResult(event, msg)
|
1209 | } else {
|
1210 | tracker.remove(message.messageID)
|
1211 |
|
1212 | self._updateIdle()
|
1213 |
|
1214 | if (msg instanceof LDAPResult) {
|
1215 | if (expect.indexOf(msg.status) === -1) {
|
1216 | return sendResult('error', errors.getError(msg))
|
1217 | }
|
1218 | return sendResult('end', msg)
|
1219 | } else if (msg instanceof Error) {
|
1220 | return sendResult('error', msg)
|
1221 | } else {
|
1222 | return sendResult('error', new errors.ProtocolError(msg.type))
|
1223 | }
|
1224 | }
|
1225 | }
|
1226 |
|
1227 | function onRequestTimeout () {
|
1228 | self.emit('timeout', message)
|
1229 | const cb = tracker.fetch(message.messageID)
|
1230 | if (cb) {
|
1231 |
|
1232 | cb(new errors.TimeoutError('request timeout (client interrupt)'))
|
1233 | }
|
1234 | }
|
1235 |
|
1236 | function writeCallback () {
|
1237 | if (expect === 'abandon') {
|
1238 |
|
1239 | tracker.abandon(message.abandonID)
|
1240 |
|
1241 | tracker.remove(message.id)
|
1242 | return callback(null)
|
1243 | } else if (expect === 'unbind') {
|
1244 | conn.unbindMessageID = message.id
|
1245 |
|
1246 | self.connected = false
|
1247 |
|
1248 |
|
1249 | conn.removeAllListeners('error')
|
1250 | conn.on('error', function () {})
|
1251 | conn.end()
|
1252 | } else if (emitter) {
|
1253 | sentEmitter = true
|
1254 | return callback(null, emitter)
|
1255 | }
|
1256 | return false
|
1257 | }
|
1258 |
|
1259 |
|
1260 | tracker.track(message, messageCallback)
|
1261 |
|
1262 | this._updateIdle(true)
|
1263 |
|
1264 | if (self.timeout) {
|
1265 | log.trace('Setting timeout to %d', self.timeout)
|
1266 | timer = setTimeout(onRequestTimeout, self.timeout)
|
1267 | }
|
1268 |
|
1269 | log.trace('sending request %j', message.json)
|
1270 |
|
1271 | try {
|
1272 | return conn.write(message.toBer(), writeCallback)
|
1273 | } catch (e) {
|
1274 | if (timer) { clearTimeout(timer) }
|
1275 |
|
1276 | log.trace({ err: e }, 'Error writing message to socket')
|
1277 | return callback(e)
|
1278 | }
|
1279 | }
|