polling-jsonp.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Module dependencies.
  3. */
  4. var Polling = require('./polling');
  5. var qs = require('querystring');
  6. var rDoubleSlashes = /\\\\n/g;
  7. var rSlashes = /(\\)?\\n/g;
  8. /**
  9. * Module exports.
  10. */
  11. module.exports = JSONP;
  12. /**
  13. * JSON-P polling transport.
  14. *
  15. * @api public
  16. */
  17. function JSONP (req) {
  18. Polling.call(this, req);
  19. this.head = '___eio[' + (req._query.j || '').replace(/[^0-9]/g, '') + '](';
  20. this.foot = ');';
  21. };
  22. /**
  23. * Inherits from Polling.
  24. */
  25. JSONP.prototype.__proto__ = Polling.prototype;
  26. /**
  27. * Handles incoming data.
  28. * Due to a bug in \n handling by browsers, we expect a escaped string.
  29. *
  30. * @api private
  31. */
  32. JSONP.prototype.onData = function (data) {
  33. // we leverage the qs module so that we get built-in DoS protection
  34. // and the fast alternative to decodeURIComponent
  35. data = qs.parse(data).d;
  36. if ('string' == typeof data) {
  37. //client will send already escaped newlines as \\\\n and newlines as \\n
  38. // \\n must be replaced with \n and \\\\n with \\n
  39. data = data.replace(rSlashes, function(match, slashes) {
  40. return slashes ? match : '\n';
  41. });
  42. Polling.prototype.onData.call(this, data.replace(rDoubleSlashes, '\\n'));
  43. }
  44. };
  45. /**
  46. * Performs the write.
  47. *
  48. * @api private
  49. */
  50. JSONP.prototype.doWrite = function (data, options, callback) {
  51. // we must output valid javascript, not valid json
  52. // see: http://timelessrepo.com/json-isnt-a-javascript-subset
  53. var js = JSON.stringify(data)
  54. .replace(/\u2028/g, '\\u2028')
  55. .replace(/\u2029/g, '\\u2029');
  56. // prepare response
  57. data = this.head + js + this.foot;
  58. Polling.prototype.doWrite.call(this, data, options, callback);
  59. };