polling.js 10.0 KB

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