index.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. 'use strict';
  2. const packageInfo = require('../../package.json');
  3. const EventEmitter = require('events').EventEmitter;
  4. const net = require('net');
  5. const tls = require('tls');
  6. const os = require('os');
  7. const crypto = require('crypto');
  8. const DataStream = require('./data-stream');
  9. const PassThrough = require('stream').PassThrough;
  10. const shared = require('../shared');
  11. // default timeout values in ms
  12. const CONNECTION_TIMEOUT = 2 * 60 * 1000; // how much to wait for the connection to be established
  13. const SOCKET_TIMEOUT = 10 * 60 * 1000; // how much to wait for socket inactivity before disconnecting the client
  14. const GREETING_TIMEOUT = 30 * 1000; // how much to wait after connection is established but SMTP greeting is not receieved
  15. /**
  16. * Generates a SMTP connection object
  17. *
  18. * Optional options object takes the following possible properties:
  19. *
  20. * * **port** - is the port to connect to (defaults to 587 or 465)
  21. * * **host** - is the hostname or IP address to connect to (defaults to 'localhost')
  22. * * **secure** - use SSL
  23. * * **ignoreTLS** - ignore server support for STARTTLS
  24. * * **requireTLS** - forces the client to use STARTTLS
  25. * * **name** - the name of the client server
  26. * * **localAddress** - outbound address to bind to (see: http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener)
  27. * * **greetingTimeout** - Time to wait in ms until greeting message is received from the server (defaults to 10000)
  28. * * **connectionTimeout** - how many milliseconds to wait for the connection to establish
  29. * * **socketTimeout** - Time of inactivity until the connection is closed (defaults to 1 hour)
  30. * * **lmtp** - if true, uses LMTP instead of SMTP protocol
  31. * * **logger** - bunyan compatible logger interface
  32. * * **debug** - if true pass SMTP traffic to the logger
  33. * * **tls** - options for createCredentials
  34. * * **socket** - existing socket to use instead of creating a new one (see: http://nodejs.org/api/net.html#net_class_net_socket)
  35. * * **secured** - boolean indicates that the provided socket has already been upgraded to tls
  36. *
  37. * @constructor
  38. * @namespace SMTP Client module
  39. * @param {Object} [options] Option properties
  40. */
  41. class SMTPConnection extends EventEmitter {
  42. constructor(options) {
  43. super(options);
  44. this.id = crypto
  45. .randomBytes(8)
  46. .toString('base64')
  47. .replace(/\W/g, '');
  48. this.stage = 'init';
  49. this.options = options || {};
  50. this.secureConnection = !!this.options.secure;
  51. this.alreadySecured = !!this.options.secured;
  52. this.port = this.options.port || (this.secureConnection ? 465 : 587);
  53. this.host = this.options.host || 'localhost';
  54. if (typeof this.options.secure === 'undefined' && this.port === 465) {
  55. // if secure option is not set but port is 465, then default to secure
  56. this.secureConnection = true;
  57. }
  58. this.name = this.options.name || this._getHostname();
  59. this.logger = shared.getLogger(this.options, {
  60. component: this.options.component || 'smtp-connection',
  61. sid: this.id
  62. });
  63. /**
  64. * Expose version nr, just for the reference
  65. * @type {String}
  66. */
  67. this.version = packageInfo.version;
  68. /**
  69. * If true, then the user is authenticated
  70. * @type {Boolean}
  71. */
  72. this.authenticated = false;
  73. /**
  74. * If set to true, this instance is no longer active
  75. * @private
  76. */
  77. this.destroyed = false;
  78. /**
  79. * Defines if the current connection is secure or not. If not,
  80. * STARTTLS can be used if available
  81. * @private
  82. */
  83. this.secure = !!this.secureConnection;
  84. /**
  85. * Store incomplete messages coming from the server
  86. * @private
  87. */
  88. this._remainder = '';
  89. /**
  90. * Unprocessed responses from the server
  91. * @type {Array}
  92. */
  93. this._responseQueue = [];
  94. this.lastServerResponse = false;
  95. /**
  96. * The socket connecting to the server
  97. * @publick
  98. */
  99. this._socket = false;
  100. /**
  101. * Lists supported auth mechanisms
  102. * @private
  103. */
  104. this._supportedAuth = [];
  105. /**
  106. * Includes current envelope (from, to)
  107. * @private
  108. */
  109. this._envelope = false;
  110. /**
  111. * Lists supported extensions
  112. * @private
  113. */
  114. this._supportedExtensions = [];
  115. /**
  116. * Defines the maximum allowed size for a single message
  117. * @private
  118. */
  119. this._maxAllowedSize = 0;
  120. /**
  121. * Function queue to run if a data chunk comes from the server
  122. * @private
  123. */
  124. this._responseActions = [];
  125. this._recipientQueue = [];
  126. /**
  127. * Timeout variable for waiting the greeting
  128. * @private
  129. */
  130. this._greetingTimeout = false;
  131. /**
  132. * Timeout variable for waiting the connection to start
  133. * @private
  134. */
  135. this._connectionTimeout = false;
  136. /**
  137. * If the socket is deemed already closed
  138. * @private
  139. */
  140. this._destroyed = false;
  141. /**
  142. * If the socket is already being closed
  143. * @private
  144. */
  145. this._closing = false;
  146. }
  147. /**
  148. * Creates a connection to a SMTP server and sets up connection
  149. * listener
  150. */
  151. connect(connectCallback) {
  152. if (typeof connectCallback === 'function') {
  153. this.once('connect', () => {
  154. this.logger.debug(
  155. {
  156. tnx: 'smtp'
  157. },
  158. 'SMTP handshake finished'
  159. );
  160. connectCallback();
  161. });
  162. }
  163. let opts = {
  164. port: this.port,
  165. host: this.host
  166. };
  167. if (this.options.localAddress) {
  168. opts.localAddress = this.options.localAddress;
  169. }
  170. if (this.options.connection) {
  171. // connection is already opened
  172. this._socket = this.options.connection;
  173. if (this.secureConnection && !this.alreadySecured) {
  174. setImmediate(() =>
  175. this._upgradeConnection(err => {
  176. if (err) {
  177. this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'CONN');
  178. return;
  179. }
  180. this._onConnect();
  181. })
  182. );
  183. } else {
  184. setImmediate(() => this._onConnect());
  185. }
  186. } else if (this.options.socket) {
  187. // socket object is set up but not yet connected
  188. this._socket = this.options.socket;
  189. try {
  190. this._socket.connect(this.port, this.host, () => {
  191. this._socket.setKeepAlive(true);
  192. this._onConnect();
  193. });
  194. } catch (E) {
  195. return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN'));
  196. }
  197. } else if (this.secureConnection) {
  198. // connect using tls
  199. if (this.options.tls) {
  200. Object.keys(this.options.tls).forEach(key => {
  201. opts[key] = this.options.tls[key];
  202. });
  203. }
  204. try {
  205. this._socket = tls.connect(this.port, this.host, opts, () => {
  206. this._socket.setKeepAlive(true);
  207. this._onConnect();
  208. });
  209. } catch (E) {
  210. return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN'));
  211. }
  212. } else {
  213. // connect using plaintext
  214. try {
  215. this._socket = net.connect(opts, () => {
  216. this._socket.setKeepAlive(true);
  217. this._onConnect();
  218. });
  219. } catch (E) {
  220. return setImmediate(() => this._onError(E, 'ECONNECTION', false, 'CONN'));
  221. }
  222. }
  223. this._connectionTimeout = setTimeout(() => {
  224. this._onError('Connection timeout', 'ETIMEDOUT', false, 'CONN');
  225. }, this.options.connectionTimeout || CONNECTION_TIMEOUT);
  226. this._socket.on('error', err => {
  227. this._onError(err, 'ECONNECTION', false, 'CONN');
  228. });
  229. }
  230. /**
  231. * Sends QUIT
  232. */
  233. quit() {
  234. this._sendCommand('QUIT');
  235. this._responseActions.push(this.close);
  236. }
  237. /**
  238. * Closes the connection to the server
  239. */
  240. close() {
  241. clearTimeout(this._connectionTimeout);
  242. clearTimeout(this._greetingTimeout);
  243. this._responseActions = [];
  244. // allow to run this function only once
  245. if (this._closing) {
  246. return;
  247. }
  248. this._closing = true;
  249. let closeMethod = 'end';
  250. if (this.stage === 'init') {
  251. // Close the socket immediately when connection timed out
  252. closeMethod = 'destroy';
  253. }
  254. this.logger.debug(
  255. {
  256. tnx: 'smtp'
  257. },
  258. 'Closing connection to the server using "%s"',
  259. closeMethod
  260. );
  261. let socket = (this._socket && this._socket.socket) || this._socket;
  262. if (socket && !socket.destroyed) {
  263. try {
  264. this._socket[closeMethod]();
  265. } catch (E) {
  266. // just ignore
  267. }
  268. }
  269. this._destroy();
  270. }
  271. /**
  272. * Authenticate user
  273. */
  274. login(authData, callback) {
  275. this._auth = authData || {};
  276. // Select SASL authentication method
  277. this._authMethod =
  278. (this._auth.method || '')
  279. .toString()
  280. .trim()
  281. .toUpperCase() || false;
  282. if (!this._authMethod && this._auth.oauth2 && !this._auth.credentials) {
  283. this._authMethod = 'XOAUTH2';
  284. } else if (!this._authMethod || (this._authMethod === 'XOAUTH2' && !this._auth.oauth2)) {
  285. // use first supported
  286. this._authMethod = (this._supportedAuth[0] || 'PLAIN').toUpperCase().trim();
  287. }
  288. if (this._authMethod !== 'XOAUTH2' && (!this._auth.credentials || !this._auth.credentials.user || !this._auth.credentials.pass)) {
  289. if (this._auth.user && this._auth.pass) {
  290. this._auth.credentials = {
  291. user: this._auth.user,
  292. pass: this._auth.pass
  293. };
  294. } else {
  295. return callback(this._formatError('Missing credentials for "' + this._authMethod + '"', 'EAUTH', false, 'API'));
  296. }
  297. }
  298. switch (this._authMethod) {
  299. case 'XOAUTH2':
  300. this._handleXOauth2Token(false, callback);
  301. return;
  302. case 'LOGIN':
  303. this._responseActions.push(str => {
  304. this._actionAUTH_LOGIN_USER(str, callback);
  305. });
  306. this._sendCommand('AUTH LOGIN');
  307. return;
  308. case 'PLAIN':
  309. this._responseActions.push(str => {
  310. this._actionAUTHComplete(str, callback);
  311. });
  312. this._sendCommand(
  313. 'AUTH PLAIN ' +
  314. Buffer.from(
  315. //this._auth.user+'\u0000'+
  316. '\u0000' + // skip authorization identity as it causes problems with some servers
  317. this._auth.credentials.user +
  318. '\u0000' +
  319. this._auth.credentials.pass,
  320. 'utf-8'
  321. ).toString('base64')
  322. );
  323. return;
  324. case 'CRAM-MD5':
  325. this._responseActions.push(str => {
  326. this._actionAUTH_CRAM_MD5(str, callback);
  327. });
  328. this._sendCommand('AUTH CRAM-MD5');
  329. return;
  330. }
  331. return callback(this._formatError('Unknown authentication method "' + this._authMethod + '"', 'EAUTH', false, 'API'));
  332. }
  333. /**
  334. * Sends a message
  335. *
  336. * @param {Object} envelope Envelope object, {from: addr, to: [addr]}
  337. * @param {Object} message String, Buffer or a Stream
  338. * @param {Function} callback Callback to return once sending is completed
  339. */
  340. send(envelope, message, done) {
  341. if (!message) {
  342. return done(this._formatError('Empty message', 'EMESSAGE', false, 'API'));
  343. }
  344. // reject larger messages than allowed
  345. if (this._maxAllowedSize && envelope.size > this._maxAllowedSize) {
  346. return setImmediate(() => {
  347. done(this._formatError('Message size larger than allowed ' + this._maxAllowedSize, 'EMESSAGE', false, 'MAIL FROM'));
  348. });
  349. }
  350. // ensure that callback is only called once
  351. let returned = false;
  352. let callback = function() {
  353. if (returned) {
  354. return;
  355. }
  356. returned = true;
  357. done(...arguments);
  358. };
  359. if (typeof message.on === 'function') {
  360. message.on('error', err => callback(this._formatError(err, 'ESTREAM', false, 'API')));
  361. }
  362. let startTime = Date.now();
  363. this._setEnvelope(envelope, (err, info) => {
  364. if (err) {
  365. return callback(err);
  366. }
  367. let envelopeTime = Date.now();
  368. let stream = this._createSendStream((err, str) => {
  369. if (err) {
  370. return callback(err);
  371. }
  372. info.envelopeTime = envelopeTime - startTime;
  373. info.messageTime = Date.now() - envelopeTime;
  374. info.messageSize = stream.outByteCount;
  375. info.response = str;
  376. return callback(null, info);
  377. });
  378. if (typeof message.pipe === 'function') {
  379. message.pipe(stream);
  380. } else {
  381. stream.write(message);
  382. stream.end();
  383. }
  384. });
  385. }
  386. /**
  387. * Resets connection state
  388. *
  389. * @param {Function} callback Callback to return once connection is reset
  390. */
  391. reset(callback) {
  392. this._sendCommand('RSET');
  393. this._responseActions.push(str => {
  394. if (str.charAt(0) !== '2') {
  395. return callback(this._formatError('Could not reset session state:\n' + str, 'EPROTOCOL', str, 'RSET'));
  396. }
  397. this._envelope = false;
  398. return callback(null, true);
  399. });
  400. }
  401. /**
  402. * Connection listener that is run when the connection to
  403. * the server is opened
  404. *
  405. * @event
  406. */
  407. _onConnect() {
  408. clearTimeout(this._connectionTimeout);
  409. this.logger.info(
  410. {
  411. tnx: 'network',
  412. localAddress: this._socket.localAddress,
  413. localPort: this._socket.localPort,
  414. remoteAddress: this._socket.remoteAddress,
  415. remotePort: this._socket.remotePort
  416. },
  417. '%s established to %s:%s',
  418. this.secure ? 'Secure connection' : 'Connection',
  419. this._socket.remoteAddress,
  420. this._socket.remotePort
  421. );
  422. if (this._destroyed) {
  423. // Connection was established after we already had canceled it
  424. this.close();
  425. return;
  426. }
  427. this.stage = 'connected';
  428. // clear existing listeners for the socket
  429. this._socket.removeAllListeners('data');
  430. this._socket.removeAllListeners('timeout');
  431. this._socket.removeAllListeners('close');
  432. this._socket.removeAllListeners('end');
  433. this._socket.on('data', chunk => this._onData(chunk));
  434. this._socket.once('close', errored => this._onClose(errored));
  435. this._socket.once('end', () => this._onEnd());
  436. this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT);
  437. this._socket.on('timeout', () => this._onTimeout());
  438. this._greetingTimeout = setTimeout(() => {
  439. // if still waiting for greeting, give up
  440. if (this._socket && !this._destroyed && this._responseActions[0] === this._actionGreeting) {
  441. this._onError('Greeting never received', 'ETIMEDOUT', false, 'CONN');
  442. }
  443. }, this.options.greetingTimeout || GREETING_TIMEOUT);
  444. this._responseActions.push(this._actionGreeting);
  445. // we have a 'data' listener set up so resume socket if it was paused
  446. this._socket.resume();
  447. }
  448. /**
  449. * 'data' listener for data coming from the server
  450. *
  451. * @event
  452. * @param {Buffer} chunk Data chunk coming from the server
  453. */
  454. _onData(chunk) {
  455. if (this._destroyed || !chunk || !chunk.length) {
  456. return;
  457. }
  458. let data = (chunk || '').toString('binary');
  459. let lines = (this._remainder + data).split(/\r?\n/);
  460. let lastline;
  461. this._remainder = lines.pop();
  462. for (let i = 0, len = lines.length; i < len; i++) {
  463. if (this._responseQueue.length) {
  464. lastline = this._responseQueue[this._responseQueue.length - 1];
  465. if (/^\d+-/.test(lastline.split('\n').pop())) {
  466. this._responseQueue[this._responseQueue.length - 1] += '\n' + lines[i];
  467. continue;
  468. }
  469. }
  470. this._responseQueue.push(lines[i]);
  471. }
  472. this._processResponse();
  473. }
  474. /**
  475. * 'error' listener for the socket
  476. *
  477. * @event
  478. * @param {Error} err Error object
  479. * @param {String} type Error name
  480. */
  481. _onError(err, type, data, command) {
  482. clearTimeout(this._connectionTimeout);
  483. clearTimeout(this._greetingTimeout);
  484. if (this._destroyed) {
  485. // just ignore, already closed
  486. // this might happen when a socket is canceled because of reached timeout
  487. // but the socket timeout error itself receives only after
  488. return;
  489. }
  490. err = this._formatError(err, type, data, command);
  491. let entry = {
  492. err
  493. };
  494. if (type) {
  495. entry.errorType = type;
  496. }
  497. if (data) {
  498. entry.errorData = data;
  499. }
  500. if (command) {
  501. entry.command = command;
  502. }
  503. this.logger.error(data, err.message);
  504. this.emit('error', err);
  505. this.close();
  506. }
  507. _formatError(message, type, response, command) {
  508. let err;
  509. if (/Error\]$/i.test(Object.prototype.toString.call(message))) {
  510. err = message;
  511. } else {
  512. err = new Error(message);
  513. }
  514. if (type && type !== 'Error') {
  515. err.code = type;
  516. }
  517. if (response) {
  518. err.response = response;
  519. err.message += ': ' + response;
  520. }
  521. let responseCode = (typeof response === 'string' && Number((response.match(/^\d+/) || [])[0])) || false;
  522. if (responseCode) {
  523. err.responseCode = responseCode;
  524. }
  525. if (command) {
  526. err.command = command;
  527. }
  528. return err;
  529. }
  530. /**
  531. * 'close' listener for the socket
  532. *
  533. * @event
  534. */
  535. _onClose() {
  536. this.logger.info(
  537. {
  538. tnx: 'network'
  539. },
  540. 'Connection closed'
  541. );
  542. if (this.upgrading && !this._destroyed) {
  543. return this._onError(new Error('Connection closed unexpectedly'), 'ETLS', false, 'CONN');
  544. } else if (![this._actionGreeting, this.close].includes(this._responseActions[0]) && !this._destroyed) {
  545. return this._onError(new Error('Connection closed unexpectedly'), 'ECONNECTION', false, 'CONN');
  546. }
  547. this._destroy();
  548. }
  549. /**
  550. * 'end' listener for the socket
  551. *
  552. * @event
  553. */
  554. _onEnd() {
  555. this._destroy();
  556. }
  557. /**
  558. * 'timeout' listener for the socket
  559. *
  560. * @event
  561. */
  562. _onTimeout() {
  563. return this._onError(new Error('Timeout'), 'ETIMEDOUT', false, 'CONN');
  564. }
  565. /**
  566. * Destroys the client, emits 'end'
  567. */
  568. _destroy() {
  569. if (this._destroyed) {
  570. return;
  571. }
  572. this._destroyed = true;
  573. this.emit('end');
  574. }
  575. /**
  576. * Upgrades the connection to TLS
  577. *
  578. * @param {Function} callback Callback function to run when the connection
  579. * has been secured
  580. */
  581. _upgradeConnection(callback) {
  582. // do not remove all listeners or it breaks node v0.10 as there's
  583. // apparently a 'finish' event set that would be cleared as well
  584. // we can safely keep 'error', 'end', 'close' etc. events
  585. this._socket.removeAllListeners('data'); // incoming data is going to be gibberish from this point onwards
  586. this._socket.removeAllListeners('timeout'); // timeout will be re-set for the new socket object
  587. let socketPlain = this._socket;
  588. let opts = {
  589. socket: this._socket,
  590. host: this.host
  591. };
  592. Object.keys(this.options.tls || {}).forEach(key => {
  593. opts[key] = this.options.tls[key];
  594. });
  595. this.upgrading = true;
  596. this._socket = tls.connect(opts, () => {
  597. this.secure = true;
  598. this.upgrading = false;
  599. this._socket.on('data', chunk => this._onData(chunk));
  600. socketPlain.removeAllListeners('close');
  601. socketPlain.removeAllListeners('end');
  602. return callback(null, true);
  603. });
  604. this._socket.on('error', err => this._onError(err, 'ESOCKET', false, 'CONN'));
  605. this._socket.once('close', errored => this._onClose(errored));
  606. this._socket.once('end', () => this._onEnd());
  607. this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT); // 10 min.
  608. this._socket.on('timeout', () => this._onTimeout());
  609. // resume in case the socket was paused
  610. socketPlain.resume();
  611. }
  612. /**
  613. * Processes queued responses from the server
  614. *
  615. * @param {Boolean} force If true, ignores _processing flag
  616. */
  617. _processResponse() {
  618. if (!this._responseQueue.length) {
  619. return false;
  620. }
  621. let str = (this.lastServerResponse = (this._responseQueue.shift() || '').toString());
  622. if (/^\d+-/.test(str.split('\n').pop())) {
  623. // keep waiting for the final part of multiline response
  624. return;
  625. }
  626. if (this.options.debug || this.options.transactionLog) {
  627. this.logger.debug(
  628. {
  629. tnx: 'server'
  630. },
  631. str.replace(/\r?\n$/, '')
  632. );
  633. }
  634. if (!str.trim()) {
  635. // skip unexpected empty lines
  636. setImmediate(() => this._processResponse(true));
  637. }
  638. let action = this._responseActions.shift();
  639. if (typeof action === 'function') {
  640. action.call(this, str);
  641. setImmediate(() => this._processResponse(true));
  642. } else {
  643. return this._onError(new Error('Unexpected Response'), 'EPROTOCOL', str, 'CONN');
  644. }
  645. }
  646. /**
  647. * Send a command to the server, append \r\n
  648. *
  649. * @param {String} str String to be sent to the server
  650. */
  651. _sendCommand(str) {
  652. if (this._destroyed) {
  653. // Connection already closed, can't send any more data
  654. return;
  655. }
  656. if (this._socket.destroyed) {
  657. return this.close();
  658. }
  659. if (this.options.debug || this.options.transactionLog) {
  660. this.logger.debug(
  661. {
  662. tnx: 'client'
  663. },
  664. (str || '').toString().replace(/\r?\n$/, '')
  665. );
  666. }
  667. this._socket.write(Buffer.from(str + '\r\n', 'utf-8'));
  668. }
  669. /**
  670. * Initiates a new message by submitting envelope data, starting with
  671. * MAIL FROM: command
  672. *
  673. * @param {Object} envelope Envelope object in the form of
  674. * {from:'...', to:['...']}
  675. * or
  676. * {from:{address:'...',name:'...'}, to:[address:'...',name:'...']}
  677. */
  678. _setEnvelope(envelope, callback) {
  679. let args = [];
  680. let useSmtpUtf8 = false;
  681. this._envelope = envelope || {};
  682. this._envelope.from = ((this._envelope.from && this._envelope.from.address) || this._envelope.from || '').toString().trim();
  683. this._envelope.to = [].concat(this._envelope.to || []).map(to => ((to && to.address) || to || '').toString().trim());
  684. if (!this._envelope.to.length) {
  685. return callback(this._formatError('No recipients defined', 'EENVELOPE', false, 'API'));
  686. }
  687. if (this._envelope.from && /[\r\n<>]/.test(this._envelope.from)) {
  688. return callback(this._formatError('Invalid sender ' + JSON.stringify(this._envelope.from), 'EENVELOPE', false, 'API'));
  689. }
  690. // check if the sender address uses only ASCII characters,
  691. // otherwise require usage of SMTPUTF8 extension
  692. if (/[\x80-\uFFFF]/.test(this._envelope.from)) {
  693. useSmtpUtf8 = true;
  694. }
  695. for (let i = 0, len = this._envelope.to.length; i < len; i++) {
  696. if (!this._envelope.to[i] || /[\r\n<>]/.test(this._envelope.to[i])) {
  697. return callback(this._formatError('Invalid recipient ' + JSON.stringify(this._envelope.to[i]), 'EENVELOPE', false, 'API'));
  698. }
  699. // check if the recipients addresses use only ASCII characters,
  700. // otherwise require usage of SMTPUTF8 extension
  701. if (/[\x80-\uFFFF]/.test(this._envelope.to[i])) {
  702. useSmtpUtf8 = true;
  703. }
  704. }
  705. // clone the recipients array for latter manipulation
  706. this._envelope.rcptQueue = JSON.parse(JSON.stringify(this._envelope.to || []));
  707. this._envelope.rejected = [];
  708. this._envelope.rejectedErrors = [];
  709. this._envelope.accepted = [];
  710. if (this._envelope.dsn) {
  711. try {
  712. this._envelope.dsn = this._setDsnEnvelope(this._envelope.dsn);
  713. } catch (err) {
  714. return callback(this._formatError('Invalid DSN ' + err.message, 'EENVELOPE', false, 'API'));
  715. }
  716. }
  717. this._responseActions.push(str => {
  718. this._actionMAIL(str, callback);
  719. });
  720. // If the server supports SMTPUTF8 and the envelope includes an internationalized
  721. // email address then append SMTPUTF8 keyword to the MAIL FROM command
  722. if (useSmtpUtf8 && this._supportedExtensions.includes('SMTPUTF8')) {
  723. args.push('SMTPUTF8');
  724. this._usingSmtpUtf8 = true;
  725. }
  726. // If the server supports 8BITMIME and the message might contain non-ascii bytes
  727. // then append the 8BITMIME keyword to the MAIL FROM command
  728. if (this._envelope.use8BitMime && this._supportedExtensions.includes('8BITMIME')) {
  729. args.push('BODY=8BITMIME');
  730. this._using8BitMime = true;
  731. }
  732. if (this._envelope.size && this._supportedExtensions.includes('SIZE')) {
  733. args.push('SIZE=' + this._envelope.size);
  734. }
  735. // If the server supports DSN and the envelope includes an DSN prop
  736. // then append DSN params to the MAIL FROM command
  737. if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) {
  738. if (this._envelope.dsn.ret) {
  739. args.push('RET=' + shared.encodeXText(this._envelope.dsn.ret));
  740. }
  741. if (this._envelope.dsn.envid) {
  742. args.push('ENVID=' + shared.encodeXText(this._envelope.dsn.envid));
  743. }
  744. }
  745. this._sendCommand('MAIL FROM:<' + this._envelope.from + '>' + (args.length ? ' ' + args.join(' ') : ''));
  746. }
  747. _setDsnEnvelope(params) {
  748. let ret = (params.ret || params.return || '').toString().toUpperCase() || null;
  749. if (ret) {
  750. switch (ret) {
  751. case 'HDRS':
  752. case 'HEADERS':
  753. ret = 'HDRS';
  754. break;
  755. case 'FULL':
  756. case 'BODY':
  757. ret = 'full';
  758. break;
  759. }
  760. }
  761. if (ret && !['FULL', 'HDRS'].includes(ret)) {
  762. throw new Error('ret: ' + JSON.stringify(ret));
  763. }
  764. let envid = (params.envid || params.id || '').toString() || null;
  765. let notify = params.notify || null;
  766. if (notify) {
  767. if (typeof notify === 'string') {
  768. notify = notify.split(',');
  769. }
  770. notify = notify.map(n => n.trim().toUpperCase());
  771. let validNotify = ['NEVER', 'SUCCESS', 'FAILURE', 'DELAY'];
  772. let invaliNotify = notify.filter(n => !validNotify.includes(n));
  773. if (invaliNotify.length || (notify.length > 1 && notify.includes('NEVER'))) {
  774. throw new Error('notify: ' + JSON.stringify(notify.join(',')));
  775. }
  776. notify = notify.join(',');
  777. }
  778. let orcpt = (params.orcpt || params.recipient || '').toString() || null;
  779. if (orcpt && orcpt.indexOf(';') < 0) {
  780. orcpt = 'rfc822;' + orcpt;
  781. }
  782. return {
  783. ret,
  784. envid,
  785. notify,
  786. orcpt
  787. };
  788. }
  789. _getDsnRcptToArgs() {
  790. let args = [];
  791. // If the server supports DSN and the envelope includes an DSN prop
  792. // then append DSN params to the RCPT TO command
  793. if (this._envelope.dsn && this._supportedExtensions.includes('DSN')) {
  794. if (this._envelope.dsn.notify) {
  795. args.push('NOTIFY=' + shared.encodeXText(this._envelope.dsn.notify));
  796. }
  797. if (this._envelope.dsn.orcpt) {
  798. args.push('ORCPT=' + shared.encodeXText(this._envelope.dsn.orcpt));
  799. }
  800. }
  801. return args.length ? ' ' + args.join(' ') : '';
  802. }
  803. _createSendStream(callback) {
  804. let dataStream = new DataStream();
  805. let logStream;
  806. if (this.options.lmtp) {
  807. this._envelope.accepted.forEach((recipient, i) => {
  808. let final = i === this._envelope.accepted.length - 1;
  809. this._responseActions.push(str => {
  810. this._actionLMTPStream(recipient, final, str, callback);
  811. });
  812. });
  813. } else {
  814. this._responseActions.push(str => {
  815. this._actionSMTPStream(str, callback);
  816. });
  817. }
  818. dataStream.pipe(this._socket, {
  819. end: false
  820. });
  821. if (this.options.debug) {
  822. logStream = new PassThrough();
  823. logStream.on('readable', () => {
  824. let chunk;
  825. while ((chunk = logStream.read())) {
  826. this.logger.debug(
  827. {
  828. tnx: 'message'
  829. },
  830. chunk.toString('binary').replace(/\r?\n$/, '')
  831. );
  832. }
  833. });
  834. dataStream.pipe(logStream);
  835. }
  836. dataStream.once('end', () => {
  837. this.logger.info(
  838. {
  839. tnx: 'message',
  840. inByteCount: dataStream.inByteCount,
  841. outByteCount: dataStream.outByteCount
  842. },
  843. '<%s bytes encoded mime message (source size %s bytes)>',
  844. dataStream.outByteCount,
  845. dataStream.inByteCount
  846. );
  847. });
  848. return dataStream;
  849. }
  850. /** ACTIONS **/
  851. /**
  852. * Will be run after the connection is created and the server sends
  853. * a greeting. If the incoming message starts with 220 initiate
  854. * SMTP session by sending EHLO command
  855. *
  856. * @param {String} str Message from the server
  857. */
  858. _actionGreeting(str) {
  859. clearTimeout(this._greetingTimeout);
  860. if (str.substr(0, 3) !== '220') {
  861. this._onError(new Error('Invalid greeting from server:\n' + str), 'EPROTOCOL', str, 'CONN');
  862. return;
  863. }
  864. if (this.options.lmtp) {
  865. this._responseActions.push(this._actionLHLO);
  866. this._sendCommand('LHLO ' + this.name);
  867. } else {
  868. this._responseActions.push(this._actionEHLO);
  869. this._sendCommand('EHLO ' + this.name);
  870. }
  871. }
  872. /**
  873. * Handles server response for LHLO command. If it yielded in
  874. * error, emit 'error', otherwise treat this as an EHLO response
  875. *
  876. * @param {String} str Message from the server
  877. */
  878. _actionLHLO(str) {
  879. if (str.charAt(0) !== '2') {
  880. this._onError(new Error('Invalid response for LHLO:\n' + str), 'EPROTOCOL', str, 'LHLO');
  881. return;
  882. }
  883. this._actionEHLO(str);
  884. }
  885. /**
  886. * Handles server response for EHLO command. If it yielded in
  887. * error, try HELO instead, otherwise initiate TLS negotiation
  888. * if STARTTLS is supported by the server or move into the
  889. * authentication phase.
  890. *
  891. * @param {String} str Message from the server
  892. */
  893. _actionEHLO(str) {
  894. let match;
  895. if (str.substr(0, 3) === '421') {
  896. this._onError(new Error('Server terminates connection:\n' + str), 'ECONNECTION', str, 'EHLO');
  897. return;
  898. }
  899. if (str.charAt(0) !== '2') {
  900. if (this.options.requireTLS) {
  901. this._onError(new Error('EHLO failed but HELO does not support required STARTTLS:\n' + str), 'ECONNECTION', str, 'EHLO');
  902. return;
  903. }
  904. // Try HELO instead
  905. this._responseActions.push(this._actionHELO);
  906. this._sendCommand('HELO ' + this.name);
  907. return;
  908. }
  909. // Detect if the server supports STARTTLS
  910. if (!this.secure && !this.options.ignoreTLS && (/[ -]STARTTLS\b/im.test(str) || this.options.requireTLS)) {
  911. this._sendCommand('STARTTLS');
  912. this._responseActions.push(this._actionSTARTTLS);
  913. return;
  914. }
  915. // Detect if the server supports SMTPUTF8
  916. if (/[ -]SMTPUTF8\b/im.test(str)) {
  917. this._supportedExtensions.push('SMTPUTF8');
  918. }
  919. // Detect if the server supports DSN
  920. if (/[ -]DSN\b/im.test(str)) {
  921. this._supportedExtensions.push('DSN');
  922. }
  923. // Detect if the server supports 8BITMIME
  924. if (/[ -]8BITMIME\b/im.test(str)) {
  925. this._supportedExtensions.push('8BITMIME');
  926. }
  927. // Detect if the server supports PIPELINING
  928. if (/[ -]PIPELINING\b/im.test(str)) {
  929. this._supportedExtensions.push('PIPELINING');
  930. }
  931. // Detect if the server supports PLAIN auth
  932. if (/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)PLAIN/i.test(str)) {
  933. this._supportedAuth.push('PLAIN');
  934. }
  935. // Detect if the server supports LOGIN auth
  936. if (/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)LOGIN/i.test(str)) {
  937. this._supportedAuth.push('LOGIN');
  938. }
  939. // Detect if the server supports CRAM-MD5 auth
  940. if (/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)CRAM-MD5/i.test(str)) {
  941. this._supportedAuth.push('CRAM-MD5');
  942. }
  943. // Detect if the server supports XOAUTH2 auth
  944. if (/AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH2/i.test(str)) {
  945. this._supportedAuth.push('XOAUTH2');
  946. }
  947. // Detect if the server supports SIZE extensions (and the max allowed size)
  948. if ((match = str.match(/[ -]SIZE(?:[ \t]+(\d+))?/im))) {
  949. this._supportedExtensions.push('SIZE');
  950. this._maxAllowedSize = Number(match[1]) || 0;
  951. }
  952. this.emit('connect');
  953. }
  954. /**
  955. * Handles server response for HELO command. If it yielded in
  956. * error, emit 'error', otherwise move into the authentication phase.
  957. *
  958. * @param {String} str Message from the server
  959. */
  960. _actionHELO(str) {
  961. if (str.charAt(0) !== '2') {
  962. this._onError(new Error('Invalid response for EHLO/HELO:\n' + str), 'EPROTOCOL', str, 'HELO');
  963. return;
  964. }
  965. this.emit('connect');
  966. }
  967. /**
  968. * Handles server response for STARTTLS command. If there's an error
  969. * try HELO instead, otherwise initiate TLS upgrade. If the upgrade
  970. * succeedes restart the EHLO
  971. *
  972. * @param {String} str Message from the server
  973. */
  974. _actionSTARTTLS(str) {
  975. if (str.charAt(0) !== '2') {
  976. if (this.options.opportunisticTLS) {
  977. this.logger.info(
  978. {
  979. tnx: 'smtp'
  980. },
  981. 'Failed STARTTLS upgrade, continuing unencrypted'
  982. );
  983. return this.emit('connect');
  984. }
  985. this._onError(new Error('Error upgrading connection with STARTTLS'), 'ETLS', str, 'STARTTLS');
  986. return;
  987. }
  988. this._upgradeConnection((err, secured) => {
  989. if (err) {
  990. this._onError(new Error('Error initiating TLS - ' + (err.message || err)), 'ETLS', false, 'STARTTLS');
  991. return;
  992. }
  993. this.logger.info(
  994. {
  995. tnx: 'smtp'
  996. },
  997. 'Connection upgraded with STARTTLS'
  998. );
  999. if (secured) {
  1000. // restart session
  1001. if (this.options.lmtp) {
  1002. this._responseActions.push(this._actionLHLO);
  1003. this._sendCommand('LHLO ' + this.name);
  1004. } else {
  1005. this._responseActions.push(this._actionEHLO);
  1006. this._sendCommand('EHLO ' + this.name);
  1007. }
  1008. } else {
  1009. this.emit('connect');
  1010. }
  1011. });
  1012. }
  1013. /**
  1014. * Handle the response for AUTH LOGIN command. We are expecting
  1015. * '334 VXNlcm5hbWU6' (base64 for 'Username:'). Data to be sent as
  1016. * response needs to be base64 encoded username. We do not need
  1017. * exact match but settle with 334 response in general as some
  1018. * hosts invalidly use a longer message than VXNlcm5hbWU6
  1019. *
  1020. * @param {String} str Message from the server
  1021. */
  1022. _actionAUTH_LOGIN_USER(str, callback) {
  1023. if (!/^334[ -]/.test(str)) {
  1024. // expecting '334 VXNlcm5hbWU6'
  1025. callback(this._formatError('Invalid login sequence while waiting for "334 VXNlcm5hbWU6"', 'EAUTH', str, 'AUTH LOGIN'));
  1026. return;
  1027. }
  1028. this._responseActions.push(str => {
  1029. this._actionAUTH_LOGIN_PASS(str, callback);
  1030. });
  1031. this._sendCommand(Buffer.from(this._auth.credentials.user + '', 'utf-8').toString('base64'));
  1032. }
  1033. /**
  1034. * Handle the response for AUTH CRAM-MD5 command. We are expecting
  1035. * '334 <challenge string>'. Data to be sent as response needs to be
  1036. * base64 decoded challenge string, MD5 hashed using the password as
  1037. * a HMAC key, prefixed by the username and a space, and finally all
  1038. * base64 encoded again.
  1039. *
  1040. * @param {String} str Message from the server
  1041. */
  1042. _actionAUTH_CRAM_MD5(str, callback) {
  1043. let challengeMatch = str.match(/^334\s+(.+)$/);
  1044. let challengeString = '';
  1045. if (!challengeMatch) {
  1046. return callback(this._formatError('Invalid login sequence while waiting for server challenge string', 'EAUTH', str, 'AUTH CRAM-MD5'));
  1047. } else {
  1048. challengeString = challengeMatch[1];
  1049. }
  1050. // Decode from base64
  1051. let base64decoded = Buffer.from(challengeString, 'base64').toString('ascii'),
  1052. hmac_md5 = crypto.createHmac('md5', this._auth.credentials.pass);
  1053. hmac_md5.update(base64decoded);
  1054. let hex_hmac = hmac_md5.digest('hex');
  1055. let prepended = this._auth.credentials.user + ' ' + hex_hmac;
  1056. this._responseActions.push(str => {
  1057. this._actionAUTH_CRAM_MD5_PASS(str, callback);
  1058. });
  1059. this._sendCommand(Buffer.from(prepended).toString('base64'));
  1060. }
  1061. /**
  1062. * Handles the response to CRAM-MD5 authentication, if there's no error,
  1063. * the user can be considered logged in. Start waiting for a message to send
  1064. *
  1065. * @param {String} str Message from the server
  1066. */
  1067. _actionAUTH_CRAM_MD5_PASS(str, callback) {
  1068. if (!str.match(/^235\s+/)) {
  1069. return callback(this._formatError('Invalid login sequence while waiting for "235"', 'EAUTH', str, 'AUTH CRAM-MD5'));
  1070. }
  1071. this.logger.info(
  1072. {
  1073. tnx: 'smtp',
  1074. username: this._auth.user,
  1075. action: 'authenticated',
  1076. method: this._authMethod
  1077. },
  1078. 'User %s authenticated',
  1079. JSON.stringify(this._auth.user)
  1080. );
  1081. this.authenticated = true;
  1082. callback(null, true);
  1083. }
  1084. /**
  1085. * Handle the response for AUTH LOGIN command. We are expecting
  1086. * '334 UGFzc3dvcmQ6' (base64 for 'Password:'). Data to be sent as
  1087. * response needs to be base64 encoded password.
  1088. *
  1089. * @param {String} str Message from the server
  1090. */
  1091. _actionAUTH_LOGIN_PASS(str, callback) {
  1092. if (!/^334[ -]/.test(str)) {
  1093. // expecting '334 UGFzc3dvcmQ6'
  1094. return callback(this._formatError('Invalid login sequence while waiting for "334 UGFzc3dvcmQ6"', 'EAUTH', str, 'AUTH LOGIN'));
  1095. }
  1096. this._responseActions.push(str => {
  1097. this._actionAUTHComplete(str, callback);
  1098. });
  1099. this._sendCommand(Buffer.from(this._auth.credentials.pass + '', 'utf-8').toString('base64'));
  1100. }
  1101. /**
  1102. * Handles the response for authentication, if there's no error,
  1103. * the user can be considered logged in. Start waiting for a message to send
  1104. *
  1105. * @param {String} str Message from the server
  1106. */
  1107. _actionAUTHComplete(str, isRetry, callback) {
  1108. if (!callback && typeof isRetry === 'function') {
  1109. callback = isRetry;
  1110. isRetry = false;
  1111. }
  1112. if (str.substr(0, 3) === '334') {
  1113. this._responseActions.push(str => {
  1114. if (isRetry || this._authMethod !== 'XOAUTH2') {
  1115. this._actionAUTHComplete(str, true, callback);
  1116. } else {
  1117. // fetch a new OAuth2 access token
  1118. setImmediate(() => this._handleXOauth2Token(true, callback));
  1119. }
  1120. });
  1121. this._sendCommand('');
  1122. return;
  1123. }
  1124. if (str.charAt(0) !== '2') {
  1125. this.logger.info(
  1126. {
  1127. tnx: 'smtp',
  1128. username: this._auth.user,
  1129. action: 'authfail',
  1130. method: this._authMethod
  1131. },
  1132. 'User %s failed to authenticate',
  1133. JSON.stringify(this._auth.user)
  1134. );
  1135. return callback(this._formatError('Invalid login', 'EAUTH', str, 'AUTH ' + this._authMethod));
  1136. }
  1137. this.logger.info(
  1138. {
  1139. tnx: 'smtp',
  1140. username: this._auth.user,
  1141. action: 'authenticated',
  1142. method: this._authMethod
  1143. },
  1144. 'User %s authenticated',
  1145. JSON.stringify(this._auth.user)
  1146. );
  1147. this.authenticated = true;
  1148. callback(null, true);
  1149. }
  1150. /**
  1151. * Handle response for a MAIL FROM: command
  1152. *
  1153. * @param {String} str Message from the server
  1154. */
  1155. _actionMAIL(str, callback) {
  1156. let message, curRecipient;
  1157. if (Number(str.charAt(0)) !== 2) {
  1158. if (this._usingSmtpUtf8 && /^550 /.test(str) && /[\x80-\uFFFF]/.test(this._envelope.from)) {
  1159. message = 'Internationalized mailbox name not allowed';
  1160. } else {
  1161. message = 'Mail command failed';
  1162. }
  1163. return callback(this._formatError(message, 'EENVELOPE', str, 'MAIL FROM'));
  1164. }
  1165. if (!this._envelope.rcptQueue.length) {
  1166. return callback(this._formatError('Can\'t send mail - no recipients defined', 'EENVELOPE', false, 'API'));
  1167. } else {
  1168. this._recipientQueue = [];
  1169. if (this._supportedExtensions.includes('PIPELINING')) {
  1170. while (this._envelope.rcptQueue.length) {
  1171. curRecipient = this._envelope.rcptQueue.shift();
  1172. this._recipientQueue.push(curRecipient);
  1173. this._responseActions.push(str => {
  1174. this._actionRCPT(str, callback);
  1175. });
  1176. this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs());
  1177. }
  1178. } else {
  1179. curRecipient = this._envelope.rcptQueue.shift();
  1180. this._recipientQueue.push(curRecipient);
  1181. this._responseActions.push(str => {
  1182. this._actionRCPT(str, callback);
  1183. });
  1184. this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs());
  1185. }
  1186. }
  1187. }
  1188. /**
  1189. * Handle response for a RCPT TO: command
  1190. *
  1191. * @param {String} str Message from the server
  1192. */
  1193. _actionRCPT(str, callback) {
  1194. let message,
  1195. err,
  1196. curRecipient = this._recipientQueue.shift();
  1197. if (Number(str.charAt(0)) !== 2) {
  1198. // this is a soft error
  1199. if (this._usingSmtpUtf8 && /^553 /.test(str) && /[\x80-\uFFFF]/.test(curRecipient)) {
  1200. message = 'Internationalized mailbox name not allowed';
  1201. } else {
  1202. message = 'Recipient command failed';
  1203. }
  1204. this._envelope.rejected.push(curRecipient);
  1205. // store error for the failed recipient
  1206. err = this._formatError(message, 'EENVELOPE', str, 'RCPT TO');
  1207. err.recipient = curRecipient;
  1208. this._envelope.rejectedErrors.push(err);
  1209. } else {
  1210. this._envelope.accepted.push(curRecipient);
  1211. }
  1212. if (!this._envelope.rcptQueue.length && !this._recipientQueue.length) {
  1213. if (this._envelope.rejected.length < this._envelope.to.length) {
  1214. this._responseActions.push(str => {
  1215. this._actionDATA(str, callback);
  1216. });
  1217. this._sendCommand('DATA');
  1218. } else {
  1219. err = this._formatError('Can\'t send mail - all recipients were rejected', 'EENVELOPE', str, 'RCPT TO');
  1220. err.rejected = this._envelope.rejected;
  1221. err.rejectedErrors = this._envelope.rejectedErrors;
  1222. return callback(err);
  1223. }
  1224. } else if (this._envelope.rcptQueue.length) {
  1225. curRecipient = this._envelope.rcptQueue.shift();
  1226. this._recipientQueue.push(curRecipient);
  1227. this._responseActions.push(str => {
  1228. this._actionRCPT(str, callback);
  1229. });
  1230. this._sendCommand('RCPT TO:<' + curRecipient + '>' + this._getDsnRcptToArgs());
  1231. }
  1232. }
  1233. /**
  1234. * Handle response for a DATA command
  1235. *
  1236. * @param {String} str Message from the server
  1237. */
  1238. _actionDATA(str, callback) {
  1239. // response should be 354 but according to this issue https://github.com/eleith/emailjs/issues/24
  1240. // some servers might use 250 instead, so lets check for 2 or 3 as the first digit
  1241. if (!/^[23]/.test(str)) {
  1242. return callback(this._formatError('Data command failed', 'EENVELOPE', str, 'DATA'));
  1243. }
  1244. let response = {
  1245. accepted: this._envelope.accepted,
  1246. rejected: this._envelope.rejected
  1247. };
  1248. if (this._envelope.rejectedErrors.length) {
  1249. response.rejectedErrors = this._envelope.rejectedErrors;
  1250. }
  1251. callback(null, response);
  1252. }
  1253. /**
  1254. * Handle response for a DATA stream when using SMTP
  1255. * We expect a single response that defines if the sending succeeded or failed
  1256. *
  1257. * @param {String} str Message from the server
  1258. */
  1259. _actionSMTPStream(str, callback) {
  1260. if (Number(str.charAt(0)) !== 2) {
  1261. // Message failed
  1262. return callback(this._formatError('Message failed', 'EMESSAGE', str, 'DATA'));
  1263. } else {
  1264. // Message sent succesfully
  1265. return callback(null, str);
  1266. }
  1267. }
  1268. /**
  1269. * Handle response for a DATA stream
  1270. * We expect a separate response for every recipient. All recipients can either
  1271. * succeed or fail separately
  1272. *
  1273. * @param {String} recipient The recipient this response applies to
  1274. * @param {Boolean} final Is this the final recipient?
  1275. * @param {String} str Message from the server
  1276. */
  1277. _actionLMTPStream(recipient, final, str, callback) {
  1278. let err;
  1279. if (Number(str.charAt(0)) !== 2) {
  1280. // Message failed
  1281. err = this._formatError('Message failed for recipient ' + recipient, 'EMESSAGE', str, 'DATA');
  1282. err.recipient = recipient;
  1283. this._envelope.rejected.push(recipient);
  1284. this._envelope.rejectedErrors.push(err);
  1285. for (let i = 0, len = this._envelope.accepted.length; i < len; i++) {
  1286. if (this._envelope.accepted[i] === recipient) {
  1287. this._envelope.accepted.splice(i, 1);
  1288. }
  1289. }
  1290. }
  1291. if (final) {
  1292. return callback(null, str);
  1293. }
  1294. }
  1295. _handleXOauth2Token(isRetry, callback) {
  1296. this._auth.oauth2.getToken(isRetry, (err, accessToken) => {
  1297. if (err) {
  1298. this.logger.info(
  1299. {
  1300. tnx: 'smtp',
  1301. username: this._auth.user,
  1302. action: 'authfail',
  1303. method: this._authMethod
  1304. },
  1305. 'User %s failed to authenticate',
  1306. JSON.stringify(this._auth.user)
  1307. );
  1308. return callback(this._formatError(err, 'EAUTH', false, 'AUTH XOAUTH2'));
  1309. }
  1310. this._responseActions.push(str => {
  1311. this._actionAUTHComplete(str, isRetry, callback);
  1312. });
  1313. this._sendCommand('AUTH XOAUTH2 ' + this._auth.oauth2.buildXOAuth2Token(accessToken));
  1314. });
  1315. }
  1316. _getHostname() {
  1317. // defaul hostname is machine hostname or [IP]
  1318. let defaultHostname = os.hostname() || '';
  1319. // ignore if not FQDN
  1320. if (defaultHostname.indexOf('.') < 0) {
  1321. defaultHostname = '[127.0.0.1]';
  1322. }
  1323. // IP should be enclosed in []
  1324. if (defaultHostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
  1325. defaultHostname = '[' + defaultHostname + ']';
  1326. }
  1327. return defaultHostname;
  1328. }
  1329. }
  1330. module.exports = SMTPConnection;