Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

polling.js 8.4KB

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