polling.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /**
  2. * Module requirements.
  3. */
  4. var Transport = require('../transport')
  5. , parser = require('engine.io-parser')
  6. , zlib = require('zlib')
  7. , accepts = require('accepts')
  8. , debug = require('debug')('engine:polling');
  9. var compressionMethods = {
  10. gzip: zlib.createGzip,
  11. deflate: zlib.createDeflate
  12. };
  13. /**
  14. * Exports the constructor.
  15. */
  16. module.exports = Polling;
  17. /**
  18. * HTTP polling constructor.
  19. *
  20. * @api public.
  21. */
  22. function Polling (req) {
  23. Transport.call(this, req);
  24. this.closeTimeout = 30 * 1000;
  25. this.maxHttpBufferSize = null;
  26. this.httpCompression = null;
  27. }
  28. /**
  29. * Inherits from Transport.
  30. *
  31. * @api public.
  32. */
  33. Polling.prototype.__proto__ = Transport.prototype;
  34. /**
  35. * Transport name
  36. *
  37. * @api public
  38. */
  39. Polling.prototype.name = 'polling';
  40. /**
  41. * Overrides onRequest.
  42. *
  43. * @param {http.ServerRequest}
  44. * @api private
  45. */
  46. Polling.prototype.onRequest = function (req) {
  47. var res = req.res;
  48. if ('GET' == req.method) {
  49. this.onPollRequest(req, res);
  50. } else if ('POST' == req.method) {
  51. this.onDataRequest(req, res);
  52. } else {
  53. res.writeHead(500);
  54. res.end();
  55. }
  56. };
  57. /**
  58. * The client sends a request awaiting for us to send data.
  59. *
  60. * @api private
  61. */
  62. Polling.prototype.onPollRequest = function (req, res) {
  63. if (this.req) {
  64. debug('request overlap');
  65. // assert: this.res, '.req and .res should be (un)set together'
  66. this.onError('overlap from client');
  67. res.writeHead(500);
  68. res.end();
  69. return;
  70. }
  71. debug('setting request');
  72. this.req = req;
  73. this.res = res;
  74. var self = this;
  75. function onClose () {
  76. self.onError('poll connection closed prematurely');
  77. }
  78. function cleanup () {
  79. req.removeListener('close', onClose);
  80. self.req = self.res = null;
  81. }
  82. req.cleanup = cleanup;
  83. req.on('close', onClose);
  84. this.writable = true;
  85. this.emit('drain');
  86. // if we're still writable but had a pending close, trigger an empty send
  87. if (this.writable && this.shouldClose) {
  88. debug('triggering empty send to append close packet');
  89. this.send([{ type: 'noop' }]);
  90. }
  91. };
  92. /**
  93. * The client sends a request with data.
  94. *
  95. * @api private
  96. */
  97. Polling.prototype.onDataRequest = function (req, res) {
  98. if (this.dataReq) {
  99. // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
  100. this.onError('data request overlap from client');
  101. res.writeHead(500);
  102. res.end();
  103. return;
  104. }
  105. var isBinary = 'application/octet-stream' == req.headers['content-type'];
  106. this.dataReq = req;
  107. this.dataRes = res;
  108. var chunks = isBinary ? new Buffer(0) : '';
  109. var self = this;
  110. function cleanup () {
  111. chunks = isBinary ? new Buffer(0) : '';
  112. req.removeListener('data', onData);
  113. req.removeListener('end', onEnd);
  114. req.removeListener('close', onClose);
  115. self.dataReq = self.dataRes = 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 (typeof data == 'string') {
  124. chunks += data;
  125. contentLength = Buffer.byteLength(chunks);
  126. } else {
  127. chunks = Buffer.concat([chunks, data]);
  128. contentLength = chunks.length;
  129. }
  130. if (contentLength > self.maxHttpBufferSize) {
  131. chunks = '';
  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. * Comparesses 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.ServerRequest} 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. };