Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

polling.js 8.1KB

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