15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
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
/**
 * Form Data format:
 *
 
```txt
--FormStreamBoundary1349886663601\r\n
Content-Disposition: form-data; name="foo"\r\n
\r\n
<FIELD-CONTENT>\r\n
--FormStreamBoundary1349886663601\r\n
Content-Disposition: form-data; name="data"\r\n
Content-Type: application/json\r\n
\r\n
<JSON-FORMAT-CONTENT>\r\n
--FormStreamBoundary1349886663601\r\n
Content-Disposition: form-data; name="file"; filename="formstream.test.js"\r\n
Content-Type: application/javascript\r\n
\r\n
<FILE-CONTENT-CHUNK-1>
...
<FILE-CONTENT-CHUNK-N>
\r\n
--FormStreamBoundary1349886663601\r\n
Content-Disposition: form-data; name="pic"; filename="fawave.png"\r\n
Content-Type: image/png\r\n
\r\n
<IMAGE-CONTENT>\r\n
--FormStreamBoundary1349886663601--
```
 
 *
 */
 
'use strict';
 
var debug = require('util').debuglog('formstream');
var Stream = require('stream');
var parseStream = require('pause-stream');
var util = require('util');
var mime = require('mime');
var path = require('path');
var fs = require('fs');
var destroy = require('destroy');
var hex = require('node-hex');
 
var PADDING = '--';
var NEW_LINE = '\r\n';
var NEW_LINE_BUFFER =  Buffer.from(NEW_LINE);
 
function FormStream(options) {
  if (!(this instanceof FormStream)) {
    return new FormStream(options);
  }
 
  FormStream.super_.call(this);
 
  this._boundary = this._generateBoundary();
  this._streams = [];
  this._buffers = [];
  this._endData = Buffer.from(PADDING + this._boundary + PADDING + NEW_LINE);
  this._contentLength = 0;
  this._isAllStreamSizeKnown = true;
  this._knownStreamSize = 0;
  this._minChunkSize = options && options.minChunkSize || 0;
 
  this.isFormStream = true;
  debug('start boundary\n%s', this._boundary);
}
 
util.inherits(FormStream, Stream);
module.exports = FormStream;
 
FormStream.prototype._generateBoundary = function() {
  // https://github.com/felixge/node-form-data/blob/master/lib/form_data.js#L162
  // This generates a 50 character boundary similar to those used by Firefox.
  // They are optimized for boyer-moore parsing.
  var boundary = '--------------------------';
  for (var i = 0; i < 24; i++) {
    boundary += Math.floor(Math.random() * 10).toString(16);
  }
 
  return boundary;
};
 
FormStream.prototype.setTotalStreamSize = function (size) {
  // this method should not make any sense if the length of each stream is known.
  if (this._isAllStreamSizeKnown) {
    return this;
  }
 
  size = size || 0;
 
  for (var i = 0; i < this._streams.length; i++) {
    size += this._streams[i][0].length;
    size += NEW_LINE_BUFFER.length; // stream field end padding size
  }
 
  this._knownStreamSize = size;
  this._isAllStreamSizeKnown = true;
  debug('set total size: %s', size);
  return this;
};
 
FormStream.prototype.headers = function (options) {
  var headers = {
    'Content-Type': 'multipart/form-data; boundary=' + this._boundary
  };
 
  // calculate total stream size
  this._contentLength += this._knownStreamSize;
  // calculate length of end padding
  this._contentLength += this._endData.length;
 
  if (this._isAllStreamSizeKnown) {
    headers['Content-Length'] = String(this._contentLength);
  }
 
  if (options) {
    for (var k in options) {
      headers[k] = options[k];
    }
  }
 
  debug('headers: %j', headers);
  return headers;
};
 
FormStream.prototype.file = function (name, filepath, filename, filesize) {
  if (typeof filename === 'number' && !filesize) {
    filesize = filename;
    filename = path.basename(filepath);
  }
  if (!filename) {
    filename = path.basename(filepath);
  }
 
  var mimeType = mime.getType(filename);
  var stream = fs.createReadStream(filepath);
 
  return this.stream(name, stream, filename, mimeType, filesize);
};
 
