tls.js 1.4 KB

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