multipart.ts 14.5 KB
Newer Older
R
Ry Dahl 已提交
1
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
2

3
const { Buffer, copy, remove } = Deno;
4
const { min, max } = Math;
5 6 7
type Closer = Deno.Closer;
type Reader = Deno.Reader;
type Writer = Deno.Writer;
8
import { equal, findIndex, findLastIndex, hasPrefix } from "../bytes/mod.ts";
9 10
import { copyN } from "../io/ioutil.ts";
import { MultiReader } from "../io/readers.ts";
11 12
import { FormFile } from "../multipart/formfile.ts";
import { extname } from "../path/mod.ts";
13
import { tempFile } from "../io/util.ts";
14
import { BufReader, BufWriter, UnexpectedEOFError } from "../io/bufio.ts";
15
import { encoder } from "../strings/mod.ts";
16 17
import { assertStrictEq } from "../testing/asserts.ts";
import { TextProtoReader } from "../textproto/mod.ts";
18

19
function randomBoundary(): string {
20 21 22 23 24 25 26
  let boundary = "--------------------------";
  for (let i = 0; i < 24; i++) {
    boundary += Math.floor(Math.random() * 10).toString(16);
  }
  return boundary;
}

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/**
 * Checks whether `buf` should be considered to match the boundary.
 *
 * The prefix is "--boundary" or "\r\n--boundary" or "\n--boundary", and the
 * caller has verified already that `hasPrefix(buf, prefix)` is true.
 *
 * `matchAfterPrefix()` returns `1` if the buffer does match the boundary,
 * meaning the prefix is followed by a dash, space, tab, cr, nl, or EOF.
 *
 * It returns `-1` if the buffer definitely does NOT match the boundary,
 * meaning the prefix is followed by some other character.
 * For example, "--foobar" does not match "--foo".
 *
 * It returns `0` more input needs to be read to make the decision,
 * meaning that `buf.length` and `prefix.length` are the same.
 */
43
export function matchAfterPrefix(
44
  buf: Uint8Array,
45
  prefix: Uint8Array,
46 47 48 49
  eof: boolean
): -1 | 0 | 1 {
  if (buf.length === prefix.length) {
    return eof ? 1 : 0;
50
  }
51
  const c = buf[prefix.length];
52 53 54 55 56 57 58 59 60 61 62 63
  if (
    c === " ".charCodeAt(0) ||
    c === "\t".charCodeAt(0) ||
    c === "\r".charCodeAt(0) ||
    c === "\n".charCodeAt(0) ||
    c === "-".charCodeAt(0)
  ) {
    return 1;
  }
  return -1;
}

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/**
 * Scans `buf` to identify how much of it can be safely returned as part of the
 * `PartReader` body.
 *
 * @param buf - The buffer to search for boundaries.
 * @param dashBoundary - Is "--boundary".
 * @param newLineDashBoundary - Is "\r\n--boundary" or "\n--boundary", depending
 * on what mode we are in. The comments below (and the name) assume
 * "\n--boundary", but either is accepted.
 * @param total - The number of bytes read out so far. If total == 0, then a
 * leading "--boundary" is recognized.
 * @param eof - Whether `buf` contains the final bytes in the stream before EOF.
 * If `eof` is false, more bytes are expected to follow.
 * @returns The number of data bytes from buf that can be returned as part of
 * the `PartReader` body.
 */
80 81 82 83 84
export function scanUntilBoundary(
  buf: Uint8Array,
  dashBoundary: Uint8Array,
  newLineDashBoundary: Uint8Array,
  total: number,
85
  eof: boolean
86
): number | Deno.EOF {
87
  if (total === 0) {
88 89 90
    // At beginning of body, allow dashBoundary.
    if (hasPrefix(buf, dashBoundary)) {
      switch (matchAfterPrefix(buf, dashBoundary, eof)) {
91
        case -1:
92
          return dashBoundary.length;
93
        case 0:
94
          return 0;
95
        case 1:
96
          return Deno.EOF;
97 98
      }
    }
99 100 101
    if (hasPrefix(dashBoundary, buf)) {
      return 0;
    }
102
  }
103 104 105

  // Search for "\n--boundary".
  const i = findIndex(buf, newLineDashBoundary);
106
  if (i >= 0) {
107
    switch (matchAfterPrefix(buf.slice(i), newLineDashBoundary, eof)) {
108
      case -1:
109
        return i + newLineDashBoundary.length;
110
      case 0:
111
        return i;
112
      case 1:
113
        return i > 0 ? i : Deno.EOF;
114 115
    }
  }
116 117
  if (hasPrefix(newLineDashBoundary, buf)) {
    return 0;
118
  }
119 120 121 122 123 124 125

  // Otherwise, anything up to the final \n is not part of the boundary and so
  // must be part of the body. Also, if the section from the final \n onward is
  // not a prefix of the boundary, it too must be part of the body.
  const j = findLastIndex(buf, newLineDashBoundary.slice(0, 1));
  if (j >= 0 && hasPrefix(newLineDashBoundary, buf.slice(j))) {
    return j;
126 127
  }

128 129
  return buf.length;
}
130 131