/**
 * Add a form field
 * @param  {String} name field name
 * @param  {String|Buffer} value field value
 * @param  {String} [mimeType] field mimeType
 * @return {this}
 */
FormStream.prototype.field = function (name, value, mimeType) {
  if (!Buffer.isBuffer(value)) {
    // field(String, Number)
    // https://github.com/qiniu/nodejs-sdk/issues/123
    if (typeof value === 'number') {
      value = String(value);
    }
    value = Buffer.from(value);
  }
  return this.buffer(name, value, null, mimeType);
};
 
FormStream.prototype.stream = function (name, stream, filename, mimeType, size) {
  if (typeof mimeType === 'number' && !size) {
    size = mimeType;
    mimeType = mime.getType(filename);
  } else if (!mimeType) {
    mimeType = mime.getType(filename);
  }
 
  stream.once('error', this.emit.bind(this, 'error'));
  // if form stream destroy, also destroy the source stream
  this.once('destroy', function () {
    destroy(stream);
  });
 
  var leading = this._leading({ name: name, filename: filename }, mimeType);
 
  var ps = parseStream().pause();
  stream.pipe(ps);
 
  this._streams.push([leading, ps]);
 
  // if the size of this stream is known, plus the total content-length;
  // otherwise, content-length is unknown.
  if (typeof size === 'number') {
    this._knownStreamSize += leading.length;
    this._knownStreamSize += size;
    this._knownStreamSize += NEW_LINE_BUFFER.length;
  } else {
    this._isAllStreamSizeKnown = false;
  }
 
  process.nextTick(this.resume.bind(this));
 
  return this;
};
 
FormStream.prototype.buffer = function (name, buffer, filename, mimeType) {
  if (filename && !mimeType) {
    mimeType = mime.getType(filename);
  }
 
  var disposition = { name: name };
  if (filename) {
    disposition.filename = filename;
  }
 
  var leading = this._leading(disposition, mimeType);
 
  // plus buffer length to total content-length
  var bufferSize = leading.length + buffer.length + NEW_LINE_BUFFER.length;
  this._buffers.push(Buffer.concat([leading, buffer, NEW_LINE_BUFFER], bufferSize));  
  this._contentLength += bufferSize;
 
  process.nextTick(this.resume.bind(this));
  if (debug.enabled) {
    if (buffer.length > 512) {
      debug('new buffer field, content size: %d\n%s%s',
        buffer.length, leading.toString(), hex(buffer.slice(0, 512)));
    } else {
      debug('new buffer field, content size: %d\n%s%s',
        buffer.length, leading.toString(), hex(buffer));
    }
  }
  return this;
};
 
FormStream.prototype._leading = function (disposition, type) {
  var leading = [PADDING + this._boundary];
 
  var dispositions = [];
 
  if (disposition) {
    for (var k in disposition) {
      dispositions.push(k + '="' + disposition[k] + '"');
    }
  }
 
  leading.push('Content-Disposition: form-data; ' + dispositions.join('; '));
  if (type) {
    leading.push('Content-Type: ' + type);
  }
 
  leading.push('');
  leading.push('');
  return Buffer.from(leading.join(NEW_LINE));
};
 
FormStream.prototype._emitBuffers = function () {
  if (!this._buffers.length) {
    return;
  }
 
  for (var i = 0; i < this._buffers.length; i++) {
    this.emit('data', this._buffers[i]);
  }
  this._buffers = [];
};
 
