changeset 203:5491ca3a335b

Fail cleanly if necessary files can't be opened.
author John "Elwin" Edwards
date Wed, 04 Jan 2017 21:25:43 -0500
parents 7f25bb89b59c
children a200b313870d
files rlgwebd
diffstat 1 files changed, 28 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/rlgwebd	Wed Jan 04 20:28:29 2017 -0500
+++ b/rlgwebd	Wed Jan 04 21:25:43 2017 -0500
@@ -25,7 +25,8 @@
 
 /* Read configuration from a file */
 var config_file = "/etc/rlgwebd.conf";
-var config_lines = fs.readFileSync(config_file).toString().split('\n');
+var config_lines = read_or_die(config_file, "Configuration file").toString().split('\n');
+
 for (var i = 0; i < config_lines.length; i++) {
   if (config_lines[i].length > 0 && config_lines[i][0] != '#') {
     var config_fields = config_lines[i].split('=');
@@ -578,6 +579,25 @@
   console.log.apply(console, arguments);
 }
 
+// Read a file synchronously, exiting if anything goes wrong.
+// Intended only for files required at startup.
+function read_or_die(filename, description) {
+  var contents;
+  try {
+    contents = fs.readFileSync(filename);
+  }
+  catch (err) {
+    if (err.code == "ENOENT") {
+      tslog("%s %s does not exist", description, filename);
+    }
+    else {
+      console.log(err.stack);
+    }
+    process.exit(1);
+  }
+  return contents;
+}
+
 /* Returns a list of the cookies in the request, obviously. */
 function getCookies(req) {
   cookies = [];
@@ -1237,9 +1257,11 @@
 
 var tls_options = {};
 if (rlgwebd_options.use_https) {
-  tls_options.key = fs.readFileSync(rlgwebd_options.keyfile),
-  tls_options.cert = fs.readFileSync(rlgwebd_options.certfile),
-  tls_options.ca = fs.readFileSync(rlgwebd_options.cafile)
+  /* If the cert can't be found, don't fall back to insecure HTTP. */
+  tls_options.key = read_or_die(rlgwebd_options.keyfile, "Keyfile");
+  tls_options.cert = read_or_die(rlgwebd_options.certfile, "Certfile");
+  if ("cafile" in rlgwebd_options)
+    tls_options.ca = read_or_die(rlgwebd_options.cafile, "CA file");
 };
 
 /* Open the control socket before chrooting where it can't be found */
@@ -1273,10 +1295,10 @@
   wsServer.on("request", wsHandler);
   tslog('WebSockets are online'); 
   if (rlgwebd_options.use_https) {
-  var httpsServer = https.createServer(tls_options, webHandler);
+    var httpsServer = https.createServer(tls_options, webHandler);
     httpsServer.listen(rlgwebd_options.https_port);
     tslog('TLS running on port %d', rlgwebd_options.https_port); 
-    wssServer = new WebSocketServer({"httpServer": httpsServer});
+    var wssServer = new WebSocketServer({"httpServer": httpsServer});
     wssServer.on("request", wsHandler);
     tslog('Secure WebSockets are online'); 
   }