tls.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict'
  2. var tls = require('tls')
  3. function buildBuilder (mqttClient, opts) {
  4. var connection
  5. opts.port = opts.port || 8883
  6. opts.host = opts.hostname || opts.host || 'localhost'
  7. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  8. delete opts.path
  9. connection = tls.connect(opts)
  10. /* eslint no-use-before-define: [2, "nofunc"] */
  11. connection.on('secureConnect', function () {
  12. if (opts.rejectUnauthorized && !connection.authorized) {
  13. connection.emit('error', new Error('TLS not authorized'))
  14. } else {
  15. connection.removeListener('error', handleTLSerrors)
  16. }
  17. })
  18. function handleTLSerrors (err) {
  19. // How can I get verify this error is a tls error?
  20. if (opts.rejectUnauthorized) {
  21. mqttClient.emit('error', err)
  22. }
  23. // close this connection to match the behaviour of net
  24. // otherwise all we get is an error from the connection
  25. // and close event doesn't fire. This is a work around
  26. // to enable the reconnect code to work the same as with
  27. // net.createConnection
  28. connection.end()
  29. }
  30. connection.on('error', handleTLSerrors)
  31. return connection
  32. }
  33. module.exports = buildBuilder