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.

535 lines
12 KiB

  1. if (global.GENTLY) require = GENTLY.hijack(require);
  2. var fs = require('fs');
  3. var util = require('util'),
  4. path = require('path'),
  5. File = require('./file'),
  6. MultipartParser = require('./multipart_parser').MultipartParser,
  7. QuerystringParser = require('./querystring_parser').QuerystringParser,
  8. OctetParser = require('./octet_parser').OctetParser,
  9. JSONParser = require('./json_parser').JSONParser,
  10. StringDecoder = require('string_decoder').StringDecoder,
  11. EventEmitter = require('events').EventEmitter,
  12. Stream = require('stream').Stream,
  13. os = require('os');
  14. function IncomingForm(opts) {
  15. if (!(this instanceof IncomingForm)) return new IncomingForm(opts);
  16. EventEmitter.call(this);
  17. opts=opts||{};
  18. this.error = null;
  19. this.ended = false;
  20. this.maxFields = opts.maxFields || 1000;
  21. this.maxFieldsSize = opts.maxFieldsSize || 2 * 1024 * 1024;
  22. this.keepExtensions = opts.keepExtensions || false;
  23. this.uploadDir = opts.uploadDir || os.tmpDir();
  24. this.encoding = opts.encoding || 'utf-8';
  25. this.headers = null;
  26. this.type = null;
  27. this.hash = false;
  28. this.bytesReceived = null;
  29. this.bytesExpected = null;
  30. this._parser = null;
  31. this._flushing = 0;
  32. this._fieldsSize = 0;
  33. this.openedFiles = [];
  34. return this;
  35. };
  36. util.inherits(IncomingForm, EventEmitter);
  37. exports.IncomingForm = IncomingForm;
  38. IncomingForm.prototype.parse = function(req, cb) {
  39. this.pause = function() {
  40. try {
  41. req.pause();
  42. } catch (err) {
  43. // the stream was destroyed
  44. if (!this.ended) {
  45. // before it was completed, crash & burn
  46. this._error(err);
  47. }
  48. return false;
  49. }
  50. return true;
  51. };
  52. this.resume = function() {
  53. try {
  54. req.resume();
  55. } catch (err) {
  56. // the stream was destroyed
  57. if (!this.ended) {
  58. // before it was completed, crash & burn
  59. this._error(err);
  60. }
  61. return false;
  62. }
  63. return true;
  64. };
  65. // Setup callback first, so we don't miss anything from data events emitted
  66. // immediately.
  67. if (cb) {
  68. var fields = {}, files = {};
  69. this
  70. .on('field', function(name, value) {
  71. fields[name] = value;
  72. })
  73. .on('file', function(name, file) {
  74. files[name] = file;
  75. })
  76. .on('error', function(err) {
  77. cb(err, fields, files);
  78. })
  79. .on('end', function() {
  80. cb(null, fields, files);
  81. });
  82. }
  83. // Parse headers and setup the parser, ready to start listening for data.
  84. this.writeHeaders(req.headers);
  85. // Start listening for data.
  86. var self = this;
  87. req
  88. .on('error', function(err) {
  89. self._error(err);
  90. })
  91. .on('aborted', function() {
  92. self.emit('aborted');
  93. self._error(new Error('Request aborted'));
  94. })
  95. .on('data', function(buffer) {
  96. self.write(buffer);
  97. })
  98. .on('end', function() {
  99. if (self.error) {
  100. return;
  101. }
  102. var err = self._parser.end();
  103. if (err) {
  104. self._error(err);
  105. }
  106. });
  107. return this;
  108. };
  109. IncomingForm.prototype.writeHeaders = function(headers) {
  110. this.headers = headers;
  111. this._parseContentLength();
  112. this._parseContentType();
  113. };
  114. IncomingForm.prototype.write = function(buffer) {
  115. if (!this._parser) {
  116. this._error(new Error('unintialized parser'));
  117. return;
  118. }
  119. this.bytesReceived += buffer.length;
  120. this.emit('progress', this.bytesReceived, this.bytesExpected);
  121. var bytesParsed = this._parser.write(buffer);
  122. if (bytesParsed !== buffer.length) {
  123. this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed'));
  124. }
  125. return bytesParsed;
  126. };
  127. IncomingForm.prototype.pause = function() {
  128. // this does nothing, unless overwritten in IncomingForm.parse
  129. return false;
  130. };
  131. IncomingForm.prototype.resume = function() {
  132. // this does nothing, unless overwritten in IncomingForm.parse
  133. return false;
  134. };
  135. IncomingForm.prototype.onPart = function(part) {
  136. // this method can be overwritten by the user
  137. this.handlePart(part);
  138. };
  139. IncomingForm.prototype.handlePart = function(part) {
  140. var self = this;
  141. if (part.filename === undefined) {
  142. var value = ''
  143. , decoder = new StringDecoder(this.encoding);
  144. part.on('data', function(buffer) {
  145. self._fieldsSize += buffer.length;
  146. if (self._fieldsSize > self.maxFieldsSize) {
  147. self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data'));
  148. return;
  149. }
  150. value += decoder.write(buffer);
  151. });
  152. part.on('end', function() {
  153. self.emit('field', part.name, value);
  154. });
  155. return;
  156. }
  157. this._flushing++;
  158. var file = new File({
  159. path: this._uploadPath(part.filename),
  160. name: part.filename,
  161. type: part.mime,
  162. hash: self.hash
  163. });
  164. this.emit('fileBegin', part.name, file);
  165. file.open();
  166. this.openedFiles.push(file);
  167. part.on('data', function(buffer) {
  168. self.pause();
  169. file.write(buffer, function() {
  170. self.resume();
  171. });
  172. });
  173. part.on('end', function() {
  174. file.end(function() {
  175. self._flushing--;
  176. self.emit('file', part.name, file);
  177. self._maybeEnd();
  178. });
  179. });
  180. };
  181. function dummyParser(self) {
  182. return {
  183. end: function () {
  184. self.ended = true;
  185. self._maybeEnd();
  186. return null;
  187. }
  188. };
  189. }
  190. IncomingForm.prototype._parseContentType = function() {
  191. if (this.bytesExpected === 0) {
  192. this._parser = dummyParser(this);
  193. return;
  194. }
  195. if (!this.headers['content-type']) {
  196. this._error(new Error('bad content-type header, no content-type'));
  197. return;
  198. }
  199. if (this.headers['content-type'].match(/octet-stream/i)) {
  200. this._initOctetStream();
  201. return;
  202. }
  203. if (this.headers['content-type'].match(/urlencoded/i)) {
  204. this._initUrlencoded();
  205. return;
  206. }
  207. if (this.headers['content-type'].match(/multipart/i)) {
  208. var m;
  209. if (m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i)) {
  210. this._initMultipart(m[1] || m[2]);
  211. } else {
  212. this._error(new Error('bad content-type header, no multipart boundary'));
  213. }
  214. return;
  215. }
  216. if (this.headers['content-type'].match(/json/i)) {
  217. this._initJSONencoded();
  218. return;
  219. }
  220. this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type']));
  221. };
  222. IncomingForm.prototype._error = function(err) {
  223. if (this.error || this.ended) {
  224. return;
  225. }
  226. this.error = err;
  227. this.pause();
  228. this.emit('error', err);
  229. if (Array.isArray(this.openedFiles)) {
  230. this.openedFiles.forEach(function(file) {
  231. file._writeStream.destroy();
  232. setTimeout(fs.unlink, 0, file.path);
  233. });
  234. }
  235. };
  236. IncomingForm.prototype._parseContentLength = function() {
  237. this.bytesReceived = 0;
  238. if (this.headers['content-length']) {
  239. this.bytesExpected = parseInt(this.headers['content-length'], 10);
  240. } else if (this.headers['transfer-encoding'] === undefined) {
  241. this.bytesExpected = 0;
  242. }
  243. if (this.bytesExpected !== null) {
  244. this.emit('progress', this.bytesReceived, this.bytesExpected);
  245. }
  246. };
  247. IncomingForm.prototype._newParser = function() {
  248. return new MultipartParser();
  249. };
  250. IncomingForm.prototype._initMultipart = function(boundary) {
  251. this.type = 'multipart';
  252. var parser = new MultipartParser(),
  253. self = this,
  254. headerField,
  255. headerValue,
  256. part;
  257. parser.initWithBoundary(boundary);
  258. parser.onPartBegin = function() {
  259. part = new Stream();
  260. part.readable = true;
  261. part.headers = {};
  262. part.name = null;
  263. part.filename = null;
  264. part.mime = null;
  265. part.transferEncoding = 'binary';
  266. part.transferBuffer = '';
  267. headerField = '';
  268. headerValue = '';
  269. };
  270. parser.onHeaderField = function(b, start, end) {
  271. headerField += b.toString(self.encoding, start, end);
  272. };
  273. parser.onHeaderValue = function(b, start, end) {
  274. headerValue += b.toString(self.encoding, start, end);
  275. };
  276. parser.onHeaderEnd = function() {
  277. headerField = headerField.toLowerCase();
  278. part.headers[headerField] = headerValue;
  279. var m;
  280. if (headerField == 'content-disposition') {
  281. if (m = headerValue.match(/\bname="([^"]+)"/i)) {
  282. part.name = m[1];
  283. }
  284. part.filename = self._fileName(headerValue);
  285. } else if (headerField == 'content-type') {
  286. part.mime = headerValue;
  287. } else if (headerField == 'content-transfer-encoding') {
  288. part.transferEncoding = headerValue.toLowerCase();
  289. }
  290. headerField = '';
  291. headerValue = '';
  292. };
  293. parser.onHeadersEnd = function() {
  294. switch(part.transferEncoding){
  295. case 'binary':
  296. case '7bit':
  297. case '8bit':
  298. parser.onPartData = function(b, start, end) {
  299. part.emit('data', b.slice(start, end));
  300. };
  301. parser.onPartEnd = function() {
  302. part.emit('end');
  303. };
  304. break;
  305. case 'base64':
  306. parser.onPartData = function(b, start, end) {
  307. part.transferBuffer += b.slice(start, end).toString('ascii');
  308. /*
  309. four bytes (chars) in base64 converts to three bytes in binary
  310. encoding. So we should always work with a number of bytes that
  311. can be divided by 4, it will result in a number of buytes that
  312. can be divided vy 3.
  313. */
  314. var offset = parseInt(part.transferBuffer.length / 4) * 4;
  315. part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64'))
  316. part.transferBuffer = part.transferBuffer.substring(offset);
  317. };
  318. parser.onPartEnd = function() {
  319. part.emit('data', new Buffer(part.transferBuffer, 'base64'))
  320. part.emit('end');
  321. };
  322. break;
  323. default:
  324. return self._error(new Error('unknown transfer-encoding'));
  325. }
  326. self.onPart(part);
  327. };
  328. parser.onEnd = function() {
  329. self.ended = true;
  330. self._maybeEnd();
  331. };
  332. this._parser = parser;
  333. };
  334. IncomingForm.prototype._fileName = function(headerValue) {
  335. var m = headerValue.match(/\bfilename="(.*?)"($|; )/i);
  336. if (!m) return;
  337. var filename = m[1].substr(m[1].lastIndexOf('\\') + 1);
  338. filename = filename.replace(/%22/g, '"');
  339. filename = filename.replace(/&#([\d]{4});/g, function(m, code) {
  340. return String.fromCharCode(code);
  341. });
  342. return filename;
  343. };
  344. IncomingForm.prototype._initUrlencoded = function() {
  345. this.type = 'urlencoded';
  346. var parser = new QuerystringParser(this.maxFields)
  347. , self = this;
  348. parser.onField = function(key, val) {
  349. self.emit('field', key, val);
  350. };
  351. parser.onEnd = function() {
  352. self.ended = true;
  353. self._maybeEnd();
  354. };
  355. this._parser = parser;
  356. };
  357. IncomingForm.prototype._initOctetStream = function() {
  358. this.type = 'octet-stream';
  359. var filename = this.headers['x-file-name'];
  360. var mime = this.headers['content-type'];
  361. var file = new File({
  362. path: this._uploadPath(filename),
  363. name: filename,
  364. type: mime
  365. });
  366. file.open();
  367. this.emit('fileBegin', filename, file);
  368. this._flushing++;
  369. var self = this;
  370. self._parser = new OctetParser();
  371. //Keep track of writes that haven't finished so we don't emit the file before it's done being written
  372. var outstandingWrites = 0;
  373. self._parser.on('data', function(buffer){
  374. self.pause();
  375. outstandingWrites++;
  376. file.write(buffer, function() {
  377. outstandingWrites--;
  378. self.resume();
  379. if(self.ended){
  380. self._parser.emit('doneWritingFile');
  381. }
  382. });
  383. });
  384. self._parser.on('end', function(){
  385. self._flushing--;
  386. self.ended = true;
  387. var done = function(){
  388. self.emit('file', 'file', file);
  389. self._maybeEnd();
  390. };
  391. if(outstandingWrites === 0){
  392. done();
  393. } else {
  394. self._parser.once('doneWritingFile', done);
  395. }
  396. });
  397. };
  398. IncomingForm.prototype._initJSONencoded = function() {
  399. this.type = 'json';
  400. var parser = new JSONParser()
  401. , self = this;
  402. if (this.bytesExpected) {
  403. parser.initWithLength(this.bytesExpected);
  404. }
  405. parser.onField = function(key, val) {
  406. self.emit('field', key, val);
  407. }
  408. parser.onEnd = function() {
  409. self.ended = true;
  410. self._maybeEnd();
  411. };
  412. this._parser = parser;
  413. };
  414. IncomingForm.prototype._uploadPath = function(filename) {
  415. var name = '';
  416. for (var i = 0; i < 32; i++) {
  417. name += Math.floor(Math.random() * 16).toString(16);
  418. }
  419. if (this.keepExtensions) {
  420. var ext = path.extname(filename);
  421. ext = ext.replace(/(\.[a-z0-9]+).*/, '$1');
  422. name += ext;
  423. }
  424. return path.join(this.uploadDir, name);
  425. };
  426. IncomingForm.prototype._maybeEnd = function() {
  427. if (!this.ended || this._flushing || this.error) {
  428. return;
  429. }
  430. this.emit('end');
  431. };