comunicationLeap/node_modules/engine.io/lib/transports/polling-jsonp.js
node_modules/engine.io/lib/transports/polling-jsonp.jsRaw
1
2/**
3 * Module dependencies.
4 */
5
6var Polling = require('./polling');
7var qs = require('querystring');
8var rDoubleSlashes = /\\\\n/g;
9var rSlashes = /(\\)?\\n/g;
10
11/**
12 * Module exports.
13 */
14
15module.exports = JSONP;
16
17/**
18 * JSON-P polling transport.
19 *
20 * @api public
21 */
22
23function JSONP (req) {
24 Polling.call(this, req);
25
26 this.head = '___eio[' + (req._query.j || '').replace(/[^0-9]/g, '') + '](';
27 this.foot = ');';
28};
29
30/**
31 * Inherits from Polling.
32 */
33
34JSONP.prototype.__proto__ = Polling.prototype;
35
36/**
37 * Handles incoming data.
38 * Due to a bug in \n handling by browsers, we expect a escaped string.
39 *
40 * @api private
41 */
42
43JSONP.prototype.onData = function (data) {
44 // we leverage the qs module so that we get built-in DoS protection
45 // and the fast alternative to decodeURIComponent
46 data = qs.parse(data).d;
47 if ('string' == typeof data) {
48 //client will send already escaped newlines as \\\\n and newlines as \\n
49 // \\n must be replaced with \n and \\\\n with \\n
50 data = data.replace(rSlashes, function(match, slashes) {
51 return slashes ? match : '\n';
52 });
53 Polling.prototype.onData.call(this, data.replace(rDoubleSlashes, '\\n'));
54 }
55};
56
57/**
58 * Performs the write.
59 *
60 * @api private
61 */
62
63JSONP.prototype.doWrite = function (data) {
64 // we must output valid javascript, not valid json
65 // see: http://timelessrepo.com/json-isnt-a-javascript-subset
66 var js = JSON.stringify(data)
67 .replace(/\u2028/g, '\\u2028')
68 .replace(/\u2029/g, '\\u2029');
69
70 // prepare response
71 data = this.head + js + this.foot;
72
73 // explicit UTF-8 is required for pages not served under utf
74 var headers = {
75 'Content-Type': 'text/javascript; charset=UTF-8',
76 'Content-Length': Buffer.byteLength(data)
77 };
78
79 // prevent XSS warnings on IE
80 // https://github.com/LearnBoost/socket.io/pull/1333
81 var ua = this.req.headers['user-agent'];
82 if (ua && (~ua.indexOf(';MSIE') || ~ua.indexOf('Trident/'))) {
83 headers['X-XSS-Protection'] = '0';
84 }
85
86 this.res.writeHead(200, this.headers(this.req, headers));
87 this.res.end(data);
88};
89
90/**
91 * Returns headers for a response.
92 *
93 * @param {http.ServerRequest} request
94 * @param {Object} extra headers
95 * @api private
96 */
97
98JSONP.prototype.headers = function (req, headers) {
99 headers = headers || {};
100
101 // disable XSS protection for IE
102 if (/MSIE 8\.0/.test(req.headers['user-agent'])) {
103 headers['X-XSS-Protection'] = '0';
104 }
105
106 this.emit('headers', headers);
107 return headers;
108};