all files / src/ webserver.js

10.87% Statements 10/92
1.79% Branches 1/56
0% Functions 0/19
10.87% Lines 10/92
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                                                                                                                                                                                                                                                                                                                                                                                                       
 
'use strict';
 
var path = require('path'),
	fs = require('fs'),
	nconf = require('nconf'),
	express = require('express'),
	app = express(),
	server,
	winston = require('winston'),
	async = require('async'),
 
	emailer = require('./emailer'),
	meta = require('./meta'),
	logger = require('./logger'),
	plugins = require('./plugins'),
	middleware = require('./middleware'),
	routes = require('./routes'),
	emitter = require('./emitter'),
 
	helpers = require('../public/src/modules/helpers');
 
Iif (nconf.get('ssl')) {
	server = require('https').createServer({
		key: fs.readFileSync(nconf.get('ssl').key),
		cert: fs.readFileSync(nconf.get('ssl').cert)
	}, app);
} else {
	server = require('http').createServer(app);
}
 
module.exports.server = server;
 
server.on('error', function(err) {
	winston.error(err);
	if (err.code === 'EADDRINUSE') {
		winston.error('NodeBB address in use, exiting...');
		process.exit(0);
	} else {
		throw err;
	}
});
 
 
module.exports.listen = function() {
	emailer.registerApp(app);
 
	middleware = middleware(app);
 
	helpers.register();
 
	logger.init(app);
 
	emitter.all(['templates:compiled', 'meta:js.compiled', 'meta:css.compiled'], function() {
		winston.info('NodeBB Ready');
		emitter.emit('nodebb:ready');
		listen();
	});
 
	initializeNodeBB(function(err) {
		if (err) {
			winston.error(err);
			process.exit();
		}
		if (process.send) {
			process.send({
				action: 'ready'
			});
		}
	});
};
 
function initializeNodeBB(callback) {
	var skipJS, skipLess, fromFile = nconf.get('from-file') || '';
 
	if (fromFile.match('js')) {
		winston.info('[minifier] Minifying client-side JS skipped');
		skipJS = true;
	}
 
	async.waterfall([
		async.apply(cacheStaticFiles),
		async.apply(meta.themes.setupPaths),
		function(next) {
			plugins.init(app, middleware, next);
		},
		async.apply(meta.js.bridgeModules, app),
		function(next) {
			async.series([
				async.apply(meta.templates.compile),
				async.apply(!skipJS ? meta.js.minify : meta.js.getFromFile, 'nodebb.min.js'),
				async.apply(!skipJS ? meta.js.minify : meta.js.getFromFile, 'acp.min.js'),
				async.apply(meta.css.minify),
				async.apply(meta.sounds.init),
				async.apply(meta.blacklist.load)
			], next);
		},
		function(results, next) {
			plugins.fireHook('static:app.preload', {
				app: app,
				middleware: middleware
			}, next);
		},
		async.apply(plugins.fireHook, 'filter:hotswap.prepare', []),
		function(hotswapIds, next) {
			routes(app, middleware, hotswapIds);
			next();
		}
	], callback);
}
 
function cacheStaticFiles(callback) {
	if (global.env === 'development') {
		return callback();
	}
 
	app.enable('cache');
	app.enable('minification');
	callback();
}
 
function listen(callback) {
	var port = parseInt(nconf.get('port'), 10);
 
	if (Array.isArray(port)) {
		if (!port.length) {
			winston.error('[startup] empty ports array in config.json');
			process.exit();
		}
 
		winston.warn('[startup] If you want to start nodebb on multiple ports please use loader.js');
		winston.warn('[startup] Defaulting to first port in array, ' + port[0]);
		port = port[0];
		if (!port) {
			winston.error('[startup] Invalid port, exiting');
			process.exit();
		}
	}
 
	if ((port !== 80 && port !== 443) || nconf.get('trust_proxy') === true) {
		winston.info('Enabling \'trust proxy\'');
		app.enable('trust proxy');
	}
 
	if ((port === 80 || port === 443) && process.env.NODE_ENV !== 'development') {
		winston.info('Using ports 80 and 443 is not recommend; use a proxy instead. See README.md');
	}
 
	var isSocket = isNaN(port),
		args = isSocket ? [port] : [port, nconf.get('bind_address')],
		bind_address = ((nconf.get('bind_address') === "0.0.0.0" || !nconf.get('bind_address')) ? '0.0.0.0' : nconf.get('bind_address')) + ':' + port,
		oldUmask;
 
	args.push(function(err) {
		if (err) {
			winston.info('[startup] NodeBB was unable to listen on: ' + bind_address);
			process.exit();
		}
 
		winston.info('NodeBB is now listening on: ' + (isSocket ? port : bind_address));
		if (oldUmask) {
			process.umask(oldUmask);
		}
	});
 
	// Alter umask if necessary
	if (isSocket) {
		oldUmask = process.umask('0000');
		module.exports.testSocket(port, function(err) {
			if (!err) {
				server.listen.apply(server, args);
			} else {
				winston.error('[startup] NodeBB was unable to secure domain socket access (' + port + ')');
				winston.error('[startup] ' + err.message);
				process.exit();
			}
		});
	} else {
		server.listen.apply(server, args);
	}
}
 
module.exports.testSocket = function(socketPath, callback) {
	if (typeof socketPath !== 'string') {
		return callback(new Error('invalid socket path : ' + socketPath));
	}
	var net = require('net');
	var file = require('./file');
	async.series([
		function(next) {
			file.exists(socketPath, function(exists) {
				if (exists) {
					next();
				} else {
					callback();
				}
			});
		},
		function(next) {
			var testSocket = new net.Socket();
			testSocket.on('error', function(err) {
				next(err.code !== 'ECONNREFUSED' ? err : null);
			});
			testSocket.connect({ path: socketPath }, function() {
				// Something's listening here, abort
				callback(new Error('port-in-use'));
			});
		},
		async.apply(fs.unlink, socketPath),	// The socket was stale, kick it out of the way
	], callback);
};