Skip to content
This repository was archived by the owner on May 14, 2024. It is now read-only.

Commit f690493

Browse files
authored
Merge pull request #574 from TPXP/fix-bind-crash
Handle connection refused and connection timeouts gracefully
2 parents 68301be + 2901e48 commit f690493

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

lib/client/client.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,15 @@ Client.prototype.bind = function bind (name,
282282
controls: controls
283283
})
284284

285-
return this._send(req, [errors.LDAP_SUCCESS], null, callback, _bypass)
285+
// Connection errors will be reported to the bind callback too (useful when the LDAP server is not available)
286+
var self = this
287+
function callbackWrapper (err, ret) {
288+
self.removeListener('connectError', callbackWrapper)
289+
callback(err, ret)
290+
}
291+
this.addListener('connectError', callbackWrapper)
292+
293+
return this._send(req, [errors.LDAP_SUCCESS], null, callbackWrapper, _bypass)
286294
}
287295

288296
/**
@@ -1004,6 +1012,8 @@ Client.prototype.connect = function connect () {
10041012
// Communicate the last-encountered error
10051013
if (err instanceof ConnectionError) {
10061014
self.emit('connectTimeout', err)
1015+
} else if (err.code === 'ECONNREFUSED') {
1016+
self.emit('connectRefused', err)
10071017
} else {
10081018
self.emit('error', err)
10091019
}

test/client.test.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1474,3 +1474,42 @@ tap.test('resultError handling', function (t) {
14741474
t.fail('should not get error')
14751475
}
14761476
})
1477+
1478+
tap.test('connection refused', function (t) {
1479+
const client = ldap.createClient({
1480+
url: 'ldap://0.0.0.0'
1481+
})
1482+
1483+
client.bind('cn=root', 'secret', function (err, res) {
1484+
t.true(err)
1485+
t.type(err, Error)
1486+
t.equals(err.code, 'ECONNREFUSED')
1487+
t.false(res)
1488+
t.end()
1489+
})
1490+
})
1491+
1492+
tap.test('connection timeout', function (t) {
1493+
const client = ldap.createClient({
1494+
url: 'ldap://example.org',
1495+
connectTimeout: 1,
1496+
timeout: 1
1497+
})
1498+
1499+
var done = false
1500+
1501+
setTimeout(function () {
1502+
if (!done) {
1503+
throw new Error('LDAPJS waited for the server for too long')
1504+
}
1505+
}, 2000)
1506+
1507+
client.bind('cn=root', 'secret', function (err, res) {
1508+
t.true(err)
1509+
t.type(err, Error)
1510+
t.equals(err.message, 'connection timeout')
1511+
done = true
1512+
t.false(res)
1513+
t.end()
1514+
})
1515+
})

0 commit comments

Comments
 (0)