Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.js 42KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  1. // Copyright 2011 Mark Cavage, Inc. All rights reserved.
  2. var EventEmitter = require('events').EventEmitter;
  3. var net = require('net');
  4. var tls = require('tls');
  5. var util = require('util');
  6. var once = require('once');
  7. var backoff = require('backoff');
  8. var vasync = require('vasync');
  9. var assert = require('assert-plus');
  10. var VError = require('verror').VError;
  11. var Attribute = require('../attribute');
  12. var Change = require('../change');
  13. var Control = require('../controls/index').Control;
  14. var SearchPager = require('./search_pager');
  15. var Protocol = require('../protocol');
  16. var dn = require('../dn');
  17. var errors = require('../errors');
  18. var filters = require('../filters');
  19. var messages = require('../messages');
  20. var url = require('../url');
  21. ///--- Globals
  22. var AbandonRequest = messages.AbandonRequest;
  23. var AddRequest = messages.AddRequest;
  24. var BindRequest = messages.BindRequest;
  25. var CompareRequest = messages.CompareRequest;
  26. var DeleteRequest = messages.DeleteRequest;
  27. var ExtendedRequest = messages.ExtendedRequest;
  28. var ModifyRequest = messages.ModifyRequest;
  29. var ModifyDNRequest = messages.ModifyDNRequest;
  30. var SearchRequest = messages.SearchRequest;
  31. var UnbindRequest = messages.UnbindRequest;
  32. var UnbindResponse = messages.UnbindResponse;
  33. var LDAPResult = messages.LDAPResult;
  34. var SearchEntry = messages.SearchEntry;
  35. var SearchReference = messages.SearchReference;
  36. var SearchResponse = messages.SearchResponse;
  37. var Parser = messages.Parser;
  38. var PresenceFilter = filters.PresenceFilter;
  39. var ConnectionError = errors.ConnectionError;
  40. var CMP_EXPECT = [errors.LDAP_COMPARE_TRUE, errors.LDAP_COMPARE_FALSE];
  41. var MAX_MSGID = Math.pow(2, 31) - 1;
  42. // node 0.6 got rid of FDs, so make up a client id for logging
  43. var CLIENT_ID = 0;
  44. ///--- Internal Helpers
  45. function nextClientId() {
  46. if (++CLIENT_ID === MAX_MSGID)
  47. return 1;
  48. return CLIENT_ID;
  49. }
  50. function validateControls(controls) {
  51. if (Array.isArray(controls)) {
  52. controls.forEach(function (c) {
  53. if (!(c instanceof Control))
  54. throw new TypeError('controls must be [Control]');
  55. });
  56. } else if (controls instanceof Control) {
  57. controls = [controls];
  58. } else {
  59. throw new TypeError('controls must be [Control]');
  60. }
  61. return controls;
  62. }
  63. function ensureDN(input, strict) {
  64. if (dn.DN.isDN(input)) {
  65. return dn;
  66. } else if (strict) {
  67. return dn.parse(input);
  68. } else if (typeof (input) === 'string') {
  69. return input;
  70. } else {
  71. throw new Error('invalid DN');
  72. }
  73. }
  74. /**
  75. * Queue to contain LDAP requests.
  76. *
  77. * @param {Object} opts queue options
  78. *
  79. * Accepted Options:
  80. * - size: Maximum queue size
  81. * - timeout: Set timeout between first queue insertion and queue flush.
  82. */
  83. function RequestQueue(opts) {
  84. if (!opts || typeof (opts) !== 'object') {
  85. opts = {};
  86. }
  87. this.size = (opts.size > 0) ? opts.size : Infinity;
  88. this.timeout = (opts.timeout > 0) ? opts.timeout : 0;
  89. this._queue = [];
  90. this._timer = null;
  91. this._frozen = false;
  92. }
  93. /**
  94. * Insert request into queue.
  95. *
  96. */
  97. RequestQueue.prototype.enqueue = function enqueue(msg, expect, emitter, cb) {
  98. if (this._queue.length >= this.size || this._frozen) {
  99. return false;
  100. }
  101. var self = this;
  102. this._queue.push([msg, expect, emitter, cb]);
  103. if (this.timeout > 0) {
  104. if (this._timer !== null) {
  105. this._timer = setTimeout(function () {
  106. // If queue times out, don't allow new entries until thawed
  107. self.freeze();
  108. self.purge();
  109. }, this.timeout);
  110. }
  111. }
  112. return true;
  113. };
  114. /**
  115. * Process all queued requests with callback.
  116. */
  117. RequestQueue.prototype.flush = function flush(cb) {
  118. if (this._timer) {
  119. clearTimeout(this._timer);
  120. this._timer = null;
  121. }
  122. var items = this._queue;
  123. this._queue = [];
  124. items.forEach(function (req) {
  125. cb(req[0], req[1], req[2], req[3]);
  126. });
  127. };
  128. /**
  129. * Purge all queued requests with an error.
  130. */
  131. RequestQueue.prototype.purge = function purge() {
  132. this.flush(function (msg, expect, emitter, cb) {
  133. cb(new errors.TimeoutError('request queue timeout'));
  134. });
  135. };
  136. /**
  137. * Freeze queue, refusing any new entries.
  138. */
  139. RequestQueue.prototype.freeze = function freeze() {
  140. this._frozen = true;
  141. };
  142. /**
  143. * Thaw queue, allowing new entries again.
  144. */
  145. RequestQueue.prototype.thaw = function thaw() {
  146. this._frozen = false;
  147. };
  148. /**
  149. * Track message callback by messageID.
  150. */
  151. function MessageTracker(opts) {
  152. assert.object(opts);
  153. assert.string(opts.id);
  154. assert.object(opts.parser);
  155. this.id = opts.id;
  156. this._msgid = 0;
  157. this._messages = {};
  158. this._abandoned = {};
  159. this.parser = opts.parser;
  160. var self = this;
  161. this.__defineGetter__('pending', function () {
  162. return Object.keys(self._messages);
  163. });
  164. }
  165. /**
  166. * Record a messageID and callback.
  167. */
  168. MessageTracker.prototype.track = function track(message, callback) {
  169. var msgid = this._nextID();
  170. message.messageID = msgid;
  171. this._messages[msgid] = callback;
  172. return msgid;
  173. };
  174. /**
  175. * Fetch callback based on messageID.
  176. */
  177. MessageTracker.prototype.fetch = function fetch(msgid) {
  178. var msg = this._messages[msgid];
  179. if (msg) {
  180. this._purgeAbandoned(msgid);
  181. return msg;
  182. }
  183. // It's possible that the server has not received the abandon request yet.
  184. // While waiting for evidence that the abandon has been received, incoming
  185. // messages that match the abandoned msgid will be handled as normal.
  186. msg = this._abandoned[msgid];
  187. if (msg) {
  188. return msg.cb;
  189. }
  190. return null;
  191. };
  192. /**
  193. * Cease tracking for a given messageID.
  194. */
  195. MessageTracker.prototype.remove = function remove(msgid) {
  196. if (this._messages[msgid]) {
  197. delete this._messages[msgid];
  198. } else if (this._abandoned[msgid]) {
  199. delete this._abandoned[msgid];
  200. }
  201. };
  202. /**
  203. * Mark a messageID as abandoned.
  204. */
  205. MessageTracker.prototype.abandon = function abandonMsg(msgid) {
  206. if (this._messages[msgid]) {
  207. // Keep track of "when" the message was abandoned
  208. this._abandoned[msgid] = {
  209. age: this._msgid,
  210. cb: this._messages[msgid]
  211. };
  212. delete this._messages[msgid];
  213. }
  214. };
  215. /**
  216. * Purge old items from abandoned list.
  217. */
  218. MessageTracker.prototype._purgeAbandoned = function _purgeAbandoned(msgid) {
  219. var self = this;
  220. // Is (comp >= ref) according to sliding window
  221. function geWindow(ref, comp) {
  222. var max = ref + (MAX_MSGID/2);
  223. var min = ref;
  224. if (max >= MAX_MSGID) {
  225. // Handle roll-over
  226. max = max - MAX_MSGID - 1;
  227. return ((comp <= max) || (comp >= min));
  228. } else {
  229. return ((comp <= max) && (comp >= min));
  230. }
  231. }
  232. Object.keys(this._abandoned).forEach(function (id) {
  233. // Abandoned messageIDs can be forgotten if a received messageID is "newer"
  234. if (geWindow(self._abandoned[id].age, msgid)) {
  235. self._abandoned[id].cb(new errors.AbandonedError(
  236. 'client request abandoned'));
  237. delete self._abandoned[id];
  238. }
  239. });
  240. };
  241. /**
  242. * Allocate the next messageID according to a sliding window.
  243. */
  244. MessageTracker.prototype._nextID = function _nextID() {
  245. if (++this._msgid >= MAX_MSGID)
  246. this._msgid = 1;
  247. return this._msgid;
  248. };
  249. ///--- API
  250. /**
  251. * Constructs a new client.
  252. *
  253. * The options object is required, and must contain either a URL (string) or
  254. * a socketPath (string); the socketPath is only if you want to talk to an LDAP
  255. * server over a Unix Domain Socket. Additionally, you can pass in a bunyan
  256. * option that is the result of `new Logger()`, presumably after you've
  257. * configured it.
  258. *
  259. * @param {Object} options must have either url or socketPath.
  260. * @throws {TypeError} on bad input.
  261. */
  262. function Client(options) {
  263. assert.ok(options);
  264. EventEmitter.call(this, options);
  265. var self = this;
  266. var _url;
  267. if (options.url)
  268. _url = url.parse(options.url);
  269. this.host = _url ? _url.hostname : undefined;
  270. this.port = _url ? _url.port : false;
  271. this.secure = _url ? _url.secure : false;
  272. this.url = _url;
  273. this.tlsOptions = options.tlsOptions;
  274. this.socketPath = options.socketPath || false;
  275. this.log = options.log.child({clazz: 'Client'}, true);
  276. this.timeout = parseInt((options.timeout || 0), 10);
  277. this.connectTimeout = parseInt((options.connectTimeout || 0), 10);
  278. this.idleTimeout = parseInt((options.idleTimeout || 0), 10);
  279. if (options.reconnect) {
  280. // Fall back to defaults if options.reconnect === true
  281. var rOpts = (typeof (options.reconnect) === 'object') ?
  282. options.reconnect : {};
  283. this.reconnect = {
  284. initialDelay: parseInt(rOpts.initialDelay || 100, 10),
  285. maxDelay: parseInt(rOpts.maxDelay || 10000, 10),
  286. failAfter: parseInt(rOpts.failAfter, 10) || Infinity
  287. };
  288. }
  289. this.strictDN = (options.strictDN !== undefined) ? options.strictDN : true;
  290. this.queue = new RequestQueue({
  291. size: parseInt((options.queueSize || 0), 10),
  292. timeout: parseInt((options.queueTimeout || 0), 10)
  293. });
  294. if (options.queueDisable) {
  295. this.queue.freeze();
  296. }
  297. // Implicitly configure setup action to bind the client if bindDN and
  298. // bindCredentials are passed in. This will more closely mimic PooledClient
  299. // auto-login behavior.
  300. if (options.bindDN !== undefined &&
  301. options.bindCredentials !== undefined) {
  302. this.on('setup', function (clt, cb) {
  303. clt.bind(options.bindDN, options.bindCredentials, function (err) {
  304. if (err) {
  305. self.emit('error', err);
  306. }
  307. cb(err);
  308. });
  309. });
  310. }
  311. this._socket = null;
  312. this.connected = false;
  313. this.connect();
  314. }
  315. util.inherits(Client, EventEmitter);
  316. module.exports = Client;
  317. /**
  318. * Sends an abandon request to the LDAP server.
  319. *
  320. * The callback will be invoked as soon as the data is flushed out to the
  321. * network, as there is never a response from abandon.
  322. *
  323. * @param {Number} messageID the messageID to abandon.
  324. * @param {Control} controls (optional) either a Control or [Control].
  325. * @param {Function} callback of the form f(err).
  326. * @throws {TypeError} on invalid input.
  327. */
  328. Client.prototype.abandon = function abandon(messageID, controls, callback) {
  329. assert.number(messageID, 'messageID');
  330. if (typeof (controls) === 'function') {
  331. callback = controls;
  332. controls = [];
  333. } else {
  334. controls = validateControls(controls);
  335. }
  336. assert.func(callback, 'callback');
  337. var req = new AbandonRequest({
  338. abandonID: messageID,
  339. controls: controls
  340. });
  341. return this._send(req, 'abandon', null, callback);
  342. };
  343. /**
  344. * Adds an entry to the LDAP server.
  345. *
  346. * Entry can be either [Attribute] or a plain JS object where the
  347. * values are either a plain value or an array of values. Any value (that's
  348. * not an array) will get converted to a string, so keep that in mind.
  349. *
  350. * @param {String} name the DN of the entry to add.
  351. * @param {Object} entry an array of Attributes to be added or a JS object.
  352. * @param {Control} controls (optional) either a Control or [Control].
  353. * @param {Function} callback of the form f(err, res).
  354. * @throws {TypeError} on invalid input.
  355. */
  356. Client.prototype.add = function add(name, entry, controls, callback) {
  357. assert.ok(name !== undefined, 'name');
  358. assert.object(entry, 'entry');
  359. if (typeof (controls) === 'function') {
  360. callback = controls;
  361. controls = [];
  362. } else {
  363. controls = validateControls(controls);
  364. }
  365. assert.func(callback, 'callback');
  366. if (Array.isArray(entry)) {
  367. entry.forEach(function (a) {
  368. if (!Attribute.isAttribute(a))
  369. throw new TypeError('entry must be an Array of Attributes');
  370. });
  371. } else {
  372. var save = entry;
  373. entry = [];
  374. Object.keys(save).forEach(function (k) {
  375. var attr = new Attribute({type: k});
  376. if (Array.isArray(save[k])) {
  377. save[k].forEach(function (v) {
  378. attr.addValue(v.toString());
  379. });
  380. } else {
  381. attr.addValue(save[k].toString());
  382. }
  383. entry.push(attr);
  384. });
  385. }
  386. var req = new AddRequest({
  387. entry: ensureDN(name, this.strictDN),
  388. attributes: entry,
  389. controls: controls
  390. });
  391. return this._send(req, [errors.LDAP_SUCCESS], null, callback);
  392. };
  393. /**
  394. * Performs a simple authentication against the server.
  395. *
  396. * @param {String} name the DN to bind as.
  397. * @param {String} credentials the userPassword associated with name.
  398. * @param {Control} controls (optional) either a Control or [Control].
  399. * @param {Function} callback of the form f(err, res).
  400. * @throws {TypeError} on invalid input.
  401. */
  402. Client.prototype.bind = function bind(name,
  403. credentials,
  404. controls,
  405. callback,
  406. _bypass) {
  407. if (typeof (name) !== 'string' && !(name instanceof dn.DN))
  408. throw new TypeError('name (string) required');
  409. assert.optionalString(credentials, 'credentials');
  410. if (typeof (controls) === 'function') {
  411. callback = controls;
  412. controls = [];
  413. } else {
  414. controls = validateControls(controls);
  415. }
  416. assert.func(callback, 'callback');
  417. var req = new BindRequest({
  418. name: name || '',
  419. authentication: 'Simple',
  420. credentials: credentials || '',
  421. controls: controls
  422. });
  423. return this._send(req, [errors.LDAP_SUCCESS], null, callback, _bypass);
  424. };
  425. /**
  426. * Compares an attribute/value pair with an entry on the LDAP server.
  427. *
  428. * @param {String} name the DN of the entry to compare attributes with.
  429. * @param {String} attr name of an attribute to check.
  430. * @param {String} value value of an attribute to check.
  431. * @param {Control} controls (optional) either a Control or [Control].
  432. * @param {Function} callback of the form f(err, boolean, res).
  433. * @throws {TypeError} on invalid input.
  434. */
  435. Client.prototype.compare = function compare(name,
  436. attr,
  437. value,
  438. controls,
  439. callback) {
  440. assert.ok(name !== undefined, 'name');
  441. assert.string(attr, 'attr');
  442. assert.string(value, 'value');
  443. if (typeof (controls) === 'function') {
  444. callback = controls;
  445. controls = [];
  446. } else {
  447. controls = validateControls(controls);
  448. }
  449. assert.func(callback, 'callback');
  450. var req = new CompareRequest({
  451. entry: ensureDN(name, this.strictDN),
  452. attribute: attr,
  453. value: value,
  454. controls: controls
  455. });
  456. return this._send(req, CMP_EXPECT, null, function (err, res) {
  457. if (err)
  458. return callback(err);
  459. return callback(null, (res.status === errors.LDAP_COMPARE_TRUE), res);
  460. });
  461. };
  462. /**
  463. * Deletes an entry from the LDAP server.
  464. *
  465. * @param {String} name the DN of the entry to delete.
  466. * @param {Control} controls (optional) either a Control or [Control].
  467. * @param {Function} callback of the form f(err, res).
  468. * @throws {TypeError} on invalid input.
  469. */
  470. Client.prototype.del = function del(name, controls, callback) {
  471. assert.ok(name !== undefined, 'name');
  472. if (typeof (controls) === 'function') {
  473. callback = controls;
  474. controls = [];
  475. } else {
  476. controls = validateControls(controls);
  477. }
  478. assert.func(callback, 'callback');
  479. var req = new DeleteRequest({
  480. entry: ensureDN(name, this.strictDN),
  481. controls: controls
  482. });
  483. return this._send(req, [errors.LDAP_SUCCESS], null, callback);
  484. };
  485. /**
  486. * Performs an extended operation on the LDAP server.
  487. *
  488. * Pretty much none of the LDAP extended operations return an OID
  489. * (responseName), so I just don't bother giving it back in the callback.
  490. * It's on the third param in `res` if you need it.
  491. *
  492. * @param {String} name the OID of the extended operation to perform.
  493. * @param {String} value value to pass in for this operation.
  494. * @param {Control} controls (optional) either a Control or [Control].
  495. * @param {Function} callback of the form f(err, value, res).
  496. * @throws {TypeError} on invalid input.
  497. */
  498. Client.prototype.exop = function exop(name, value, controls, callback) {
  499. assert.string(name, 'name');
  500. if (typeof (value) === 'function') {
  501. callback = value;
  502. controls = [];
  503. value = '';
  504. }
  505. if (!(Buffer.isBuffer(value) || typeof (value) === 'string'))
  506. throw new TypeError('value (Buffer || string) required');
  507. if (typeof (controls) === 'function') {
  508. callback = controls;
  509. controls = [];
  510. } else {
  511. controls = validateControls(controls);
  512. }
  513. assert.func(callback, 'callback');
  514. var req = new ExtendedRequest({
  515. requestName: name,
  516. requestValue: value,
  517. controls: controls
  518. });
  519. return this._send(req, [errors.LDAP_SUCCESS], null, function (err, res) {
  520. if (err)
  521. return callback(err);
  522. return callback(null, res.responseValue || '', res);
  523. });
  524. };
  525. /**
  526. * Performs an LDAP modify against the server.
  527. *
  528. * @param {String} name the DN of the entry to modify.
  529. * @param {Change} change update to perform (can be [Change]).
  530. * @param {Control} controls (optional) either a Control or [Control].
  531. * @param {Function} callback of the form f(err, res).
  532. * @throws {TypeError} on invalid input.
  533. */
  534. Client.prototype.modify = function modify(name, change, controls, callback) {
  535. assert.ok(name !== undefined, 'name');
  536. assert.object(change, 'change');
  537. var changes = [];
  538. function changeFromObject(change) {
  539. if (!change.operation && !change.type)
  540. throw new Error('change.operation required');
  541. if (typeof (change.modification) !== 'object')
  542. throw new Error('change.modification (object) required');
  543. if (Object.keys(change.modification).length == 2 &&
  544. typeof (change.modification.type) === 'string' &&
  545. Array.isArray(change.modification.vals)) {
  546. // Use modification directly if it's already normalized:
  547. changes.push(new Change({
  548. operation: change.operation || change.type,
  549. modification: change.modification
  550. }));
  551. } else {
  552. // Normalize the modification object
  553. Object.keys(change.modification).forEach(function (k) {
  554. var mod = {};
  555. mod[k] = change.modification[k];
  556. changes.push(new Change({
  557. operation: change.operation || change.type,
  558. modification: mod
  559. }));
  560. });
  561. }
  562. }
  563. if (Change.isChange(change)) {
  564. changes.push(change);
  565. } else if (Array.isArray(change)) {
  566. change.forEach(function (c) {
  567. if (Change.isChange(c)) {
  568. changes.push(c);
  569. } else {
  570. changeFromObject(c);
  571. }
  572. });
  573. } else {
  574. changeFromObject(change);
  575. }
  576. if (typeof (controls) === 'function') {
  577. callback = controls;
  578. controls = [];
  579. } else {
  580. controls = validateControls(controls);
  581. }
  582. assert.func(callback, 'callback');
  583. var req = new ModifyRequest({
  584. object: ensureDN(name, this.strictDN),
  585. changes: changes,
  586. controls: controls
  587. });
  588. return this._send(req, [errors.LDAP_SUCCESS], null, callback);
  589. };
  590. /**
  591. * Performs an LDAP modifyDN against the server.
  592. *
  593. * This does not allow you to keep the old DN, as while the LDAP protocol
  594. * has a facility for that, it's stupid. Just Search/Add.
  595. *
  596. * This will automatically deal with "new superior" logic.
  597. *
  598. * @param {String} name the DN of the entry to modify.
  599. * @param {String} newName the new DN to move this entry to.
  600. * @param {Control} controls (optional) either a Control or [Control].
  601. * @param {Function} callback of the form f(err, res).
  602. * @throws {TypeError} on invalid input.
  603. */
  604. Client.prototype.modifyDN = function modifyDN(name,
  605. newName,
  606. controls,
  607. callback) {
  608. assert.ok(name !== undefined, 'name');
  609. assert.string(newName, 'newName');
  610. if (typeof (controls) === 'function') {
  611. callback = controls;
  612. controls = [];
  613. } else {
  614. controls = validateControls(controls);
  615. }
  616. assert.func(callback);
  617. var DN = ensureDN(name);
  618. // TODO: is non-strict handling desired here?
  619. var newDN = dn.parse(newName);
  620. var req = new ModifyDNRequest({
  621. entry: DN,
  622. deleteOldRdn: true,
  623. controls: controls
  624. });
  625. if (newDN.length !== 1) {
  626. req.newRdn = dn.parse(newDN.rdns.shift().toString());
  627. req.newSuperior = newDN;
  628. } else {
  629. req.newRdn = newDN;
  630. }
  631. return this._send(req, [errors.LDAP_SUCCESS], null, callback);
  632. };
  633. /**
  634. * Performs an LDAP search against the server.
  635. *
  636. * Note that the defaults for options are a 'base' search, if that's what
  637. * you want you can just pass in a string for options and it will be treated
  638. * as the search filter. Also, you can either pass in programatic Filter
  639. * objects or a filter string as the filter option.
  640. *
  641. * Note that this method is 'special' in that the callback 'res' param will
  642. * have two important events on it, namely 'entry' and 'end' that you can hook
  643. * to. The former will emit a SearchEntry object for each record that comes
  644. * back, and the latter will emit a normal LDAPResult object.
  645. *
  646. * @param {String} base the DN in the tree to start searching at.
  647. * @param {Object} options parameters:
  648. * - {String} scope default of 'base'.
  649. * - {String} filter default of '(objectclass=*)'.
  650. * - {Array} attributes [string] to return.
  651. * - {Boolean} attrsOnly whether to return values.
  652. * @param {Control} controls (optional) either a Control or [Control].
  653. * @param {Function} callback of the form f(err, res).
  654. * @throws {TypeError} on invalid input.
  655. */
  656. Client.prototype.search = function search(base,
  657. options,
  658. controls,
  659. callback,
  660. _bypass) {
  661. assert.ok(base !== undefined, 'search base');
  662. if (Array.isArray(options) || (options instanceof Control)) {
  663. controls = options;
  664. options = {};
  665. } else if (typeof (options) === 'function') {
  666. callback = options;
  667. controls = [];
  668. options = {
  669. filter: new PresenceFilter({attribute: 'objectclass'})
  670. };
  671. } else if (typeof (options) === 'string') {
  672. options = {filter: filters.parseString(options)};
  673. } else if (typeof (options) !== 'object') {
  674. throw new TypeError('options (object) required');
  675. }
  676. if (typeof (options.filter) === 'string') {
  677. options.filter = filters.parseString(options.filter);
  678. } else if (!options.filter) {
  679. options.filter = new PresenceFilter({attribute: 'objectclass'});
  680. } else if (!filters.isFilter(options.filter)) {
  681. throw new TypeError('options.filter (Filter) required');
  682. }
  683. if (typeof (controls) === 'function') {
  684. callback = controls;
  685. controls = [];
  686. } else {
  687. controls = validateControls(controls);
  688. }
  689. assert.func(callback, 'callback');
  690. if (options.attributes) {
  691. if (!Array.isArray(options.attributes)) {
  692. if (typeof (options.attributes) === 'string') {
  693. options.attributes = [options.attributes];
  694. } else {
  695. throw new TypeError('options.attributes must be an Array of Strings');
  696. }
  697. }
  698. }
  699. var self = this;
  700. var baseDN = ensureDN(base, this.strictDN);
  701. function sendRequest(ctrls, emitter, cb) {
  702. var req = new SearchRequest({
  703. baseObject: baseDN,
  704. scope: options.scope || 'base',
  705. filter: options.filter,
  706. derefAliases: options.derefAliases || Protocol.NEVER_DEREF_ALIASES,
  707. sizeLimit: options.sizeLimit || 0,
  708. timeLimit: options.timeLimit || 10,
  709. typesOnly: options.typesOnly || false,
  710. attributes: options.attributes || [],
  711. controls: ctrls
  712. });
  713. return self._send(req,
  714. [errors.LDAP_SUCCESS],
  715. emitter,
  716. cb,
  717. _bypass);
  718. }
  719. if (options.paged) {
  720. // Perform automated search paging
  721. var pageOpts = typeof (options.paged) === 'object' ? options.paged : {};
  722. var size = 100; // Default page size
  723. if (pageOpts.pageSize > 0) {
  724. size = pageOpts.pageSize;
  725. } else if (options.sizeLimit > 1) {
  726. // According to the RFC, servers should ignore the paging control if
  727. // pageSize >= sizelimit. Some might still send results, but it's safer
  728. // to stay under that figure when assigning a default value.
  729. size = options.sizeLimit - 1;
  730. }
  731. var pager = new SearchPager({
  732. callback: callback,
  733. controls: controls,
  734. pageSize: size,
  735. pagePause: pageOpts.pagePause
  736. });
  737. pager.on('search', sendRequest);
  738. pager.begin();
  739. } else {
  740. sendRequest(controls, new EventEmitter(), callback);
  741. }
  742. };
  743. /**
  744. * Unbinds this client from the LDAP server.
  745. *
  746. * Note that unbind does not have a response, so this callback is actually
  747. * optional; either way, the client is disconnected.
  748. *
  749. * @param {Function} callback of the form f(err).
  750. * @throws {TypeError} if you pass in callback as not a function.
  751. */
  752. Client.prototype.unbind = function unbind(callback) {
  753. if (!callback)
  754. callback = function () {};
  755. if (typeof (callback) !== 'function')
  756. throw new TypeError('callback must be a function');
  757. // When the socket closes, it is useful to know whether it was due to a
  758. // user-initiated unbind or something else.
  759. this.unbound = true;
  760. if (!this._socket)
  761. return callback();
  762. var req = new UnbindRequest();
  763. return this._send(req, 'unbind', null, callback);
  764. };
  765. /**
  766. * Attempt to secure connection with StartTLS.
  767. */
  768. Client.prototype.starttls = function starttls(options,
  769. controls,
  770. callback,
  771. _bypass) {
  772. assert.optionalObject(options);
  773. options = options || {};
  774. callback = once(callback);
  775. var self = this;
  776. if (this._starttls) {
  777. return callback(new Error('STARTTLS already in progress or active'));
  778. }
  779. function onSend(err, emitter) {
  780. if (err) {
  781. callback(err);
  782. return;
  783. }
  784. /*
  785. * Now that the request has been sent, block all outgoing messages
  786. * until an error is received or we successfully complete the setup.
  787. */
  788. // TODO: block traffic
  789. self._starttls = {
  790. started: true
  791. };
  792. emitter.on('error', function (err) {
  793. self._starttls = null;
  794. callback(err);
  795. });
  796. emitter.on('end', function (res) {
  797. var sock = self._socket;
  798. /*
  799. * Unplumb socket data during SSL negotiation.
  800. * This will prevent the LDAP parser from stumbling over the TLS
  801. * handshake and raising a ruckus.
  802. */
  803. sock.removeAllListeners('data');
  804. options.socket = sock;
  805. var secure = tls.connect(options);
  806. secure.once('secureConnect', function () {
  807. /*
  808. * Wire up 'data' and 'error' handlers like the normal socket.
  809. * Handling 'end' events isn't necessary since the underlying socket
  810. * will handle those.
  811. */
  812. secure.removeAllListeners('error');
  813. secure.on('data', function onData(data) {
  814. if (self.log.trace())
  815. self.log.trace('data event: %s', util.inspect(data));
  816. self._tracker.parser.write(data);
  817. });
  818. secure.on('error', function (err) {
  819. if (self.log.trace())
  820. self.log.trace({err: err}, 'error event: %s', new Error().stack);
  821. self.emit('error', err);
  822. sock.destroy();
  823. });
  824. callback(null);
  825. });
  826. secure.once('error', function (err) {
  827. // If the SSL negotiation failed, to back to plain mode.
  828. self._starttls = null;
  829. secure.removeAllListeners();
  830. callback(err);
  831. });
  832. self._starttls.success = true;
  833. self._socket = secure;
  834. });
  835. }
  836. var req = new ExtendedRequest({
  837. requestName: '1.3.6.1.4.1.1466.20037',
  838. requestValue: null,
  839. controls: controls
  840. });
  841. return this._send(req,
  842. [errors.LDAP_SUCCESS],
  843. new EventEmitter(),
  844. onSend,
  845. _bypass);
  846. };
  847. /**
  848. * Disconnect from the LDAP server and do not allow reconnection.
  849. *
  850. * If the client is instantiated with proper reconnection options, it's
  851. * possible to initiate new requests after a call to unbind since the client
  852. * will attempt to reconnect in order to fulfill the request.
  853. *
  854. * Calling destroy will prevent any further reconnection from occurring.
  855. *
  856. * @param {Object} err (Optional) error that was cause of client destruction
  857. */
  858. Client.prototype.destroy = function destroy(err) {
  859. this.destroyed = true;
  860. this.queue.freeze();
  861. // Purge any queued requests which are now meaningless
  862. this.queue.flush(function (msg, expect, emitter, cb) {
  863. if (typeof (cb) === 'function') {
  864. cb(new Error('client destroyed'));
  865. }
  866. });
  867. if (this.connected) {
  868. this.unbind();
  869. } else if (this._socket) {
  870. this._socket.destroy();
  871. }
  872. this.emit('destroy', err);
  873. };
  874. /**
  875. * Initiate LDAP connection.
  876. */
  877. Client.prototype.connect = function connect() {
  878. if (this.connecting || this.connected) {
  879. return;
  880. }
  881. var self = this;
  882. var log = this.log;
  883. var socket;
  884. var tracker;
  885. // Establish basic socket connection
  886. function connectSocket(cb) {
  887. cb = once(cb);
  888. function onResult(err, res) {
  889. if (err) {
  890. if (self.connectTimer) {
  891. clearTimeout(self.connectTimer);
  892. self.connectTimer = null;
  893. }
  894. self.emit('connectError', err);
  895. }
  896. cb(err, res);
  897. }
  898. function onConnect() {
  899. if (self.connectTimer) {
  900. clearTimeout(self.connectTimer);
  901. self.connectTimer = null;
  902. }
  903. socket.removeAllListeners('error')
  904. .removeAllListeners('connect')
  905. .removeAllListeners('secureConnect');
  906. tracker.id = nextClientId() + '__' + tracker.id;
  907. self.log = self.log.child({ldap_id: tracker.id}, true);
  908. // Move on to client setup
  909. setupClient(cb);
  910. }
  911. var port = (self.port || self.socketPath);
  912. if (self.secure) {
  913. socket = tls.connect(port, self.host, self.tlsOptions);
  914. socket.once('secureConnect', onConnect);
  915. } else {
  916. socket = net.connect(port, self.host);
  917. socket.once('connect', onConnect);
  918. }
  919. socket.once('error', onResult);
  920. initSocket();
  921. // Setup connection timeout handling, if desired
  922. if (self.connectTimeout) {
  923. self.connectTimer = setTimeout(function onConnectTimeout() {
  924. if (!socket || !socket.readable || !socket.writeable) {
  925. socket.destroy();
  926. self._socket = null;
  927. onResult(new ConnectionError('connection timeout'));
  928. }
  929. }, self.connectTimeout);
  930. }
  931. }
  932. // Initialize socket events and LDAP parser.
  933. function initSocket() {
  934. tracker = new MessageTracker({
  935. id: self.url ? self.url.href : self.socketPath,
  936. parser: new Parser({log: log})
  937. });
  938. // This won't be set on TLS. So. Very. Annoying.
  939. if (typeof (socket.setKeepAlive) !== 'function') {
  940. socket.setKeepAlive = function setKeepAlive(enable, delay) {
  941. return socket.socket ?
  942. socket.socket.setKeepAlive(enable, delay) : false;
  943. };
  944. }
  945. socket.on('data', function onData(data) {
  946. if (log.trace())
  947. log.trace('data event: %s', util.inspect(data));
  948. tracker.parser.write(data);
  949. });
  950. // The "router"
  951. tracker.parser.on('message', function onMessage(message) {
  952. message.connection = self._socket;
  953. var callback = tracker.fetch(message.messageID);
  954. if (!callback) {
  955. log.error({message: message.json}, 'unsolicited message');
  956. return false;
  957. }
  958. return callback(message);
  959. });
  960. tracker.parser.on('error', function onParseError(err) {
  961. self.emit('error', new VError(err, 'Parser error for %s',
  962. tracker.id));
  963. self.connected = false;
  964. socket.end();
  965. });
  966. }
  967. // After connect, register socket event handlers and run any setup actions
  968. function setupClient(cb) {
  969. cb = once(cb);
  970. // Indicate failure if anything goes awry during setup
  971. function bail(err) {
  972. socket.destroy();
  973. cb(err || new Error('client error during setup'));
  974. }
  975. // Work around lack of close event on tls.socket in node < 0.11
  976. ((socket.socket) ? socket.socket : socket).once('close', bail);
  977. socket.once('error', bail);
  978. socket.once('end', bail);
  979. socket.once('timeout', bail);
  980. self._socket = socket;
  981. self._tracker = tracker;
  982. // Run any requested setup (such as automatically performing a bind) on
  983. // socket before signalling successful connection.
  984. // This setup needs to bypass the request queue since all other activity is
  985. // blocked until the connection is considered fully established post-setup.
  986. // Only allow bind/search/starttls for now.
  987. var basicClient = {
  988. bind: function bindBypass(name, credentials, controls, callback) {
  989. return self.bind(name, credentials, controls, callback, true);
  990. },
  991. search: function searchBypass(base, options, controls, callback) {
  992. return self.search(base, options, controls, callback, true);
  993. },
  994. starttls: function starttlsBypass(options, controls, callback) {
  995. return self.starttls(options, controls, callback, true);
  996. },
  997. unbind: self.unbind.bind(self)
  998. };
  999. vasync.forEachPipeline({
  1000. func: function (f, callback) {
  1001. f(basicClient, callback);
  1002. },
  1003. inputs: self.listeners('setup')
  1004. }, function (err, res) {
  1005. if (err) {
  1006. self.emit('setupError', err);
  1007. }
  1008. cb(err);
  1009. });
  1010. }
  1011. // Wire up "official" event handlers after successful connect/setup
  1012. function postSetup() {
  1013. socket.removeAllListeners('error')
  1014. .removeAllListeners('close')
  1015. .removeAllListeners('end')
  1016. .removeAllListeners('timeout');
  1017. // Work around lack of close event on tls.socket in node < 0.11
  1018. ((socket.socket) ? socket.socket : socket).once('close',
  1019. self._onClose.bind(self));
  1020. socket.on('end', function onEnd() {
  1021. if (log.trace())
  1022. log.trace('end event');
  1023. self.emit('end');
  1024. socket.end();
  1025. });
  1026. socket.on('error', function onSocketError(err) {
  1027. if (log.trace())
  1028. log.trace({err: err}, 'error event: %s', new Error().stack);
  1029. self.emit('error', err);
  1030. socket.destroy();
  1031. });
  1032. socket.on('timeout', function onTimeout() {
  1033. if (log.trace())
  1034. log.trace('timeout event');
  1035. self.emit('socketTimeout');
  1036. socket.end();
  1037. });
  1038. }
  1039. var retry;
  1040. var failAfter;
  1041. if (this.reconnect) {
  1042. retry = backoff.exponential({
  1043. initialDelay: this.reconnect.initialDelay,
  1044. maxDelay: this.reconnect.maxDelay
  1045. });
  1046. failAfter = this.reconnect.failAfter;
  1047. } else {
  1048. retry = backoff.exponential({
  1049. initialDelay: 1,
  1050. maxDelay: 2
  1051. });
  1052. failAfter = 1;
  1053. }
  1054. retry.failAfter(failAfter);
  1055. retry.on('ready', function (num, delay) {
  1056. if (self.destroyed) {
  1057. // Cease connection attempts if destroyed
  1058. return;
  1059. }
  1060. connectSocket(function (err) {
  1061. if (!err) {
  1062. postSetup();
  1063. self.connecting = false;
  1064. self.connected = true;
  1065. self.emit('connect', socket);
  1066. self.log.debug('connected after %d attempt(s)', num+1);
  1067. // Flush any queued requests
  1068. self._flushQueue();
  1069. self._connectRetry = null;
  1070. } else {
  1071. retry.backoff(err);
  1072. }
  1073. });
  1074. });
  1075. retry.on('fail', function (err) {
  1076. if (self.destroyed) {
  1077. // Silence any connect/setup errors if destroyed
  1078. return;
  1079. }
  1080. self.log.debug('failed to connect after %d attempts', failAfter);
  1081. // Communicate the last-encountered error
  1082. if (err instanceof ConnectionError) {
  1083. self.emit('connectTimeout', err);
  1084. } else {
  1085. self.emit('error', err);
  1086. }
  1087. });
  1088. this._connectRetry = retry;
  1089. this.connecting = true;
  1090. retry.backoff();
  1091. };
  1092. ///--- Private API
  1093. /**
  1094. * Flush queued requests out to the socket.
  1095. */
  1096. Client.prototype._flushQueue = function _flushQueue() {
  1097. // Pull items we're about to process out of the queue.
  1098. this.queue.flush(this._send.bind(this));
  1099. };
  1100. /**
  1101. * Clean up socket/parser resources after socket close.
  1102. */
  1103. Client.prototype._onClose = function _onClose(had_err) {
  1104. var socket = this._socket;
  1105. var tracker = this._tracker;
  1106. socket.removeAllListeners('connect')
  1107. .removeAllListeners('data')
  1108. .removeAllListeners('drain')
  1109. .removeAllListeners('end')
  1110. .removeAllListeners('error')
  1111. .removeAllListeners('timeout');
  1112. this._socket = null;
  1113. this.connected = false;
  1114. ((socket.socket) ? socket.socket : socket).removeAllListeners('close');
  1115. if (this.log.trace())
  1116. this.log.trace('close event had_err=%s', had_err ? 'yes' : 'no');
  1117. this.emit('close', had_err);
  1118. // On close we have to walk the outstanding messages and go invoke their
  1119. // callback with an error.
  1120. tracker.pending.forEach(function (msgid) {
  1121. var cb = tracker.fetch(msgid);
  1122. tracker.remove(msgid);
  1123. if (socket.unbindMessageID !== parseInt(msgid, 10)) {
  1124. return cb(new ConnectionError(tracker.id + ' closed'));
  1125. } else {
  1126. // Unbinds will be communicated as a success since we're closed
  1127. var unbind = new UnbindResponse({messageID: msgid});
  1128. unbind.status = 'unbind';
  1129. return cb(unbind);
  1130. }
  1131. });
  1132. // Trash any parser or starttls state
  1133. this._tracker = null;
  1134. delete this._starttls;
  1135. // Automatically fire reconnect logic if the socket was closed for any reason
  1136. // other than a user-initiated unbind.
  1137. if (this.reconnect && !this.unbound) {
  1138. this.connect();
  1139. }
  1140. this.unbound = false;
  1141. return false;
  1142. };
  1143. /**
  1144. * Maintain idle timer for client.
  1145. *
  1146. * Will start timer to fire 'idle' event if conditions are satisfied. If
  1147. * conditions are not met and a timer is running, it will be cleared.
  1148. *
  1149. * @param {Boolean} override explicitly disable timer.
  1150. */
  1151. Client.prototype._updateIdle = function _updateIdle(override) {
  1152. if (this.idleTimeout === 0) {
  1153. return;
  1154. }
  1155. // Client must be connected but not waiting on any request data
  1156. var self = this;
  1157. function isIdle(disable) {
  1158. return ((disable !== true) &&
  1159. (self._socket && self.connected) &&
  1160. (self._tracker.pending.length === 0));
  1161. }
  1162. if (isIdle(override)) {
  1163. if (!this._idleTimer) {
  1164. this._idleTimer = setTimeout(function () {
  1165. // Double-check idleness in case socket was torn down
  1166. if (isIdle()) {
  1167. self.emit('idle');
  1168. }
  1169. }, this.idleTimeout);
  1170. }
  1171. } else {
  1172. if (this._idleTimer) {
  1173. clearTimeout(this._idleTimer);
  1174. this._idleTimer = null;
  1175. }
  1176. }
  1177. };
  1178. /**
  1179. * Attempt to send an LDAP request.
  1180. */
  1181. Client.prototype._send = function _send(message,
  1182. expect,
  1183. emitter,
  1184. callback,
  1185. _bypass) {
  1186. assert.ok(message);
  1187. assert.ok(expect);
  1188. assert.optionalObject(emitter);
  1189. assert.ok(callback);
  1190. // Allow connect setup traffic to bypass checks
  1191. if (_bypass && this._socket && this._socket.writable) {
  1192. return this._sendSocket(message, expect, emitter, callback);
  1193. }
  1194. if (!this._socket || !this.connected) {
  1195. if (!this.queue.enqueue(message, expect, emitter, callback)) {
  1196. callback(new ConnectionError('connection unavailable'));
  1197. }
  1198. // Initiate reconnect if needed
  1199. if (this.reconnect) {
  1200. this.connect();
  1201. }
  1202. return false;
  1203. } else {
  1204. this._flushQueue();
  1205. return this._sendSocket(message, expect, emitter, callback);
  1206. }
  1207. };
  1208. Client.prototype._sendSocket = function _sendSocket(message,
  1209. expect,
  1210. emitter,
  1211. callback) {
  1212. var conn = this._socket;
  1213. var tracker = this._tracker;
  1214. var log = this.log;
  1215. var self = this;
  1216. var timer = false;
  1217. var sentEmitter = false;
  1218. function sendResult(event, obj) {
  1219. if (event === 'error' && self.listeners('resultError')) {
  1220. self.emit('resultError', obj);
  1221. }
  1222. if (emitter) {
  1223. if (event === 'error') {
  1224. // Error will go unhandled if emitter hasn't been sent via callback.
  1225. // Execute callback with the error instead.
  1226. if (!sentEmitter)
  1227. return callback(obj);
  1228. }
  1229. return emitter.emit(event, obj);
  1230. }
  1231. if (event === 'error')
  1232. return callback(obj);
  1233. return callback(null, obj);
  1234. }
  1235. function messageCallback(msg) {
  1236. if (timer)
  1237. clearTimeout(timer);
  1238. if (log.trace())
  1239. log.trace({msg: msg ? msg.json : null}, 'response received');
  1240. if (expect === 'abandon')
  1241. return sendResult('end', null);
  1242. if (msg instanceof SearchEntry || msg instanceof SearchReference) {
  1243. var event = msg.constructor.name;
  1244. event = event[0].toLowerCase() + event.slice(1);
  1245. return sendResult(event, msg);
  1246. } else {
  1247. tracker.remove(message.messageID);
  1248. // Potentially mark client as idle
  1249. self._updateIdle();
  1250. if (msg instanceof LDAPResult) {
  1251. if (expect.indexOf(msg.status) === -1) {
  1252. return sendResult('error', errors.getError(msg));
  1253. }
  1254. return sendResult('end', msg);
  1255. } else if (msg instanceof Error) {
  1256. return sendResult('error', msg);
  1257. } else {
  1258. return sendResult('error', new errors.ProtocolError(msg.type));
  1259. }
  1260. }
  1261. }
  1262. function onRequestTimeout() {
  1263. self.emit('timeout', message);
  1264. var cb = tracker.fetch(message.messageID);
  1265. if (cb) {
  1266. //FIXME: the timed-out request should be abandoned
  1267. cb(new errors.TimeoutError('request timeout (client interrupt)'));
  1268. }
  1269. }
  1270. function writeCallback() {
  1271. if (expect === 'abandon') {
  1272. // Mark the messageID specified as abandoned
  1273. tracker.abandon(message.abandonID);
  1274. // No need to track the abandon request itself
  1275. tracker.remove(message.id);
  1276. return callback(null);
  1277. } else if (expect === 'unbind') {
  1278. conn.unbindMessageID = message.id;
  1279. // Mark client as disconnected once unbind clears the socket
  1280. self.connected = false;
  1281. // Some servers will RST the connection after receiving an unbind.
  1282. // Socket errors are blackholed since the connection is being closed.
  1283. conn.removeAllListeners('error');
  1284. conn.on('error', function () {});
  1285. conn.end();
  1286. } else if (emitter) {
  1287. sentEmitter = true;
  1288. return callback(null, emitter);
  1289. }
  1290. return false;
  1291. }
  1292. // Start actually doing something...
  1293. tracker.track(message, messageCallback);
  1294. // Mark client as active
  1295. this._updateIdle(true);
  1296. if (self.timeout) {
  1297. log.trace('Setting timeout to %d', self.timeout);
  1298. timer = setTimeout(onRequestTimeout, self.timeout);
  1299. }
  1300. if (log.trace())
  1301. log.trace('sending request %j', message.json);
  1302. try {
  1303. return conn.write(message.toBer(), writeCallback);
  1304. } catch (e) {
  1305. if (timer)
  1306. clearTimeout(timer);
  1307. log.trace({err: e}, 'Error writing message to socket');
  1308. return callback(e);
  1309. }
  1310. };