Debian Codegraph @

fastify-busboy/bench/dicer/parted-multipart.js

raw
1 'use strict'
2
3 /**
4 * Parted (https://github.com/chjj/parted)
5 * A streaming multipart state parser.
6 * Copyright (c) 2011, Christopher Jeffrey. (MIT Licensed)
7 */
8
9 var fs = require('node:fs')
10 , path = require('node:path')
11 , EventEmitter = require('node:events').EventEmitter
12 , StringDecoder = require('node:string_decoder').StringDecoder
13 , set = require('qs').set
14 , each = Array.prototype.forEach;
15
16 /**
17 * Character Constants
18 */
19
20 var DASH = '-'.charCodeAt(0)
21 , CR = '\r'.charCodeAt(0)
22 , LF = '\n'.charCodeAt(0)
23 , COLON = ':'.charCodeAt(0)
24 , SPACE = ' '.charCodeAt(0);
25
26 /**
27 * Parser
28 */
29
30 var Parser = function(type, options) {
31 if (!(this instanceof Parser)) {
32 return new Parser(type, options);
33 }
34
35 EventEmitter.call(this);
36
37 this.writable = true;
38 this.readable = true;
39
40 this.options = options || {};
41
42 var key = grab(type, 'boundary');
43 if (!key) {
44 return this._error('No boundary key found.');
45 }
46
47 this.key = Buffer.allocUnsafe('\r\n--' + key);
48
49 this._key = {};
50 each.call(this.key, function(ch) {
51 this._key[ch] = true;
52 }, this);
53
54 this.state = 'start';
55 this.pending = 0;
56 this.written = 0;
57 this.writtenDisk = 0;
58 this.buff = Buffer.allocUnsafe(200);
59
60 this.preamble = true;
61 this.epilogue = false;
62
63 this._reset();
64 };
65
66 Parser.prototype.__proto__ = EventEmitter.prototype;
67
68 /**
69 * Parsing
70 */
71
72 Parser.prototype.write = function(data) {
73 if (!this.writable
74 || this.epilogue) return;
75
76 try {
77 this._parse(data);
78 } catch (e) {
79 this._error(e);
80 }
81
82 return true;
83 };
84
85 Parser.prototype.end = function(data) {
86 if (!this.writable) return;
87
88 if (data) this.write(data);
89
90 if (!this.epilogue) {
91 return this._error('Message underflow.');
92 }
93
94 return true;
95 };
96
97 Parser.prototype._parse = function(data) {
98 var i = 0
99 , len = data.length
100 , buff = this.buff
101 , key = this.key
102 , ch
103 , val
104 , j;
105
106 for (; i < len; i++) {
107 if (this.pos >= 200) {
108 return this._error('Potential buffer overflow.');
109 }
110
111 ch = data[i];
112
113 switch (this.state) {
114 case 'start':
115 switch (ch) {
116 case DASH:
117 this.pos = 3;
118 this.state = 'key';
119 break;
120 default:
121 break;
122 }
123 break;
124 case 'key':
125 if (this.pos === key.length) {
126 this.state = 'key_end';
127 i--;
128 } else if (ch !== key[this.pos]) {
129 if (this.preamble) {
130 this.state = 'start';
131 i--;
132 } else {
133 this.state = 'body';
134 val = this.pos - i;
135 if (val > 0) {
136 this._write(key.slice(0, val));
137 }
138 i--;
139 }
140 } else {
141 this.pos++;
142 }
143 break;
144 case 'key_end':
145 switch (ch) {
146 case CR:
147 this.state = 'key_line_end';
148 break;
149 case DASH:
150 this.state = 'key_dash_end';
151 break;
152 default:
153 return this._error('Expected CR or DASH.');
154 }
155 break;
156 case 'key_line_end':
157 switch (ch) {
158 case LF:
159 if (this.preamble) {
160 this.preamble = false;
161 } else {
162 this._finish();
163 }
164 this.state = 'header_name';
165 this.pos = 0;
166 break;
167 default:
168 return this._error('Expected CR.');
169 }
170 break;
171 case 'key_dash_end':
172 switch (ch) {
173 case DASH:
174 this.epilogue = true;
175 this._finish();
176 return;
177 default:
178 return this._error('Expected DASH.');
179 }
180 case 'header_name':
181 switch (ch) {
182 case COLON:
183 this.header = buff.toString('ascii', 0, this.pos);
184 this.pos = 0;
185 this.state = 'header_val';
186 break;
187 default:
188 buff[this.pos++] = ch | 32;
189 break;
190 }
191 break;
192 case 'header_val':
193 switch (ch) {
194 case CR:
195 this.state = 'header_val_end';
196 break;
197 case SPACE:
198 if (this.pos === 0) {
199 break;
200 }
201 // FALL-THROUGH
202 default:
203 buff[this.pos++] = ch;
204 break;
205 }
206 break;
207 case 'header_val_end':
208 switch (ch) {
209 case LF:
210 val = buff.toString('ascii', 0, this.pos);
211 this._header(this.header, val);
212 this.pos = 0;
213 this.state = 'header_end';
214 break;
215 default:
216 return this._error('Expected LF.');
217 }
218 break;
219 case 'header_end':
220 switch (ch) {
221 case CR:
222 this.state = 'head_end';
223 break;
224 default:
225 this.state = 'header_name';
226 i--;
227 break;
228 }
229 break;
230 case 'head_end':
231 switch (ch) {
232 case LF:
233 this.state = 'body';
234 i++;
235 if (i >= len) return;
236 data = data.slice(i);
237 i = -1;
238 len = data.length;
239 break;
240 default:
241 return this._error('Expected LF.');
242 }
243 break;
244 case 'body':
245 switch (ch) {
246 case CR:
247 if (i > 0) {
248 this._write(data.slice(0, i));
249 }
250 this.pos = 1;
251 this.state = 'key';
252 data = data.slice(i);
253 i = 0;
254 len = data.length;
255 break;
256 default:
257 // boyer-moore-like algorithm
258 // at felixge's suggestion
259 while ((j = i + key.length - 1) < len) {
260 if (this._key[data[j]]) break;
261 i = j;
262 }
263 break;
264 }
265 break;
266 }
267 }
268
269 if (this.state === 'body') {
270 this._write(data);
271 }
272 };
273
274 Parser.prototype._header = function(name, val) {
275 /*if (name === 'content-disposition') {
276 this.field = grab(val, 'name');
277 this.file = grab(val, 'filename');
278
279 if (this.file) {
280 this.data = stream(this.file, this.options.path);
281 } else {
282 this.decode = new StringDecoder('utf8');
283 this.data = '';
284 }
285 }*/
286
287 return this.emit('header', name, val);
288 };
289
290 Parser.prototype._write = function(data) {
291 /*if (this.data == null) {
292 return this._error('No disposition.');
293 }
294
295 if (this.file) {
296 this.data.write(data);
297 this.writtenDisk += data.length;
298 } else {
299 this.data += this.decode.write(data);
300 this.written += data.length;
301 }*/
302
303 this.emit('data', data);
304 };
305
306 Parser.prototype._reset = function() {
307 this.pos = 0;
308 this.decode = null;
309 this.field = null;
310 this.data = null;
311 this.file = null;
312 this.header = null;
313 };
314
315 Parser.prototype._error = function(err) {
316 this.destroy();
317 this.emit('error', typeof err === 'string'
318 ? new Error(err)
319 : err);
320 };
321
322 Parser.prototype.destroy = function(err) {
323 this.writable = false;
324 this.readable = false;
325 this._reset();
326 };
327
328 Parser.prototype._finish = function() {
329 var self = this
330 , field = this.field
331 , data = this.data
332 , file = this.file
333 , part;
334
335 this.pending++;
336
337 this._reset();
338
339 if (data && data.path) {
340 part = data.path;
341 data.end(next);
342 } else {
343 part = data;
344 next();
345 }
346
347 function next() {
348 if (!self.readable) return;
349
350 self.pending--;
351
352 self.emit('part', field, part);
353
354 if (data && data.path) {
355 self.emit('file', field, part, file);
356 }
357
358 if (self.epilogue && !self.pending) {
359 self.emit('end');
360 self.destroy();
361 }
362 }
363 };
364
365 /**
366 * Uploads
367 */
368
369 Parser.root = process.platform === 'win32'
370 ? 'C:/Temp'
371 : '/tmp';
372
373 /**
374 * Middleware
375 */
376
377 Parser.middleware = function(options) {
378 options = options || {};
379 return function(req, res, next) {
380 if (options.ensureBody) {
381 req.body = {};
382 }
383
384 if (req.method === 'GET'
385 || req.method === 'HEAD'
386 || req._multipart) return next();
387
388 req._multipart = true;
389
390 var type = req.headers['content-type'];
391
392 if (type) type = type.split(';', 1)[0].trim().toLowerCase();
393
394 if (type === 'multipart/form-data') {
395 Parser.handle(req, res, next, options);
396 } else {
397 next();
398 }
399 };
400 };
401
402 /**
403 * Handler
404 */
405
406 Parser.handle = function(req, res, next, options) {
407 var parser = new Parser(req.headers['content-type'], options)
408 , diskLimit = options.diskLimit
409 , limit = options.limit
410 , parts = {}
411 , files = {};
412
413 parser.on('error', function(err) {
414 req.destroy();
415 next(err);
416 });
417
418 parser.on('part', function(field, part) {
419 set(parts, field, part);
420 });
421
422 parser.on('file', function(field, path, name) {
423 set(files, field, {
424 path: path,
425 name: name,
426 toString: function() {
427 return path;
428 }
429 });
430 });
431
432 parser.on('data', function() {
433 if (this.writtenDisk > diskLimit || this.written > limit) {
434 this.emit('error', new Error('Overflow.'));
435 this.destroy();
436 }
437 });
438
439 parser.on('end', next);
440
441 req.body = parts;
442 req.files = files;
443 req.pipe(parser);
444 };
445
446 /**
447 * Helpers
448 */
449
450 var isWindows = process.platform === 'win32';
451
452 var stream = function(name, dir) {
453 var ext = path.extname(name) || ''
454 , name = path.basename(name, ext) || ''
455 , dir = dir || Parser.root
456 , tag;
457
458 tag = Math.random().toString(36).substring(2);
459
460 name = name.substring(0, 200) + '.' + tag;
461 name = path.join(dir, name) + ext.substring(0, 6);
462 name = name.replace(/\0/g, '');
463
464 if (isWindows) {
465 name = name.replace(/[:*<>|"?]/g, '');
466 }
467
468 return fs.createWriteStream(name);
469 };
470
471 var grab = function(str, name) {
472 if (!str) return;
473
474 var rx = new RegExp('\\b' + name + '\\s*=\\s*("[^"]+"|\'[^\']+\'|[^;,]+)', 'i')
475 , cap = rx.exec(str);
476
477 if (cap) {
478 return cap[1].trim().replace(/^['"]|['"]$/g, '');
479 }
480 };
481
482 /**
483 * Expose
484 */
485
486 module.exports = Parser;