/usr/lib/nodejs/multiparty/index.js is in node-multiparty 4.0.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 | var stream = require('stream');
var util = require('util');
var fs = require('fs');
var crypto = require('crypto');
var path = require('path');
var os = require('os');
var StringDecoder = require('string_decoder').StringDecoder;
var FdSlicer = require('fd-slicer');
var START = 0;
var START_BOUNDARY = 1;
var HEADER_FIELD_START = 2;
var HEADER_FIELD = 3;
var HEADER_VALUE_START = 4;
var HEADER_VALUE = 5;
var HEADER_VALUE_ALMOST_DONE = 6;
var HEADERS_ALMOST_DONE = 7;
var PART_DATA_START = 8;
var PART_DATA = 9;
var PART_END = 10;
var CLOSE_BOUNDARY = 11;
var END = 12;
var LF = 10;
var CR = 13;
var SPACE = 32;
var HYPHEN = 45;
var COLON = 58;
var A = 97;
var Z = 122;
var CONTENT_TYPE_RE = /^multipart\/(?:form-data|related)(?:;|$)/i;
var CONTENT_TYPE_PARAM_RE = /;\s*([^=]+)=(?:"([^"]+)"|([^;]+))/gi;
var FILE_EXT_RE = /(\.[_\-a-zA-Z0-9]{0,16}).*/;
var LAST_BOUNDARY_SUFFIX_LEN = 4; // --\r\n
// replace base64 characters with safe-for-filename characters
var b64Safe = {'/': '_', '+': '-'};
exports.Form = Form;
util.inherits(Form, stream.Writable);
function Form(options) {
var self = this;
stream.Writable.call(self);
options = options || {};
self.error = null;
self.autoFields = !!options.autoFields;
self.autoFiles = !!options.autoFiles;
self.maxFields = options.maxFields || 1000;
self.maxFieldsSize = options.maxFieldsSize || 2 * 1024 * 1024;
self.maxFilesSize = options.maxFilesSize || Infinity;
self.uploadDir = options.uploadDir || os.tmpDir();
self.encoding = options.encoding || 'utf8';
self.bytesReceived = 0;
self.bytesExpected = null;
self.openedFiles = [];
self.totalFieldSize = 0;
self.totalFieldCount = 0;
self.totalFileSize = 0;
self.flushing = 0;
self.backpressure = false;
self.writeCbs = [];
self.emitQueue = [];
self.on('newListener', function(eventName) {
if (eventName === 'file') {
self.autoFiles = true;
} else if (eventName === 'field') {
self.autoFields = true;
}
});
}
Form.prototype.parse = function(req, cb) {
var called = false;
var self = this;
var waitend = true;
if (cb) {
// if the user supplies a callback, this implies autoFields and autoFiles
self.autoFields = true;
self.autoFiles = true;
// wait for request to end before calling cb
var end = function (done) {
if (called) return;
called = true;
// wait for req events to fire
process.nextTick(function() {
if (waitend && req.readable) {
// dump rest of request
req.resume();
req.once('end', done);
return;
}
done();
});
};
var fields = {};
var files = {};
self.on('error', function(err) {
end(function() {
cb(err);
});
});
self.on('field', function(name, value) {
var fieldsArray = fields[name] || (fields[name] = []);
fieldsArray.push(value);
});
self.on('file', function(name, file) {
var filesArray = files[name] || (files[name] = []);
filesArray.push(file);
});
self.on('close', function() {
end(function() {
cb(null, fields, files);
});
});
}
self.handleError = handleError;
self.bytesExpected = getBytesExpected(req.headers);
req.on('end', onReqEnd);
req.on('error', function(err) {
waitend = false;
handleError(err);
});
req.on('aborted', onReqAborted);
var state = req._readableState;
if (req._decoder || (state && (state.encoding || state.decoder))) {
// this is a binary protocol
// if an encoding is set, input is likely corrupted
validationError(new Error('request encoding must not be set'));
return;
}
var contentType = req.headers['content-type'];
if (!contentType) {
validationError(new Error('missing content-type header'));
return;
}
var m = CONTENT_TYPE_RE.exec(contentType);
if (!m) {
validationError(new Error('unrecognized content-type: ' + contentType));
return;
}
var boundary;
CONTENT_TYPE_PARAM_RE.lastIndex = m.index + m[0].length - 1;
while ((m = CONTENT_TYPE_PARAM_RE.exec(contentType))) {
if (m[1].toLowerCase() !== 'boundary') continue;
boundary = m[2] || m[3];
break;
}
if (!boundary) {
validationError(new Error('content-type missing boundary: ' + require('util').inspect(m)));
return;
}
setUpParser(self, boundary);
req.pipe(self);
function onReqAborted() {
waitend = false;
self.emit('aborted');
handleError(new Error("Request aborted"));
}
function onReqEnd() {
waitend = false;
}
function handleError(err) {
var first = !self.error;
if (first) {
self.error = err;
req.removeListener('aborted', onReqAborted);
req.removeListener('end', onReqEnd);
if (self.destStream) {
self.destStream.emit('error', err);
}
}
cleanupOpenFiles(self);
if (first) {
self.emit('error', err);
}
}
function validationError(err) {
// handle error on next tick for event listeners to attach
process.nextTick(handleError.bind(null, err))
}
};
Form.prototype._write = function(buffer, encoding, cb) {
if (this.error) return;
var self = this;
var i = 0;
var len = buffer.length;
var prevIndex = self.index;
var index = self.index;
var state = self.state;
var lookbehind = self.lookbehind;
var boundary = self.boundary;
var boundaryChars = self.boundaryChars;
var boundaryLength = self.boundary.length;
var boundaryEnd = boundaryLength - 1;
var bufferLength = buffer.length;
var c;
var cl;
for (i = 0; i < len; i++) {
c = buffer[i];
switch (state) {
case START:
index = 0;
state = START_BOUNDARY;
/* falls through */
case START_BOUNDARY:
if (index === boundaryLength - 2 && c === HYPHEN) {
index = 1;
state = CLOSE_BOUNDARY;
break;
} else if (index === boundaryLength - 2) {
if (c !== CR) return self.handleError(new Error("Expected CR Received " + c));
index++;
break;
} else if (index === boundaryLength - 1) {
if (c !== LF) return self.handleError(new Error("Expected LF Received " + c));
index = 0;
self.onParsePartBegin();
state = HEADER_FIELD_START;
break;
}
if (c !== boundary[index+2]) index = -2;
if (c === boundary[index+2]) index++;
break;
case HEADER_FIELD_START:
state = HEADER_FIELD;
self.headerFieldMark = i;
index = 0;
/* falls through */
case HEADER_FIELD:
if (c === CR) {
self.headerFieldMark = null;
state = HEADERS_ALMOST_DONE;
break;
}
index++;
if (c === HYPHEN) break;
if (c === COLON) {
if (index === 1) {
// empty header field
self.handleError(new Error("Empty header field"));
return;
}
self.onParseHeaderField(buffer.slice(self.headerFieldMark, i));
self.headerFieldMark = null;
state = HEADER_VALUE_START;
break;
}
cl = lower(c);
if (cl < A || cl > Z) {
self.handleError(new Error("Expected alphabetic character, received " + c));
return;
}
break;
case HEADER_VALUE_START:
if (c === SPACE) break;
self.headerValueMark = i;
state = HEADER_VALUE;
/* falls through */
case HEADER_VALUE:
if (c === CR) {
self.onParseHeaderValue(buffer.slice(self.headerValueMark, i));
self.headerValueMark = null;
self.onParseHeaderEnd();
state = HEADER_VALUE_ALMOST_DONE;
}
break;
case HEADER_VALUE_ALMOST_DONE:
if (c !== LF) return self.handleError(new Error("Expected LF Received " + c));
state = HEADER_FIELD_START;
break;
case HEADERS_ALMOST_DONE:
if (c !== LF) return self.handleError(new Error("Expected LF Received " + c));
var err = self.onParseHeadersEnd(i + 1);
if (err) return self.handleError(err);
state = PART_DATA_START;
break;
case PART_DATA_START:
state = PART_DATA;
self.partDataMark = i;
/* falls through */
case PART_DATA:
prevIndex = index;
if (index === 0) {
// boyer-moore derrived algorithm to safely skip non-boundary data
i += boundaryEnd;
while (i < bufferLength && !(buffer[i] in boundaryChars)) {
i += boundaryLength;
}
i -= boundaryEnd;
c = buffer[i];
}
if (index < boundaryLength) {
if (boundary[index] === c) {
if (index === 0) {
self.onParsePartData(buffer.slice(self.partDataMark, i));
self.partDataMark = null;
}
index++;
} else {
index = 0;
}
} else if (index === boundaryLength) {
index++;
if (c === CR) {
// CR = part boundary
self.partBoundaryFlag = true;
} else if (c === HYPHEN) {
index = 1;
state = CLOSE_BOUNDARY;
break;
} else {
index = 0;
}
} else if (index - 1 === boundaryLength) {
if (self.partBoundaryFlag) {
index = 0;
if (c === LF) {
self.partBoundaryFlag = false;
self.onParsePartEnd();
self.onParsePartBegin();
state = HEADER_FIELD_START;
break;
}
} else {
index = 0;
}
}
if (index > 0) {
// when matching a possible boundary, keep a lookbehind reference
// in case it turns out to be a false lead
lookbehind[index-1] = c;
} else if (prevIndex > 0) {
// if our boundary turned out to be rubbish, the captured lookbehind
// belongs to partData
self.onParsePartData(lookbehind.slice(0, prevIndex));
prevIndex = 0;
self.partDataMark = i;
// reconsider the current character even so it interrupted the sequence
// it could be the beginning of a new sequence
i--;
}
break;
case CLOSE_BOUNDARY:
if (c !== HYPHEN) return self.handleError(new Error("Expected HYPHEN Received " + c));
if (index === 1) {
self.onParsePartEnd();
state = END;
} else if (index > 1) {
return self.handleError(new Error("Parser has invalid state."));
}
index++;
break;
case END:
break;
default:
self.handleError(new Error("Parser has invalid state."));
return;
}
}
if (self.headerFieldMark != null) {
self.onParseHeaderField(buffer.slice(self.headerFieldMark));
self.headerFieldMark = 0;
}
if (self.headerValueMark != null) {
self.onParseHeaderValue(buffer.slice(self.headerValueMark));
self.headerValueMark = 0;
}
if (self.partDataMark != null) {
self.onParsePartData(buffer.slice(self.partDataMark));
self.partDataMark = 0;
}
self.index = index;
self.state = state;
self.bytesReceived += buffer.length;
self.emit('progress', self.bytesReceived, self.bytesExpected);
if (self.backpressure) {
self.writeCbs.push(cb);
} else {
cb();
}
};
Form.prototype.onParsePartBegin = function() {
clearPartVars(this);
}
Form.prototype.onParseHeaderField = function(b) {
this.headerField += this.headerFieldDecoder.write(b);
}
Form.prototype.onParseHeaderValue = function(b) {
this.headerValue += this.headerValueDecoder.write(b);
}
Form.prototype.onParseHeaderEnd = function() {
this.headerField = this.headerField.toLowerCase();
this.partHeaders[this.headerField] = this.headerValue;
var m;
if (this.headerField === 'content-disposition') {
if (m = this.headerValue.match(/\bname="([^"]+)"/i)) {
this.partName = m[1];
}
this.partFilename = parseFilename(this.headerValue);
} else if (this.headerField === 'content-transfer-encoding') {
this.partTransferEncoding = this.headerValue.toLowerCase();
}
this.headerFieldDecoder = new StringDecoder(this.encoding);
this.headerField = '';
this.headerValueDecoder = new StringDecoder(this.encoding);
this.headerValue = '';
}
Form.prototype.onParsePartData = function(b) {
if (this.partTransferEncoding === 'base64') {
this.backpressure = ! this.destStream.write(b.toString('ascii'), 'base64');
} else {
this.backpressure = ! this.destStream.write(b);
}
}
Form.prototype.onParsePartEnd = function() {
if (this.destStream) {
flushWriteCbs(this);
var s = this.destStream;
process.nextTick(function() {
s.end();
});
}
clearPartVars(this);
}
Form.prototype.onParseHeadersEnd = function(offset) {
var self = this;
switch(self.partTransferEncoding){
case 'binary':
case '7bit':
case '8bit':
self.partTransferEncoding = 'binary';
break;
case 'base64': break;
default:
return new Error("unknown transfer-encoding: " + self.partTransferEncoding);
}
self.totalFieldCount += 1;
if (self.totalFieldCount > self.maxFields) {
return new Error("maxFields " + self.maxFields + " exceeded.");
}
self.destStream = new stream.PassThrough();
self.destStream.on('drain', function() {
flushWriteCbs(self);
});
self.destStream.headers = self.partHeaders;
self.destStream.name = self.partName;
self.destStream.filename = self.partFilename;
self.destStream.byteOffset = self.bytesReceived + offset;
var partContentLength = self.destStream.headers['content-length'];
self.destStream.byteCount = partContentLength ? parseInt(partContentLength, 10) :
self.bytesExpected ? (self.bytesExpected - self.destStream.byteOffset -
self.boundary.length - LAST_BOUNDARY_SUFFIX_LEN) :
undefined;
if (self.destStream.filename == null && self.autoFields) {
handleField(self, self.destStream);
} else if (self.destStream.filename != null && self.autoFiles) {
handleFile(self, self.destStream);
} else {
handlePart(self, self.destStream);
}
}
function flushWriteCbs(self) {
self.writeCbs.forEach(function(cb) {
process.nextTick(cb);
});
self.writeCbs = [];
self.backpressure = false;
}
function getBytesExpected(headers) {
var contentLength = headers['content-length'];
if (contentLength) {
return parseInt(contentLength, 10);
} else if (headers['transfer-encoding'] == null) {
return 0;
} else {
return null;
}
}
function beginFlush(self) {
self.flushing += 1;
}
function endFlush(self) {
self.flushing -= 1;
if (self.flushing < 0) {
// if this happens this is a critical bug in multiparty and this stack trace
// will help us figure it out.
self.handleError(new Error("unexpected endFlush"));
return;
}
maybeClose(self);
}
function maybeClose(self) {
if (self.flushing > 0 || self.error) return;
// go through the emit queue in case any field, file, or part events are
// waiting to be emitted
holdEmitQueue(self)(function() {
// nextTick because the user is listening to part 'end' events and we are
// using part 'end' events to decide when to emit 'close'. we add our 'end'
// handler before the user gets a chance to add theirs. So we make sure
// their 'end' event fires before we emit the 'close' event.
// this is covered by test/standalone/test-issue-36
process.nextTick(function() {
self.emit('close');
});
});
}
function cleanupOpenFiles(self) {
self.openedFiles.forEach(function(internalFile) {
// since fd slicer autoClose is true, destroying the only write stream
// is guaranteed by the API to close the fd
internalFile.ws.destroy();
fs.unlink(internalFile.publicFile.path, function(err) {
if (err) self.handleError(err);
});
});
self.openedFiles = [];
}
function holdEmitQueue(self) {
var o = {cb: null};
self.emitQueue.push(o);
return function(cb) {
o.cb = cb;
flushEmitQueue(self);
};
}
function flushEmitQueue(self) {
while (self.emitQueue.length > 0 && self.emitQueue[0].cb) {
self.emitQueue.shift().cb();
}
}
function handlePart(self, partStream) {
beginFlush(self);
var emitAndReleaseHold = holdEmitQueue(self);
partStream.on('end', function() {
endFlush(self);
});
emitAndReleaseHold(function() {
self.emit('part', partStream);
});
}
function handleFile(self, fileStream) {
if (self.error) return;
var publicFile = {
fieldName: fileStream.name,
originalFilename: fileStream.filename,
path: uploadPath(self.uploadDir, fileStream.filename),
headers: fileStream.headers,
size: 0,
};
var internalFile = {
publicFile: publicFile,
ws: null,
};
beginFlush(self); // flush to write stream
var emitAndReleaseHold = holdEmitQueue(self);
fileStream.on('error', function(err) {
self.handleError(err);
});
fs.open(publicFile.path, 'w', function(err, fd) {
if (err) return self.handleError(err);
var fdSlicer = new FdSlicer(fd, {autoClose: true});
// end option here guarantees that no more than that amount will be written
// or else an error will be emitted
internalFile.ws = fdSlicer.createWriteStream({end: self.maxFilesSize - self.totalFileSize});
// if an error ocurred while we were waiting for fs.open we handle that
// cleanup now
self.openedFiles.push(internalFile);
if (self.error) return cleanupOpenFiles(self);
var prevByteCount = 0;
internalFile.ws.on('error', function(err) {
self.handleError(err);
});
internalFile.ws.on('progress', function() {
publicFile.size = internalFile.ws.bytesWritten;
var delta = publicFile.size - prevByteCount;
self.totalFileSize += delta;
prevByteCount = publicFile.size;
});
fdSlicer.on('close', function() {
if (self.error) return;
emitAndReleaseHold(function() {
self.emit('file', fileStream.name, publicFile);
});
endFlush(self);
});
fileStream.pipe(internalFile.ws);
});
}
function handleField(self, fieldStream) {
var value = '';
var decoder = new StringDecoder(self.encoding);
beginFlush(self);
var emitAndReleaseHold = holdEmitQueue(self);
fieldStream.on('error', function(err) {
self.handleError(err);
});
fieldStream.on('readable', function() {
var buffer = fieldStream.read();
if (!buffer) return;
self.totalFieldSize += buffer.length;
if (self.totalFieldSize > self.maxFieldsSize) {
self.handleError(new Error("maxFieldsSize " + self.maxFieldsSize + " exceeded"));
return;
}
value += decoder.write(buffer);
});
fieldStream.on('end', function() {
emitAndReleaseHold(function() {
self.emit('field', fieldStream.name, value);
});
endFlush(self);
});
}
function clearPartVars(self) {
self.partHeaders = {};
self.partName = null;
self.partFilename = null;
self.partTransferEncoding = 'binary';
self.destStream = null;
self.headerFieldDecoder = new StringDecoder(self.encoding);
self.headerField = "";
self.headerValueDecoder = new StringDecoder(self.encoding);
self.headerValue = "";
}
function setUpParser(self, boundary) {
self.boundary = new Buffer(boundary.length + 4);
self.boundary.write('\r\n--', 0, boundary.length + 4, 'ascii');
self.boundary.write(boundary, 4, boundary.length, 'ascii');
self.lookbehind = new Buffer(self.boundary.length + 8);
self.state = START;
self.boundaryChars = {};
for (var i = 0; i < self.boundary.length; i++) {
self.boundaryChars[self.boundary[i]] = true;
}
self.index = null;
self.partBoundaryFlag = false;
beginFlush(self);
self.on('finish', function() {
if (self.state !== END) {
self.handleError(new Error('stream ended unexpectedly'));
}
endFlush(self);
});
}
function uploadPath(baseDir, filename) {
var ext = path.extname(filename).replace(FILE_EXT_RE, '$1');
var name = randoString(18) + ext;
return path.join(baseDir, name);
}
function randoString(size) {
return rando(size).toString('base64').replace(/[\/\+]/g, function(x) {
return b64Safe[x];
});
}
function rando(size) {
try {
return crypto.randomBytes(size);
} catch (err) {
return crypto.pseudoRandomBytes(size);
}
}
function parseFilename(headerValue) {
var m = headerValue.match(/\bfilename="(.*?)"($|; )/i);
if (!m) {
m = headerValue.match(/\bfilename\*=utf-8\'\'(.*?)($|; )/i);
if (m) {
m[1] = decodeURI(m[1]);
}
else {
return;
}
}
var filename = m[1].substr(m[1].lastIndexOf('\\') + 1);
filename = filename.replace(/%22/g, '"');
filename = filename.replace(/&#([\d]{4});/g, function(m, code) {
return String.fromCharCode(code);
});
return filename;
}
function lower(c) {
return c | 0x20;
}
|