server.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. #!/usr/bin/env node
  2. var querystring = require("querystring");
  3. var response = require("./response");
  4. var toobusy = require("toobusy-js");
  5. var logging = require("./logging");
  6. var config = require("../config");
  7. var http = require("http");
  8. var mime = require("mime");
  9. var path = require("path");
  10. var url = require("url");
  11. var fs = require("fs");
  12. var server = null;
  13. var routes = {
  14. index: require("./routes/index"),
  15. avatars: require("./routes/avatars"),
  16. skins: require("./routes/skins"),
  17. renders: require("./routes/renders"),
  18. capes: require("./routes/capes")
  19. };
  20. // serves assets from lib/public
  21. function asset_request(req, callback) {
  22. var filename = path.join(__dirname, "public", req.url.path_list.join("/"));
  23. fs.access(filename, function(fs_err) {
  24. if (!fs_err) {
  25. fs.readFile(filename, function(err, data) {
  26. callback({
  27. body: data,
  28. type: mime.lookup(filename),
  29. err: err
  30. });
  31. });
  32. } else {
  33. callback({});
  34. }
  35. });
  36. }
  37. // generates a 12 character random string
  38. function request_id() {
  39. return Math.random().toString(36).substring(2, 14);
  40. }
  41. // splits a URL path into an Array
  42. // the path is resolved and decoded
  43. function path_list(pathname) {
  44. // remove double and trailing slashes
  45. pathname = pathname.replace(/\/\/+/g, "/").replace(/(.)\/$/, "$1");
  46. var list = pathname.split("/");
  47. list.shift();
  48. for (var i = 0; i < list.length; i++) {
  49. // URL decode
  50. list[i] = querystring.unescape(list[i]);
  51. }
  52. return list;
  53. }
  54. // handles the +req+ by routing to the request to the appropriate module
  55. function requestHandler(req, res) {
  56. req.url = url.parse(req.url, true);
  57. req.url.query = req.url.query || {};
  58. req.url.path_list = path_list(req.url.pathname);
  59. req.id = request_id();
  60. req.start = Date.now();
  61. var local_path = req.url.path_list[0];
  62. logging.debug(req.id, req.method, req.url.href);
  63. toobusy.maxLag(200);
  64. if (toobusy() && !process.env.TRAVIS) {
  65. res.writeHead(503, {
  66. "Content-Type": "text/plain"
  67. });
  68. res.end("Server is over capacity :/");
  69. logging.error("Too busy:", req.id, 503, Date.now() - req.start + "ms", "(error)");
  70. return;
  71. }
  72. if (req.method === "GET" || req.method === "HEAD") {
  73. try {
  74. switch (local_path) {
  75. case "":
  76. routes.index(req, function(result) {
  77. response(req, res, result);
  78. });
  79. break;
  80. case "avatars":
  81. routes.avatars(req, function(result) {
  82. response(req, res, result);
  83. });
  84. break;
  85. case "skins":
  86. routes.skins(req, function(result) {
  87. response(req, res, result);
  88. });
  89. break;
  90. case "renders":
  91. routes.renders(req, function(result) {
  92. response(req, res, result);
  93. });
  94. break;
  95. case "capes":
  96. routes.capes(req, function(result) {
  97. response(req, res, result);
  98. });
  99. break;
  100. default:
  101. asset_request(req, function(result) {
  102. response(req, res, result);
  103. });
  104. }
  105. } catch(e) {
  106. var error = JSON.stringify(req.headers) + "\n" + e.stack;
  107. logging.error(req.id + "Error:", error);
  108. res.writeHead(500, {
  109. "Content-Type": "text/plain"
  110. });
  111. res.end(config.server.debug_enabled ? error : "Internal Server Error");
  112. }
  113. } else {
  114. res.writeHead(405, {
  115. "Content-Type": "text/plain"
  116. });
  117. res.end("Method Not Allowed");
  118. }
  119. }
  120. var exp = {};
  121. exp.boot = function(callback) {
  122. var port = process.env.PORT || 3000;
  123. var bind_ip = process.env.BIND || "0.0.0.0";
  124. server = http.createServer(requestHandler).listen(port, bind_ip, function() {
  125. logging.log("Server running on http://" + bind_ip + ":" + port + "/");
  126. if (callback) {
  127. callback();
  128. }
  129. });
  130. // stop accepting new connections,
  131. // wait for established connections to finish (30s max),
  132. // then exit
  133. process.on("SIGTERM", function() {
  134. logging.warn("Got SIGTERM, no longer accepting connections!");
  135. setTimeout(function() {
  136. logging.error("Dropping connections after 30s. Force quit.");
  137. process.exit(1);
  138. }, 30000);
  139. server.close(function() {
  140. logging.log("All connections closed, shutting down.");
  141. process.exit();
  142. });
  143. });
  144. };
  145. exp.close = function(callback) {
  146. server.close(callback);
  147. };
  148. module.exports = exp;
  149. if (require.main === module) {
  150. logging.error("Please use 'npm start' or 'www.js'");
  151. process.exit(1);
  152. }