nginx.js 11 KB

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