greenlock-cli.js/lib/servers.js

106 lines
2.9 KiB
JavaScript
Raw Normal View History

2016-08-10 02:39:39 +00:00
'use strict';
var NOBJ = {};
module.exports.create = function (challenge) {
var servers = {
_servers: []
, httpResponder: function (req, res) {
console.log('[LE-CLI] httpResponder');
var acmeChallengePrefix = '/.well-known/acme-challenge/';
if (0 !== req.url.indexOf(acmeChallengePrefix)) {
res.end("Let's Encrypt! Command line tool");
return;
}
var token = req.url.slice(acmeChallengePrefix.length);
challenge.get(NOBJ, req.headers.host.replace(/:.*/, ''), token, function (err, val) {
res.end(val || '_ ERROR challenge not found _');
});
}
, startServers: function (plainPorts, tlsPorts, opts) {
opts = opts || {};
2018-05-13 04:55:05 +00:00
var tlsOptions = opts.tlsOptions;
2016-08-10 02:39:39 +00:00
var https = require('https');
var http = require('http');
if (servers._servers.length) {
return;
}
// http-01-port
plainPorts.forEach(function (port) {
var server = http.createServer(servers.httpResponder);
servers._servers.push(server);
server.listen(port, function () {
if (opts.debug) {
console.info('Listening http on', this.address());
}
});
server.on('error', function (err) {
if ('EADDRINUSE' === err.code) {
console.error("");
console.error("You already have a different server running on port '" + port + "'.");
console.error("You should probably use the --webroot-path option instead of --standalone.");
return;
}
throw err;
});
});
// tls-sni-01-port
tlsPorts.forEach(function (port) {
2018-05-13 04:55:05 +00:00
var server = https.createServer(tlsOptions, servers.httpResponder);
2016-08-10 02:39:39 +00:00
servers._servers.push(server);
2016-08-10 14:23:12 +00:00
server.listen(port, function () {
2016-08-10 02:39:39 +00:00
if (opts.debug) {
console.info('Listening https on', this.address());
}
});
2016-08-10 14:23:12 +00:00
server.on('error', function (err) {
2016-08-10 02:39:39 +00:00
if ('EADDRINUSE' === err.code) {
console.error("");
console.error("You already have a different server running on port '" + port + "'.");
console.error("You should probably use the --webroot-path option instead of --standalone.");
return;
}
throw err;
});
});
}
, closeServers: function (opts) {
opts = opts || {};
return new Promise(function (done) {
var closedServers = 0;
var serversToClose = servers._servers.length;
if (0 === serversToClose) {
done();
}
servers._servers.forEach(function (server) {
server.close(function () {
if (serversToClose === ++closedServers) {
if (opts.debug) {
console.info('Closed all servers');
}
servers._servers = [];
done();
}
});
});
2016-08-10 02:39:39 +00:00
});
}
};
return servers;
};