index.js 58 KB

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