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