nginx.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. const _ = require('lodash');
  2. const fs = require('fs');
  3. const logger = require('../logger').nginx;
  4. const config = require('../lib/config');
  5. const utils = require('../lib/utils');
  6. const error = require('../lib/error');
  7. const internalNginx = {
  8. /**
  9. * This will:
  10. * - test the nginx config first to make sure it's OK
  11. * - create / recreate the config for the host
  12. * - test again
  13. * - IF OK: update the meta with online status
  14. * - IF BAD: update the meta with offline status and remove the config entirely
  15. * - then reload nginx
  16. *
  17. * @param {Object|String} model
  18. * @param {String} host_type
  19. * @param {Object} host
  20. * @returns {Promise}
  21. */
  22. configure: (model, host_type, host) => {
  23. let combined_meta = {};
  24. return internalNginx.test()
  25. .then(() => {
  26. // Nginx is OK
  27. // We're deleting this config regardless.
  28. // Don't throw errors, as the file may not exist at all
  29. // Delete the .err file too
  30. return internalNginx.deleteConfig(host_type, host, false, true);
  31. })
  32. .then(() => {
  33. return internalNginx.generateConfig(host_type, host);
  34. })
  35. .then(() => {
  36. // Test nginx again and update meta with result
  37. return internalNginx.test()
  38. .then(() => {
  39. // nginx is ok
  40. combined_meta = _.assign({}, host.meta, {
  41. nginx_online: true,
  42. nginx_err: null
  43. });
  44. return model
  45. .query()
  46. .where('id', host.id)
  47. .patch({
  48. meta: combined_meta
  49. });
  50. })
  51. .catch((err) => {
  52. // Remove the error_log line because it's a docker-ism false positive that doesn't need to be reported.
  53. // It will always look like this:
  54. // nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (6: No such device or address)
  55. let valid_lines = [];
  56. let err_lines = err.message.split('\n');
  57. err_lines.map(function (line) {
  58. if (line.indexOf('/var/log/nginx/error.log') === -1) {
  59. valid_lines.push(line);
  60. }
  61. });
  62. if (config.debug()) {
  63. logger.error('Nginx test failed:', valid_lines.join('\n'));
  64. }
  65. // config is bad, update meta and delete config
  66. combined_meta = _.assign({}, host.meta, {
  67. nginx_online: false,
  68. nginx_err: valid_lines.join('\n')
  69. });
  70. return model
  71. .query()
  72. .where('id', host.id)
  73. .patch({
  74. meta: combined_meta
  75. })
  76. .then(() => {
  77. internalNginx.renameConfigAsError(host_type, host);
  78. })
  79. .then(() => {
  80. return internalNginx.deleteConfig(host_type, host, true);
  81. });
  82. });
  83. })
  84. .then(() => {
  85. return internalNginx.reload();
  86. })
  87. .then(() => {
  88. return combined_meta;
  89. });
  90. },
  91. /**
  92. * @returns {Promise}
  93. */
  94. test: () => {
  95. if (config.debug()) {
  96. logger.info('Testing Nginx configuration');
  97. }
  98. return utils.exec('/usr/sbin/nginx -t -g "error_log off;"');
  99. },
  100. /**
  101. * @returns {Promise}
  102. */
  103. reload: () => {
  104. return internalNginx.test()
  105. .then(() => {
  106. logger.info('Reloading Nginx');
  107. return utils.exec('/usr/sbin/nginx -s reload');
  108. });
  109. },
  110. /**
  111. * @param {String} host_type
  112. * @param {Integer} host_id
  113. * @returns {String}
  114. */
  115. getConfigName: (host_type, host_id) => {
  116. if (host_type === 'default') {
  117. return '/data/nginx/default_host/site.conf';
  118. }
  119. return '/data/nginx/' + internalNginx.getFileFriendlyHostType(host_type) + '/' + host_id + '.conf';
  120. },
  121. /**
  122. * Generates custom locations
  123. * @param {Object} host
  124. * @returns {Promise}
  125. */
  126. renderLocations: (host) => {
  127. return new Promise((resolve, reject) => {
  128. let template;
  129. try {
  130. template = fs.readFileSync(__dirname + '/../templates/_location.conf', {encoding: 'utf8'});
  131. } catch (err) {
  132. reject(new error.ConfigurationError(err.message));
  133. return;
  134. }
  135. const renderEngine = utils.getRenderEngine();
  136. let renderedLocations = '';
  137. const locationRendering = async () => {
  138. for (let i = 0; i < host.locations.length; i++) {
  139. let locationCopy = Object.assign({}, {access_list_id: host.access_list_id}, {certificate_id: host.certificate_id},
  140. {ssl_forced: host.ssl_forced}, {caching_enabled: host.caching_enabled}, {block_exploits: host.block_exploits},
  141. {allow_websocket_upgrade: host.allow_websocket_upgrade}, {http2_support: host.http2_support},
  142. {hsts_enabled: host.hsts_enabled}, {hsts_subdomains: host.hsts_subdomains}, {access_list: host.access_list},
  143. {certificate: host.certificate}, host.locations[i]);
  144. if (locationCopy.forward_host.indexOf('/') > -1) {
  145. const splitted = locationCopy.forward_host.split('/');
  146. locationCopy.forward_host = splitted.shift();
  147. locationCopy.forward_path = `/${splitted.join('/')}`;
  148. }
  149. // eslint-disable-next-line
  150. renderedLocations += await renderEngine.parseAndRender(template, locationCopy);
  151. }
  152. };
  153. locationRendering().then(() => resolve(renderedLocations));
  154. });
  155. },
  156. /**
  157. * @param {String} host_type
  158. * @param {Object} host
  159. * @returns {Promise}
  160. */
  161. generateConfig: (host_type, host) => {
  162. const nice_host_type = internalNginx.getFileFriendlyHostType(host_type);
  163. if (config.debug()) {
  164. logger.info('Generating ' + nice_host_type + ' Config:', JSON.stringify(host, null, 2));
  165. }
  166. const renderEngine = utils.getRenderEngine();
  167. return new Promise((resolve, reject) => {
  168. let template = null;
  169. let filename = internalNginx.getConfigName(nice_host_type, host.id);
  170. try {
  171. template = fs.readFileSync(__dirname + '/../templates/' + nice_host_type + '.conf', {encoding: 'utf8'});
  172. } catch (err) {
  173. reject(new error.ConfigurationError(err.message));
  174. return;
  175. }
  176. let locationsPromise;
  177. let origLocations;
  178. // Manipulate the data a bit before sending it to the template
  179. if (nice_host_type !== 'default') {
  180. host.use_default_location = true;
  181. if (typeof host.advanced_config !== 'undefined' && host.advanced_config) {
  182. host.use_default_location = !internalNginx.advancedConfigHasDefaultLocation(host.advanced_config);
  183. }
  184. }
  185. if (host.locations) {
  186. //logger.info ('host.locations = ' + JSON.stringify(host.locations, null, 2));
  187. origLocations = [].concat(host.locations);
  188. locationsPromise = internalNginx.renderLocations(host).then((renderedLocations) => {
  189. host.locations = renderedLocations;
  190. });
  191. // Allow someone who is using / custom location path to use it, and skip the default / location
  192. _.map(host.locations, (location) => {
  193. if (location.path === '/') {
  194. host.use_default_location = false;
  195. }
  196. });
  197. } else {
  198. locationsPromise = Promise.resolve();
  199. }
  200. // Set the IPv6 setting for the host
  201. host.ipv6 = internalNginx.ipv6Enabled();
  202. locationsPromise.then(() => {
  203. renderEngine
  204. .parseAndRender(template, host)
  205. .then((config_text) => {
  206. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  207. if (config.debug()) {
  208. logger.success('Wrote config:', filename, config_text);
  209. }
  210. // Restore locations array
  211. host.locations = origLocations;
  212. resolve(true);
  213. })
  214. .catch((err) => {
  215. if (config.debug()) {
  216. logger.warn('Could not write ' + filename + ':', err.message);
  217. }
  218. reject(new error.ConfigurationError(err.message));
  219. });
  220. });
  221. });
  222. },
  223. /**
  224. * This generates a temporary nginx config listening on port 80 for the domain names listed
  225. * in the certificate setup. It allows the letsencrypt acme challenge to be requested by letsencrypt
  226. * when requesting a certificate without having a hostname set up already.
  227. *
  228. * @param {Object} certificate
  229. * @returns {Promise}
  230. */
  231. generateLetsEncryptRequestConfig: (certificate) => {
  232. if (config.debug()) {
  233. logger.info('Generating LetsEncrypt Request Config:', certificate);
  234. }
  235. const renderEngine = utils.getRenderEngine();
  236. return new Promise((resolve, reject) => {
  237. let template = null;
  238. let filename = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  239. try {
  240. template = fs.readFileSync(__dirname + '/../templates/letsencrypt-request.conf', {encoding: 'utf8'});
  241. } catch (err) {
  242. reject(new error.ConfigurationError(err.message));
  243. return;
  244. }
  245. certificate.ipv6 = internalNginx.ipv6Enabled();
  246. renderEngine
  247. .parseAndRender(template, certificate)
  248. .then((config_text) => {
  249. fs.writeFileSync(filename, config_text, {encoding: 'utf8'});
  250. if (config.debug()) {
  251. logger.success('Wrote config:', filename, config_text);
  252. }
  253. resolve(true);
  254. })
  255. .catch((err) => {
  256. if (config.debug()) {
  257. logger.warn('Could not write ' + filename + ':', err.message);
  258. }
  259. reject(new error.ConfigurationError(err.message));
  260. });
  261. });
  262. },
  263. /**
  264. * A simple wrapper around unlinkSync that writes to the logger
  265. *
  266. * @param {String} filename
  267. */
  268. deleteFile: (filename) => {
  269. logger.debug('Deleting file: ' + filename);
  270. try {
  271. fs.unlinkSync(filename);
  272. } catch (err) {
  273. logger.debug('Could not delete file:', JSON.stringify(err, null, 2));
  274. }
  275. },
  276. /**
  277. *
  278. * @param {String} host_type
  279. * @returns String
  280. */
  281. getFileFriendlyHostType: (host_type) => {
  282. return host_type.replace(new RegExp('-', 'g'), '_');
  283. },
  284. /**
  285. * This removes the temporary nginx config file generated by `generateLetsEncryptRequestConfig`
  286. *
  287. * @param {Object} certificate
  288. * @returns {Promise}
  289. */
  290. deleteLetsEncryptRequestConfig: (certificate) => {
  291. const config_file = '/data/nginx/temp/letsencrypt_' + certificate.id + '.conf';
  292. return new Promise((resolve/*, reject*/) => {
  293. internalNginx.deleteFile(config_file);
  294. resolve();
  295. });
  296. },
  297. /**
  298. * @param {String} host_type
  299. * @param {Object} [host]
  300. * @param {Boolean} [delete_err_file]
  301. * @returns {Promise}
  302. */
  303. deleteConfig: (host_type, host, delete_err_file) => {
  304. const config_file = internalNginx.getConfigName(internalNginx.getFileFriendlyHostType(host_type), typeof host === 'undefined' ? 0 : host.id);
  305. const config_file_err = config_file + '.err';
  306. return new Promise((resolve/*, reject*/) => {
  307. internalNginx.deleteFile(config_file);
  308. if (delete_err_file) {
  309. internalNginx.deleteFile(config_file_err);
  310. }
  311. resolve();
  312. });
  313. },
  314. /**
  315. * @param {String} host_type
  316. * @param {Object} [host]
  317. * @returns {Promise}
  318. */
  319. renameConfigAsError: (host_type, host) => {
  320. const config_file = internalNginx.getConfigName(internalNginx.getFileFriendlyHostType(host_type), typeof host === 'undefined' ? 0 : host.id);
  321. const config_file_err = config_file + '.err';
  322. return new Promise((resolve/*, reject*/) => {
  323. fs.unlink(config_file, () => {
  324. // ignore result, continue
  325. fs.rename(config_file, config_file_err, () => {
  326. // also ignore result, as this is a debugging informative file anyway
  327. resolve();
  328. });
  329. });
  330. });
  331. },
  332. /**
  333. * @param {String} host_type
  334. * @param {Array} hosts
  335. * @returns {Promise}
  336. */
  337. bulkGenerateConfigs: (host_type, hosts) => {
  338. let promises = [];
  339. hosts.map(function (host) {
  340. promises.push(internalNginx.generateConfig(host_type, host));
  341. });
  342. return Promise.all(promises);
  343. },
  344. /**
  345. * @param {String} host_type
  346. * @param {Array} hosts
  347. * @returns {Promise}
  348. */
  349. bulkDeleteConfigs: (host_type, hosts) => {
  350. let promises = [];
  351. hosts.map(function (host) {
  352. promises.push(internalNginx.deleteConfig(host_type, host, true));
  353. });
  354. return Promise.all(promises);
  355. },
  356. /**
  357. * @param {string} config
  358. * @returns {boolean}
  359. */
  360. advancedConfigHasDefaultLocation: function (cfg) {
  361. return !!cfg.match(/^(?:.*;)?\s*?location\s*?\/\s*?{/im);
  362. },
  363. /**
  364. * @returns {boolean}
  365. */
  366. ipv6Enabled: function () {
  367. if (typeof process.env.DISABLE_IPV6 !== 'undefined') {
  368. const disabled = process.env.DISABLE_IPV6.toLowerCase();
  369. return !(disabled === 'on' || disabled === 'true' || disabled === '1' || disabled === 'yes');
  370. }
  371. return true;
  372. }
  373. };
  374. module.exports = internalNginx;