class PartReader implements Reader, Closer {
132
  n: number | Deno.EOF = 0;
133
  total = 0;
134 135 136

  constructor(private mr: MultipartReader, public readonly headers: Headers) {}

137
  async read(p: Uint8Array): Promise<number | Deno.EOF> {
138
    const br = this.mr.bufReader;
139 140 141 142 143 144 145

    // Read into buffer until we identify some data to return,
    // or we find a reason to stop (boundary or EOF).
    let peekLength = 1;
    while (this.n === 0) {
      peekLength = max(peekLength, br.buffered());
      const peekBuf = await br.peek(peekLength);
146
      if (peekBuf === Deno.EOF) {
147
        throw new UnexpectedEOFError();
148
      }
149 150 151
      const eof = peekBuf.length < peekLength;
      this.n = scanUntilBoundary(
        peekBuf,
152 153 154
        this.mr.dashBoundary,
        this.mr.newLineDashBoundary,
        this.total,
155
        eof
156
      );
157 158 159 160
      if (this.n === 0) {
        // Force buffered I/O to read more into buffer.
        assertStrictEq(eof, false);
        peekLength++;
161 162 163
      }
    }

164 165
    if (this.n === Deno.EOF) {
      return Deno.EOF;
166
    }
167 168 169 170 171

    const nread = min(p.length, this.n);
    const buf = p.subarray(0, nread);
    const r = await br.readFull(buf);
    assertStrictEq(r, buf);
172
    this.n -= nread;
173
    this.total += nread;
174
    return nread;
175 176 177 178
  }

  close(): void {}

179 180
  private contentDisposition!: string;
  private contentDispositionParams!: { [key: string]: string };
181 182 183 184

