Reload the TLS certificate and private key if they change.

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@3409 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
Cory McWilliams 2017-10-12 23:29:33 +00:00
parent 3b27db2655
commit 37a9d856af

View File

@ -445,7 +445,7 @@ function handleConnection(client) {
var kBacklog = 8; var kBacklog = 8;
var kHost = "0.0.0.0" var kHost = "0.0.0.0"
var kHttpPort = gGlobalSettings.httpPort || 12345; var kHttpPort = gGlobalSettings.httpPort || 12345;
var kHttpsPort = gGlobalSettings.httpsPort || 12346; var kHttpsPort = gGlobalSettings.httpsPort || null;
var socket = new Socket(); var socket = new Socket();
socket.bind(kHost, kHttpPort).then(function() { socket.bind(kHost, kHttpPort).then(function() {
@ -458,27 +458,46 @@ socket.bind(kHost, kHttpPort).then(function() {
logError("[" + new Date() + "] " + error); logError("[" + new Date() + "] " + error);
}); });
var privateKey = new TextDecoder("ASCII").decode(File.readFile("data/httpd/privatekey.pem")); if (kHttpsPort) {
var certificate = new TextDecoder("ASCII").decode(File.readFile("data/httpd/certificate.pem")); var tls = {};
if (privateKey && certificate) {
var tls = new TlsContext();
tls.setPrivateKey(privateKey);
tls.setCertificate(certificate);
var secureSocket = new Socket(); var secureSocket = new Socket();
secureSocket.bind(kHost, kHttpsPort).then(function() { secureSocket.bind(kHost, kHttpsPort).then(function() {
secureSocket.listen(kBacklog, function() { return secureSocket.listen(kBacklog, function() {
secureSocket.accept().then(function(client) { return secureSocket.accept().then(function(client) {
handleConnection(client); handleConnection(client);
client.startTls(tls).catch(function(error) {
const kCertificatePath = "data/httpd/certificate.pem";
const kPrivateKeyPath = "data/httpd/privatekey.pem";
return Promise.all([
File.stat(kCertificatePath),
File.stat(kPrivateKeyPath),
]).then(function(stat) {
if (!tls.context ||
tls.certStat.mtime != stat[0].mtime ||
tls.certStat.size != stat[0].size ||
tls.keyStat.mtime != stat[1].mtime ||
tls.keyStat.size != stat[1].size) {
print("Reloading " + kCertificatePath + " and " + kPrivateKeyPath);
var privateKey = new TextDecoder("ASCII").decode(File.readFile(kPrivateKeyPath));
var certificate = new TextDecoder("ASCII").decode(File.readFile(kCertificatePath));
tls.context = new TlsContext();
tls.context.setPrivateKey(privateKey);
tls.context.setCertificate(certificate);
tls.certStat = stat[0];
tls.keyStat = stat[1];
}
return client.startTls(tls.context);
}).catch(function(error) {
logError("[" + new Date() + "] [" + client.peerName + "] " + error); logError("[" + new Date() + "] [" + client.peerName + "] " + error);
}); });
});
});
}).catch(function(error) { }).catch(function(error) {
logError("[" + new Date() + "] " + error); logError("[" + new Date() + "] " + error);
}); });
});
});
} }
exports.all = all; exports.all = all;