polling.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. const Transport = require("../transport");
  2. const parser = require("engine.io-parser");
  3. const zlib = require("zlib");
  4. const accepts = require("accepts");
  5. const debug = require("debug")("engine:polling");
  6. const compressionMethods = {
  7. gzip: zlib.createGzip,
  8. deflate: zlib.createDeflate
  9. };
  10. class Polling extends Transport {
  11. /**
  12. * HTTP polling constructor.
  13. *
  14. * @api public.
  15. */
  16. constructor(req) {
  17. super(req);
  18. this.closeTimeout = 30 * 1000;
  19. this.maxHttpBufferSize = null;
  20. this.httpCompression = null;
  21. }
  22. /**
  23. * Transport name
  24. *
  25. * @api public
  26. */
  27. get name() {
  28. return "polling";
  29. }
  30. /**
  31. * Overrides onRequest.
  32. *
  33. * @param {http.IncomingMessage}
  34. * @api private
  35. */
  36. onRequest(req) {
  37. const res = req.res;
  38. if ("GET" === req.method) {
  39. this.onPollRequest(req, res);
  40. } else if ("POST" === req.method) {
  41. this.onDataRequest(req, res);
  42. } else {
  43. res.writeHead(500);
  44. res.end();
  45. }
  46. }
  47. /**
  48. * The client sends a request awaiting for us to send data.
  49. *
  50. * @api private
  51. */
  52. onPollRequest(req, res) {
  53. if (this.req) {
  54. debug("request overlap");
  55. // assert: this.res, '.req and .res should be (un)set together'
  56. this.onError("overlap from client");
  57. res.writeHead(500);
  58. res.end();
  59. return;
  60. }
  61. debug("setting request");
  62. this.req = req;
  63. this.res = res;
  64. const self = this;
  65. function onClose() {
  66. self.onError("poll connection closed prematurely");
  67. }
  68. function cleanup() {
  69. req.removeListener("close", onClose);
  70. self.req = self.res = null;
  71. }
  72. req.cleanup = cleanup;
  73. req.on("close", onClose);
  74. this.writable = true;
  75. this.emit("drain");
  76. // if we're still writable but had a pending close, trigger an empty send
  77. if (this.writable && this.shouldClose) {
  78. debug("triggering empty send to append close packet");
  79. this.send([{ type: "noop" }]);
  80. }
  81. }
  82. /**
  83. * The client sends a request with data.
  84. *
  85. * @api private
  86. */
  87. onDataRequest(req, res) {
  88. if (this.dataReq) {
  89. // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
  90. this.onError("data request overlap from client");
  91. res.writeHead(500);
  92. res.end();
  93. return;
  94. }
  95. this.dataReq = req;
  96. this.dataRes = res;
  97. let chunks = "";
  98. const self = this;
  99. function cleanup() {
  100. req.removeListener("data", onData);
  101. req.removeListener("end", onEnd);
  102. req.removeListener("close", onClose);
  103. self.dataReq = self.dataRes = chunks = null;
  104. }
  105. function onClose() {
  106. cleanup();
  107. self.onError("data request connection closed prematurely");
  108. }
  109. function onData(data) {
  110. let contentLength;
  111. chunks += data;
  112. contentLength = Buffer.byteLength(chunks);
  113. if (contentLength > self.maxHttpBufferSize) {
  114. chunks = "";
  115. req.connection.destroy();
  116. }
  117. }
  118. function onEnd() {
  119. self.onData(chunks);
  120. const headers = {
  121. // text/html is required instead of text/plain to avoid an
  122. // unwanted download dialog on certain user-agents (GH-43)
  123. "Content-Type": "text/html",
  124. "Content-Length": 2
  125. };
  126. res.writeHead(200, self.headers(req, headers));
  127. res.end("ok");
  128. cleanup();
  129. }
  130. req.on("close", onClose);
  131. req.setEncoding("utf8");
  132. req.on("data", onData);
  133. req.on("end", onEnd);
  134. }
  135. /**
  136. * Processes the incoming data payload.
  137. *
  138. * @param {String} encoded payload
  139. * @api private
  140. */
  141. onData(data) {
  142. debug('received "%s"', data);
  143. const self = this;
  144. const callback = function(packet) {
  145. if ("close" === packet.type) {
  146. debug("got xhr close packet");
  147. self.onClose();
  148. return false;
  149. }
  150. self.onPacket(packet);
  151. };
  152. parser.decodePayload(data).forEach(callback);
  153. }
  154. /**
  155. * Overrides onClose.
  156. *
  157. * @api private
  158. */
  159. onClose() {
  160. if (this.writable) {
  161. // close pending poll request
  162. this.send([{ type: "noop" }]);
  163. }
  164. super.onClose();
  165. }
  166. /**
  167. * Writes a packet payload.
  168. *
  169. * @param {Object} packet
  170. * @api private
  171. */
  172. send(packets) {
  173. this.writable = false;
  174. if (this.shouldClose) {
  175. debug("appending close packet to payload");
  176. packets.push({ type: "close" });
  177. this.shouldClose();
  178. this.shouldClose = null;
  179. }
  180. const self = this;
  181. parser.encodePayload(packets, data => {
  182. const compress = packets.some(function(packet) {
  183. return packet.options && packet.options.compress;
  184. });
  185. self.write(data, { compress: compress });
  186. });
  187. }
  188. /**
  189. * Writes data as response to poll request.
  190. *
  191. * @param {String} data
  192. * @param {Object} options
  193. * @api private
  194. */
  195. write(data, options) {
  196. debug('writing "%s"', data);
  197. const self = this;
  198. this.doWrite(data, options, function() {
  199. self.req.cleanup();
  200. });
  201. }
  202. /**
  203. * Performs the write.
  204. *
  205. * @api private
  206. */
  207. doWrite(data, options, callback) {
  208. const self = this;
  209. // explicit UTF-8 is required for pages not served under utf
  210. const isString = typeof data === "string";
  211. const contentType = isString
  212. ? "text/plain; charset=UTF-8"
  213. : "application/octet-stream";
  214. const headers = {
  215. "Content-Type": contentType
  216. };
  217. if (!this.httpCompression || !options.compress) {
  218. respond(data);
  219. return;
  220. }
  221. const len = isString ? Buffer.byteLength(data) : data.length;
  222. if (len < this.httpCompression.threshold) {
  223. respond(data);
  224. return;
  225. }
  226. const encoding = accepts(this.req).encodings(["gzip", "deflate"]);
  227. if (!encoding) {
  228. respond(data);
  229. return;
  230. }
  231. this.compress(data, encoding, function(err, data) {
  232. if (err) {
  233. self.res.writeHead(500);
  234. self.res.end();
  235. callback(err);
  236. return;
  237. }
  238. headers["Content-Encoding"] = encoding;
  239. respond(data);
  240. });
  241. function respond(data) {
  242. headers["Content-Length"] =
  243. "string" === typeof data ? Buffer.byteLength(data) : data.length;
  244. self.res.writeHead(200, self.headers(self.req, headers));
  245. self.res.end(data);
  246. callback();
  247. }
  248. }
  249. /**
  250. * Compresses data.
  251. *
  252. * @api private
  253. */
  254. compress(data, encoding, callback) {
  255. debug("compressing");
  256. const buffers = [];
  257. let nread = 0;
  258. compressionMethods[encoding](this.httpCompression)
  259. .on("error", callback)
  260. .on("data", function(chunk) {
  261. buffers.push(chunk);
  262. nread += chunk.length;
  263. })
  264. .on("end", function() {
  265. callback(null, Buffer.concat(buffers, nread));
  266. })
  267. .end(data);
  268. }
  269. /**
  270. * Closes the transport.
  271. *
  272. * @api private
  273. */
  274. doClose(fn) {
  275. debug("closing");
  276. const self = this;
  277. let closeTimeoutTimer;
  278. if (this.dataReq) {
  279. debug("aborting ongoing data request");
  280. this.dataReq.destroy();
  281. }
  282. if (this.writable) {
  283. debug("transport writable - closing right away");
  284. this.send([{ type: "close" }]);
  285. onClose();
  286. } else if (this.discarded) {
  287. debug("transport discarded - closing right away");
  288. onClose();
  289. } else {
  290. debug("transport not writable - buffering orderly close");
  291. this.shouldClose = onClose;
  292. closeTimeoutTimer = setTimeout(onClose, this.closeTimeout);
  293. }
  294. function onClose() {
  295. clearTimeout(closeTimeoutTimer);
  296. fn();
  297. self.onClose();
  298. }
  299. }
  300. /**
  301. * Returns headers for a response.
  302. *
  303. * @param {http.IncomingMessage} request
  304. * @param {Object} extra headers
  305. * @api private
  306. */
  307. headers(req, headers) {
  308. headers = headers || {};
  309. // prevent XSS warnings on IE
  310. // https://github.com/LearnBoost/socket.io/pull/1333
  311. const ua = req.headers["user-agent"];
  312. if (ua && (~ua.indexOf(";MSIE") || ~ua.indexOf("Trident/"))) {
  313. headers["X-XSS-Protection"] = "0";
  314. }
  315. this.emit("headers", headers);
  316. return headers;
  317. }
  318. }
  319. module.exports = Polling;