  private getContentDispositionParams(): { [key: string]: string } {
    if (this.contentDispositionParams) return this.contentDispositionParams;
    const cd = this.headers.get("content-disposition");
185 186
    const params: { [key: string]: string } = {};
    const comps = cd!.split(";");
187 188 189
    this.contentDisposition = comps[0];
    comps
      .slice(1)
190
      .map((v: string): string => v.trim())
K
Kitson Kelly 已提交
191 192 193 194 195 196 197 198 199
      .map((kv: string): void => {
        const [k, v] = kv.split("=");
        if (v) {
          const s = v.charAt(0);
          const e = v.charAt(v.length - 1);
          if ((s === e && s === '"') || s === "'") {
            params[k] = v.substr(1, v.length - 2);
          } else {
            params[k] = v;
200 201
          }
        }
K
Kitson Kelly 已提交
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
    return (this.contentDispositionParams = params);
  }

  get fileName(): string {
    return this.getContentDispositionParams()["filename"];
  }

  get formName(): string {
    const p = this.getContentDispositionParams();
    if (this.contentDisposition === "form-data") {
      return p["name"];
    }
    return "";
  }
}

function skipLWSPChar(u: Uint8Array): Uint8Array {
  const ret = new Uint8Array(u.length);
  const sp = " ".charCodeAt(0);
  const ht = "\t".charCodeAt(0);
  let j = 0;
  for (let i = 0; i < u.length; i++) {
    if (u[i] === sp || u[i] === ht) continue;
    ret[j++] = u[i];
  }
  return ret.slice(0, j);
}

231 232 233 234 235 236 237 238
/** Reader for parsing multipart/form-data */
export class MultipartReader {
  readonly newLine = encoder.encode("\r\n");
  readonly newLineDashBoundary = encoder.encode(`\r\n--${this.boundary}`);
  readonly dashBoundaryDash = encoder.encode(`--${this.boundary}--`);
  readonly dashBoundary = encoder.encode(`--${this.boundary}`);
  readonly bufReader: BufReader;

239
  constructor(reader: Reader, private boundary: string) {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    this.bufReader = new BufReader(reader);
  }

  /** Read all form data from stream.
   * If total size of stored data in memory exceed maxMemory,
   * overflowed file data will be written to temporal files.
   * String field values are never written to files */
  async readForm(
    maxMemory: number
  ): Promise<{ [key: string]: string | FormFile }> {
    const result = Object.create(null);
    let maxValueBytes = maxMemory + (10 << 20);
    const buf = new Buffer(new Uint8Array(maxValueBytes));
    for (;;) {
      const p = await this.nextPart();
255
      if (p === Deno.EOF) {
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        break;
      }
      if (p.formName === "") {
        continue;
      }
      buf.reset();
      if (!p.fileName) {
        // value
        const n = await copyN(buf, p, maxValueBytes);
        maxValueBytes -= n;
        if (maxValueBytes < 0) {
          throw new RangeError("message too large");
        }
        const value = buf.toString();
        result[p.formName] = value;
        continue;
      }
      // file
      let formFile: FormFile;
      const n = await copy(buf, p);
      if (n > maxMemory) {
        // too big, write to disk and flush buffer
278
        const ext = extname(p.fileName);
279 280 281 282 283 284 285 286 287 288 289 290 291
        const { file, filepath } = await tempFile(".", {
          prefix: "multipart-",
          postfix: ext
        });
        try {
          const size = await copyN(
            file,
            new MultiReader(buf, p),
            maxValueBytes
          );
          file.close();
          formFile = {
            filename: p.fileName,
292
            type: p.headers.get("content-type")!,
293 294 295 296 297 298 299 300 301
            tempfile: filepath,
            size
          };
        } catch (e) {
          await remove(filepath);
        }
      } else {
        formFile = {
          filename: p.fileName,
302
          type: p.headers.get("content-type")!,
303
          content: buf.bytes(),
304
          size: buf.length
305 306 307 308
        };
        maxMemory -= n;
        maxValueBytes -= n;
      }
309
      result[p.formName] = formFile!;
310 311 312 313
    }
    return result;
  }

314
  private currentPart: PartReader | undefined;
315
  private partsRead = 0;
316

317
  private async nextPart(): Promise<PartReader | Deno.EOF> {
318 319 320
    if (this.currentPart) {
      this.currentPart.close();
    }
321
    if (equal(this.dashBoundary, encoder.encode("--"))) {
322 323 324 325
      throw new Error("boundary is empty");
    }
    let expectNewPart = false;
    for (;;) {
326
      const line = await this.bufReader.readSlice("\n".charCodeAt(0));
327
      if (line === Deno.EOF) {
328
        throw new UnexpectedEOFError();
329 330 331 332
      }
      if (this.isBoundaryDelimiterLine(line)) {
        this.partsRead++;
        const r = new TextProtoReader(this.bufReader);
333
        const headers = await r.readMIMEHeader();
334
        if (headers === Deno.EOF) {
335
          throw new UnexpectedEOFError();
336 337 338 339 340 341
        }
        const np = new PartReader(this, headers);
        this.currentPart = np;
        return np;
      }
      if (this.isFinalBoundary(line)) {
342
        return Deno.EOF;
343 344 345 346 347 348 349
      }
      if (expectNewPart) {
        throw new Error(`expecting a new Part; got line ${line}`);
      }
      if (this.partsRead === 0) {
        continue;
      }
350
      if (equal(line, this.newLine)) {
351 352 353
        expectNewPart = true;
        continue;
      }
354
      throw new Error(`unexpected line in nextPart(): ${line}`);
355 356 357
    }
  }

358
  private isFinalBoundary(line: Uint8Array): boolean {
359
    if (!hasPrefix(line, this.dashBoundaryDash)) {
360 361
      return false;
    }
362
    const rest = line.slice(this.dashBoundaryDash.length, line.length);
363
    return rest.length === 0 || equal(skipLWSPChar(rest), this.newLine);
364 365
  }

366
  private isBoundaryDelimiterLine(line: Uint8Array): boolean {
367
    if (!hasPrefix(line, this.dashBoundary)) {
368 369 370
      return false;
    }
    const rest = line.slice(this.dashBoundary.length);
371
    return equal(skipLWSPChar(rest), this.newLine);
372 373 374 375 376 377
  }
}

class PartWriter implements Writer {
  closed = false;
  private readonly partHeader: string;
378
  private headersWritten = false;
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

  constructor(
    private writer: Writer,
    readonly boundary: string,
    public headers: Headers,
    isFirstBoundary: boolean
  ) {
    let buf = "";
    if (isFirstBoundary) {
      buf += `--${boundary}\r\n`;
    } else {
      buf += `\r\n--${boundary}\r\n`;
    }
    for (const [key, value] of headers.entries()) {
      buf += `${key}: ${value}\r\n`;
    }
    buf += `\r\n`;
    this.partHeader = buf;
  }

  close(): void {
    this.closed = true;
  }

  async write(p: Uint8Array): Promise<number> {
    if (this.closed) {
      throw new Error("part is closed");
    }
    if (!this.headersWritten) {
      await this.writer.write(encoder.encode(this.partHeader));
      this.headersWritten = true;
    }
    return this.writer.write(p);
  }
}

415
function checkBoundary(b: string): string {
416
  if (b.length < 1 || b.length > 70) {
417
    throw new Error(`invalid boundary length: ${b.length}`);
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
  }
  const end = b.length - 1;
  for (let i = 0; i < end; i++) {
    const c = b.charAt(i);
    if (!c.match(/[a-zA-Z0-9'()+_,\-./:=?]/) || (c === " " && i !== end)) {
      throw new Error("invalid boundary character: " + c);
    }
  }
  return b;
}

/** Writer for creating multipart/form-data */
export class MultipartWriter {
  private readonly _boundary: string;

433
  get boundary(): string {
434 435 436
    return this._boundary;
  }

437
  private lastPart: PartWriter | undefined;
438
  private bufWriter: BufWriter;
439
  private isClosed = false;
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

  constructor(private readonly writer: Writer, boundary?: string) {
    if (boundary !== void 0) {
      this._boundary = checkBoundary(boundary);
    } else {
      this._boundary = randomBoundary();
    }
    this.bufWriter = new BufWriter(writer);
  }

  formDataContentType(): string {
    return `multipart/form-data; boundary=${this.boundary}`;
  }

  private createPart(headers: Headers): Writer {
    if (this.isClosed) {
      throw new Error("multipart: writer is closed");
    }
    if (this.lastPart) {
      this.lastPart.close();
    }
    const part = new PartWriter(
      this.writer,
      this.boundary,
      headers,
      !this.lastPart
    );
    this.lastPart = part;
    return part;
  }

  createFormFile(field: string, filename: string): Writer {
    const h = new Headers();
    h.set(
      "Content-Disposition",
      `form-data; name="${field}"; filename="${filename}"`
    );
    h.set("Content-Type", "application/octet-stream");
    return this.createPart(h);
  }

  createFormField(field: string): Writer {
    const h = new Headers();
    h.set("Content-Disposition", `form-data; name="${field}"`);
    h.set("Content-Type", "application/octet-stream");
    return this.createPart(h);
  }

488
  async writeField(field: string, value: string): Promise<void> {
489 490 491 492
    const f = await this.createFormField(field);
    await f.write(encoder.encode(value));
  }

493 494 495 496 497
  async writeFile(
    field: string,
    filename: string,
    file: Reader
  ): Promise<void> {
498 499 500 501
    const f = await this.createFormFile(field, filename);
    await copy(f, file);
  }

502
  private flush(): Promise<void> {
503 504 505 506
    return this.bufWriter.flush();
  }

  /** Close writer. No additional data can be writen to stream */
507
  async close(): Promise<void> {
508 509 510 511 512 513 514 515 516 517 518 519
    if (this.isClosed) {
      throw new Error("multipart: writer is closed");
    }
    if (this.lastPart) {
      this.lastPart.close();
      this.lastPart = void 0;
    }
    await this.writer.write(encoder.encode(`\r\n--${this.boundary}--\r\n`));
    await this.flush();
    this.isClosed = true;
  }
}