From c0e7d6d8263ba0031f3dd86fc1b47359a204a3ca Mon Sep 17 00:00:00 2001 From: Stefan Machmeier Date: Thu, 1 Mar 2018 17:22:39 +0100 Subject: [PATCH] Mqtt proxy configuration for websocket connection, #1651. --- nodes/core/io/10-mqtt.js | 21 ++++++++++++++++++++- package.json | 1 + 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/nodes/core/io/10-mqtt.js b/nodes/core/io/10-mqtt.js index d7cc027d3..233bef1b6 100644 --- a/nodes/core/io/10-mqtt.js +++ b/nodes/core/io/10-mqtt.js @@ -19,6 +19,8 @@ module.exports = function(RED) { var mqtt = require("mqtt"); var util = require("util"); var isUtf8 = require('is-utf8'); + var HttpsProxyAgent = require('https-proxy-agent'); + var url = require('url'); function matchTopic(ts,t) { if (ts == "#") { @@ -109,12 +111,29 @@ module.exports = function(RED) { if (typeof this.cleansession === 'undefined') { this.cleansession = true; } + var prox; + if (process.env.http_proxy != null) { prox = process.env.http_proxy; } + if (process.env.HTTP_PROXY != null) { prox = process.env.HTTP_PROXY; } // Create the URL to pass in to the MQTT.js library if (this.brokerurl === "") { // if the broker may be ws:// or wss:// or even tcp:// if (this.broker.indexOf("://") > -1) { this.brokerurl = this.broker; + // Only for ws or wss, check if proxy env var for additional configuration + if (this.brokerurl.indexOf("wss://") > -1 || this.brokerurl.indexOf("ws://") > -1 ) + // check if proxy is set in env + if (prox) { + var parsedUrl = url.parse(this.brokerurl); + var proxyOpts = url.parse(prox); + // true for wss + proxyOpts.secureEndpoint = parsedUrl.protocol ? parsedUrl.protocol === 'wss:' : true; + // Set Agent for wsOption in MQTT + var agent = new HttpsProxyAgent(proxyOpts); + this.options.wsOptions = { + agent: agent + } + } } else { // construct the std mqtt:// url if (this.usetls) { @@ -448,4 +467,4 @@ module.exports = function(RED) { } } RED.nodes.registerType("mqtt out",MQTTOutNode); -}; +}; \ No newline at end of file diff --git a/package.json b/package.json index 870806d5b..0dcd300e2 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "fs-extra": "5.0.0", "fs.notify": "0.0.4", "hash-sum": "1.0.2", + "https-proxy-agent": "2.2.1", "i18next": "11.6.0", "is-utf8": "0.2.1", "js-yaml": "3.12.0",