From 3aa10850083013e3059ffd8fbd8582a5ba436059 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Tue, 16 May 2017 02:20:02 -0500 Subject: [PATCH] can haz wss --- lib/modules/http.js | 60 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/lib/modules/http.js b/lib/modules/http.js index 8ace19d..11258f1 100644 --- a/lib/modules/http.js +++ b/lib/modules/http.js @@ -5,6 +5,7 @@ module.exports.create = function (deps, conf, greenlockMiddleware) { var app = express(); var adminApp = require('./admin').create(deps, conf); var domainMatches = require('../match-domain').match; + var proxyRoutes = []; var adminDomains = [ /\blocalhost\.admin\./ @@ -112,16 +113,30 @@ module.exports.create = function (deps, conf, greenlockMiddleware) { res.end(require('../proxy-err-resp').getRespBody(err, conf.debug)); }); - return function (req, res, next) { - var hostname = req.headers.host.split(':')[0]; - var relevant = mod.domains.some(function (pattern) { - return domainMatches(pattern, hostname); - }); + return { + web: function (req, res, next) { + var hostname = req.headers.host.split(':')[0]; + var relevant = mod.domains.some(function (pattern) { + return domainMatches(pattern, hostname); + }); - if (relevant) { - proxy.web(req, res); - } else { - next(); + if (relevant) { + proxy.web(req, res); + } else { + next(); + } + } + , ws: function (req, socket, head, next) { + var hostname = req.headers.host.split(':')[0]; + var relevant = mod.domains.some(function (pattern) { + return domainMatches(pattern, hostname); + }); + + if (relevant) { + proxy.ws(req, socket, head); + } else { + next(); + } } }; } @@ -164,7 +179,9 @@ module.exports.create = function (deps, conf, greenlockMiddleware) { (conf.http.modules || []).forEach(function (mod) { if (mod.name === 'proxy') { - app.use(createProxyRoute(mod)); + var proxyRoute = createProxyRoute(mod); + proxyRoutes.push(proxyRoute); + app.use(proxyRoute.web); } else if (mod.name === 'static') { app.use(createStaticRoute(mod)); @@ -175,5 +192,26 @@ module.exports.create = function (deps, conf, greenlockMiddleware) { }); app.use(respond404); - return require('http').createServer(app); + + var server = require('http').createServer(function (req, res) { + app(req, res) + }); + + server.on('upgrade', function (req, socket, head) { + if (!proxyRoutes.length) { + socket.end(); + } + + function proxyWs() { + var proxyRoute = proxyRoutes.shift(); + if (!proxyRoute) { + socket.end(); + } + proxyRoute.ws(req, socket, head, proxyWs); + } + + proxyWs(); + }); + + return server; };