FormStream.prototype._emitStream = function (item) {
  var self = this;
  // item: [ leading, stream ]
  var streamSize = 0;
  var chunkCount = 0;
  const leading = item[0];
  self.emit('data', leading);
  chunkCount++;
  if (debug.enabled) {
    debug('new stream, chunk index %d\n%s', chunkCount, leading.toString());
  }
 
  var stream = item[1];
  stream.on('data', function (data) {
    self.emit('data', data);
    streamSize += leading.length;
    chunkCount++;
    if (debug.enabled) {
      if (data.length > 512) {
        debug('stream chunk, size %d, chunk index %d, stream size %d\n%s......   only show 512 bytes   ......',
          data.length, chunkCount, streamSize, hex(data.slice(0, 512)));
      } else {
        debug('stream chunk, size %d, chunk index %d, stream size %d\n%s',
          data.length, chunkCount, streamSize, hex(data));
      }
    }
  });
  stream.on('end', function () {
    self.emit('data', NEW_LINE_BUFFER);
    chunkCount++;
    debug('stream end, chunk index %d, stream size %d', chunkCount, streamSize);
    return process.nextTick(self.drain.bind(self));
  });
  stream.resume();
};
 
FormStream.prototype._emitStreamWithChunkSize = function (item, minChunkSize) {
  var self = this;
  // item: [ leading, stream ]
  var streamSize = 0;
  var chunkCount = 0;
  var bufferSize = 0;
  var buffers = [];
  const leading = item[0];
  buffers.push(leading);
  bufferSize += leading.length;
  if (debug.enabled) {
    debug('new stream, with min chunk size: %d\n%s', minChunkSize, leading.toString());
  }
 
  var stream = item[1];
  stream.on('data', function (data) {
    if (typeof data === 'string') {
      data = Buffer.from(data, 'utf-8');
    }
    buffers.push(data);
    bufferSize += data.length;
    streamSize += data.length;
    debug('got stream data size %d, buffer size %d, stream size %d',
      data.length, bufferSize, streamSize);
    if (bufferSize >= minChunkSize) {
      const chunk = Buffer.concat(buffers, bufferSize);
      buffers = [];
      bufferSize = 0;
      self.emit('data', chunk);
      chunkCount++;
      if (debug.enabled) {
        if (chunk.length > 512) {
          debug('stream chunk, size %d, chunk index %d, stream size %d\n%s......   only show 512 bytes   ......',
            chunk.length, chunkCount, streamSize, hex(chunk.slice(0, 512)));
        } else {
          debug('stream chunk, size %d, chunk index %d, stream size %d\n%s',
            chunk.length, chunkCount, streamSize, hex(chunk));
        }
      }
    }
  });
  stream.on('end', function () {
    buffers.push(NEW_LINE_BUFFER);
    bufferSize += NEW_LINE_BUFFER.length;
    const chunk = Buffer.concat(buffers, bufferSize);
    self.emit('data', chunk);
    chunkCount++;
    if (chunk.length > 512) {
      debug('stream end, size %d, chunk index %d, stream size %d\n%s......   only show 512 bytes   ......',
        chunk.length, chunkCount, streamSize, hex(chunk.slice(0, 512)));
    } else {
      debug('stream end, size %d, chunk index %d, stream size %d\n%s',
        chunk.length, chunkCount, streamSize, hex(chunk));
    }
    return process.nextTick(self.drain.bind(self));
  });
  stream.resume();
};
 
FormStream.prototype._emitEnd = function () {
  // ending format:
  //
  // --{boundary}--\r\n
  this.emit('data', this._endData);
  this.emit('end');
  if (debug.enabled) {
    debug('end boundary\n%s', this._endData.toString());
  }
};
 
FormStream.prototype.drain = function () {
  // debug('drain');
  this._emitBuffers();
 
  var item = this._streams.shift();
  if (item) {
    if (this._minChunkSize && this._minChunkSize > 0) {
      this._emitStreamWithChunkSize(item, this._minChunkSize);
    } else {
      this._emitStream(item);
    }
  } else {
    this._emitEnd();
  }
 
  return this;
};
 
FormStream.prototype.resume = function () {
  // debug('resume');
  this.paused = false;
 
  if (!this._draining) {
    this._draining = true;
    this.drain();
  }
 
  return this;
};
 
FormStream.prototype.close = FormStream.prototype.destroy = function () {
  this.emit('destroy');
  // debug('destroy or close');
};