2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-12-06 09:51:13 -05:00
|
|
|
import { equals, indexOf, lastIndexOf, startsWith } from "../bytes/mod.ts";
|
2019-02-10 18:49:48 -05:00
|
|
|
import { copyN } from "../io/ioutil.ts";
|
|
|
|
import { MultiReader } from "../io/readers.ts";
|
2019-10-16 14:39:33 -04:00
|
|
|
import { extname } from "../path/mod.ts";
|
2020-03-13 21:40:13 -04:00
|
|
|
import { BufReader, BufWriter } from "../io/bufio.ts";
|
2020-04-01 15:23:39 -04:00
|
|
|
import { encoder } from "../encoding/utf8.ts";
|
2020-06-07 09:20:33 -04:00
|
|
|
import { assert } from "../_util/assert.ts";
|
2019-05-23 22:04:06 -04:00
|
|
|
import { TextProtoReader } from "../textproto/mod.ts";
|
2020-05-09 08:34:47 -04:00
|
|
|
import { hasOwnProperty } from "../_util/has_own_property.ts";
|
2020-01-10 14:29:09 -05:00
|
|
|
|
|
|
|
/** FormFile object */
|
|
|
|
export interface FormFile {
|
|
|
|
/** filename */
|
|
|
|
filename: string;
|
|
|
|
/** content-type header value of file */
|
|
|
|
type: string;
|
|
|
|
/** byte size of file */
|
|
|
|
size: number;
|
|
|
|
/** in-memory content of file. Either content or tempfile is set */
|
|
|
|
content?: Uint8Array;
|
|
|
|
/** temporal file path.
|
|
|
|
* Set if file size is bigger than specified max-memory size at reading form
|
|
|
|
* */
|
|
|
|
tempfile?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Type guard for FormFile */
|
2020-11-03 10:19:29 -05:00
|
|
|
// deno-lint-ignore no-explicit-any
|
2020-01-10 14:29:09 -05:00
|
|
|
export function isFormFile(x: any): x is FormFile {
|
|
|
|
return hasOwnProperty(x, "filename") && hasOwnProperty(x, "type");
|
|
|
|
}
|
2019-02-10 18:49:48 -05:00
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
function randomBoundary(): string {
|
2019-02-10 18:49:48 -05:00
|
|
|
let boundary = "--------------------------";
|
|
|
|
for (let i = 0; i < 24; i++) {
|
2020-07-05 18:23:59 -04:00
|
|
|
boundary += Math.floor(Math.random() * 16).toString(16);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
return boundary;
|
|
|
|
}
|
|
|
|
|
2019-05-23 22:04:06 -04:00
|
|
|
/**
|
|
|
|
* 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.
|
|
|
|
*/
|
2019-03-04 19:53:35 -05:00
|
|
|
export function matchAfterPrefix(
|
2019-05-23 22:04:06 -04:00
|
|
|
buf: Uint8Array,
|
2019-03-04 19:53:35 -05:00
|
|
|
prefix: Uint8Array,
|
2020-07-14 15:24:17 -04:00
|
|
|
eof: boolean,
|
2019-05-23 22:04:06 -04:00
|
|
|
): -1 | 0 | 1 {
|
|
|
|
if (buf.length === prefix.length) {
|
|
|
|
return eof ? 1 : 0;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
const c = buf[prefix.length];
|
2019-03-04 19:53:35 -05:00
|
|
|
if (
|
|
|
|
c === " ".charCodeAt(0) ||
|
|
|
|
c === "\t".charCodeAt(0) ||
|
|
|
|
c === "\r".charCodeAt(0) ||
|
|
|
|
c === "\n".charCodeAt(0) ||
|
|
|
|
c === "-".charCodeAt(0)
|
|
|
|
) {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
2019-05-23 22:04:06 -04:00
|
|
|
/**
|
|
|
|
* 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.
|
|
|
|
*/
|
2019-03-04 19:53:35 -05:00
|
|
|
export function scanUntilBoundary(
|
|
|
|
buf: Uint8Array,
|
|
|
|
dashBoundary: Uint8Array,
|
|
|
|
newLineDashBoundary: Uint8Array,
|
|
|
|
total: number,
|
2020-07-14 15:24:17 -04:00
|
|
|
eof: boolean,
|
2020-04-28 12:40:43 -04:00
|
|
|
): number | null {
|
2019-03-04 19:53:35 -05:00
|
|
|
if (total === 0) {
|
2019-05-23 22:04:06 -04:00
|
|
|
// At beginning of body, allow dashBoundary.
|
2020-12-06 09:51:13 -05:00
|
|
|
if (startsWith(buf, dashBoundary)) {
|
2019-05-23 22:04:06 -04:00
|
|
|
switch (matchAfterPrefix(buf, dashBoundary, eof)) {
|
2019-03-04 19:53:35 -05:00
|
|
|
case -1:
|
2019-05-23 22:04:06 -04:00
|
|
|
return dashBoundary.length;
|
2019-03-04 19:53:35 -05:00
|
|
|
case 0:
|
2019-05-23 22:04:06 -04:00
|
|
|
return 0;
|
2019-03-04 19:53:35 -05:00
|
|
|
case 1:
|
2020-04-28 12:40:43 -04:00
|
|
|
return null;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
|
|
|
}
|
2020-12-06 09:51:13 -05:00
|
|
|
if (startsWith(dashBoundary, buf)) {
|
2019-05-23 22:04:06 -04:00
|
|
|
return 0;
|
|
|
|
}
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
|
|
|
|
// Search for "\n--boundary".
|
2020-12-06 09:51:13 -05:00
|
|
|
const i = indexOf(buf, newLineDashBoundary);
|
2019-03-04 19:53:35 -05:00
|
|
|
if (i >= 0) {
|
2019-05-23 22:04:06 -04:00
|
|
|
switch (matchAfterPrefix(buf.slice(i), newLineDashBoundary, eof)) {
|
2019-03-04 19:53:35 -05:00
|
|
|
case -1:
|
2019-05-23 22:04:06 -04:00
|
|
|
return i + newLineDashBoundary.length;
|
2019-03-04 19:53:35 -05:00
|
|
|
case 0:
|
2019-05-23 22:04:06 -04:00
|
|
|
return i;
|
2019-03-04 19:53:35 -05:00
|
|
|
case 1:
|
2020-04-28 12:40:43 -04:00
|
|
|
return i > 0 ? i : null;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
|
|
|
}
|
2020-12-06 09:51:13 -05:00
|
|
|
if (startsWith(newLineDashBoundary, buf)) {
|
2019-05-23 22:04:06 -04:00
|
|
|
return 0;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
|
|
|
|
// 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.
|
2020-12-06 09:51:13 -05:00
|
|
|
const j = lastIndexOf(buf, newLineDashBoundary.slice(0, 1));
|
|
|
|
if (j >= 0 && startsWith(newLineDashBoundary, buf.slice(j))) {
|
2019-05-23 22:04:06 -04:00
|
|
|
return j;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
|
|
|
|
2019-05-23 22:04:06 -04:00
|
|
|
return buf.length;
|
|
|
|
}
|
2019-03-04 19:53:35 -05:00
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
class PartReader implements Deno.Reader, Deno.Closer {
|
2020-04-28 12:40:43 -04:00
|
|
|
n: number | null = 0;
|
2019-10-05 12:02:34 -04:00
|
|
|
total = 0;
|
2019-03-04 19:53:35 -05:00
|
|
|
|
|
|
|
constructor(private mr: MultipartReader, public readonly headers: Headers) {}
|
|
|
|
|
2020-04-28 12:40:43 -04:00
|
|
|
async read(p: Uint8Array): Promise<number | null> {
|
2019-03-04 19:53:35 -05:00
|
|
|
const br = this.mr.bufReader;
|
2019-05-23 22:04:06 -04:00
|
|
|
|
|
|
|
// 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) {
|
2020-06-12 15:23:38 -04:00
|
|
|
peekLength = Math.max(peekLength, br.buffered());
|
2019-05-23 22:04:06 -04:00
|
|
|
const peekBuf = await br.peek(peekLength);
|
2020-04-28 12:40:43 -04:00
|
|
|
if (peekBuf === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
const eof = peekBuf.length < peekLength;
|
|
|
|
this.n = scanUntilBoundary(
|
|
|
|
peekBuf,
|
2019-03-04 19:53:35 -05:00
|
|
|
this.mr.dashBoundary,
|
|
|
|
this.mr.newLineDashBoundary,
|
|
|
|
this.total,
|
2020-07-14 15:24:17 -04:00
|
|
|
eof,
|
2019-03-04 19:53:35 -05:00
|
|
|
);
|
2019-05-23 22:04:06 -04:00
|
|
|
if (this.n === 0) {
|
|
|
|
// Force buffered I/O to read more into buffer.
|
2020-06-07 09:20:33 -04:00
|
|
|
assert(eof === false);
|
2019-05-23 22:04:06 -04:00
|
|
|
peekLength++;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-28 12:40:43 -04:00
|
|
|
if (this.n === null) {
|
|
|
|
return null;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
const nread = Math.min(p.length, this.n);
|
2019-05-23 22:04:06 -04:00
|
|
|
const buf = p.subarray(0, nread);
|
|
|
|
const r = await br.readFull(buf);
|
2020-06-07 09:20:33 -04:00
|
|
|
assert(r === buf);
|
2019-03-04 19:53:35 -05:00
|
|
|
this.n -= nread;
|
2019-05-23 22:04:06 -04:00
|
|
|
this.total += nread;
|
2019-07-07 15:20:41 -04:00
|
|
|
return nread;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
close(): void {}
|
|
|
|
|
2019-05-30 08:59:30 -04:00
|
|
|
private contentDisposition!: string;
|
|
|
|
private contentDispositionParams!: { [key: string]: string };
|
2019-03-04 19:53:35 -05:00
|
|
|
|
|
|
|
private getContentDispositionParams(): { [key: string]: string } {
|
|
|
|
if (this.contentDispositionParams) return this.contentDispositionParams;
|
|
|
|
const cd = this.headers.get("content-disposition");
|
2019-05-30 08:59:30 -04:00
|
|
|
const params: { [key: string]: string } = {};
|
2020-02-07 02:23:38 -05:00
|
|
|
assert(cd != null, "content-disposition must be set");
|
2020-05-19 14:22:26 -04:00
|
|
|
const comps = decodeURI(cd).split(";");
|
2019-03-04 19:53:35 -05:00
|
|
|
this.contentDisposition = comps[0];
|
|
|
|
comps
|
|
|
|
.slice(1)
|
2019-05-30 08:59:30 -04:00
|
|
|
.map((v: string): string => v.trim())
|
2019-11-13 13:42:34 -05:00
|
|
|
.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;
|
2019-03-04 19:53:35 -05:00
|
|
|
}
|
|
|
|
}
|
2019-11-13 13:42:34 -05:00
|
|
|
});
|
2019-03-04 19:53:35 -05:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2020-04-12 01:24:58 -04:00
|
|
|
export interface MultipartFormData {
|
2020-06-01 18:39:47 -04:00
|
|
|
file(key: string): FormFile | FormFile[] | undefined;
|
2020-04-12 01:24:58 -04:00
|
|
|
value(key: string): string | undefined;
|
2020-06-01 18:39:47 -04:00
|
|
|
entries(): IterableIterator<
|
|
|
|
[string, string | FormFile | FormFile[] | undefined]
|
|
|
|
>;
|
2020-04-12 01:24:58 -04:00
|
|
|
[Symbol.iterator](): IterableIterator<
|
2020-06-01 18:39:47 -04:00
|
|
|
[string, string | FormFile | FormFile[] | undefined]
|
2020-04-12 01:24:58 -04:00
|
|
|
>;
|
|
|
|
/** Remove all tempfiles */
|
|
|
|
removeAll(): Promise<void>;
|
|
|
|
}
|
|
|
|
|
2019-02-10 18:49:48 -05:00
|
|
|
/** 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;
|
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
constructor(reader: Deno.Reader, private boundary: string) {
|
2019-02-10 18:49:48 -05:00
|
|
|
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.
|
2020-02-07 02:23:38 -05:00
|
|
|
* String field values are never written to files.
|
|
|
|
* null value means parsing or writing to file was failed in some reason.
|
2020-05-17 06:31:19 -04:00
|
|
|
* @param maxMemory maximum memory size to store file in memory. bytes. @default 10485760 (10MB)
|
2020-02-07 02:23:38 -05:00
|
|
|
* */
|
2020-04-12 01:24:58 -04:00
|
|
|
async readForm(maxMemory = 10 << 20): Promise<MultipartFormData> {
|
2020-06-01 18:39:47 -04:00
|
|
|
const fileMap = new Map<string, FormFile | FormFile[]>();
|
2020-04-12 01:24:58 -04:00
|
|
|
const valueMap = new Map<string, string>();
|
2019-02-10 18:49:48 -05:00
|
|
|
let maxValueBytes = maxMemory + (10 << 20);
|
2020-06-12 15:23:38 -04:00
|
|
|
const buf = new Deno.Buffer(new Uint8Array(maxValueBytes));
|
2019-02-10 18:49:48 -05:00
|
|
|
for (;;) {
|
|
|
|
const p = await this.nextPart();
|
2020-04-28 12:40:43 -04:00
|
|
|
if (p === null) {
|
2019-02-10 18:49:48 -05:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (p.formName === "") {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
buf.reset();
|
|
|
|
if (!p.fileName) {
|
|
|
|
// value
|
2020-04-26 16:26:02 -04:00
|
|
|
const n = await copyN(p, buf, maxValueBytes);
|
2019-02-10 18:49:48 -05:00
|
|
|
maxValueBytes -= n;
|
|
|
|
if (maxValueBytes < 0) {
|
|
|
|
throw new RangeError("message too large");
|
|
|
|
}
|
2020-04-29 16:38:10 -04:00
|
|
|
const value = new TextDecoder().decode(buf.bytes());
|
2020-04-12 01:24:58 -04:00
|
|
|
valueMap.set(p.formName, value);
|
2019-02-10 18:49:48 -05:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// file
|
2020-06-01 18:39:47 -04:00
|
|
|
let formFile: FormFile | FormFile[] | undefined;
|
2020-04-29 16:38:24 -04:00
|
|
|
const n = await copyN(p, buf, maxValueBytes);
|
2020-02-07 02:23:38 -05:00
|
|
|
const contentType = p.headers.get("content-type");
|
|
|
|
assert(contentType != null, "content-type must be set");
|
2019-02-10 18:49:48 -05:00
|
|
|
if (n > maxMemory) {
|
|
|
|
// too big, write to disk and flush buffer
|
2019-05-23 22:04:06 -04:00
|
|
|
const ext = extname(p.fileName);
|
2020-10-20 07:51:57 -04:00
|
|
|
const filepath = await Deno.makeTempFile({
|
|
|
|
dir: ".",
|
2019-02-10 18:49:48 -05:00
|
|
|
prefix: "multipart-",
|
2020-10-20 07:51:57 -04:00
|
|
|
suffix: ext,
|
2019-02-10 18:49:48 -05:00
|
|
|
});
|
2020-10-20 07:51:57 -04:00
|
|
|
|
|
|
|
const file = await Deno.open(filepath, { write: true });
|
|
|
|
|
2019-02-10 18:49:48 -05:00
|
|
|
try {
|
2020-06-12 15:23:38 -04:00
|
|
|
const size = await Deno.copy(new MultiReader(buf, p), file);
|
2020-04-29 16:38:24 -04:00
|
|
|
|
2019-02-10 18:49:48 -05:00
|
|
|
file.close();
|
|
|
|
formFile = {
|
|
|
|
filename: p.fileName,
|
2020-02-07 02:23:38 -05:00
|
|
|
type: contentType,
|
2019-02-10 18:49:48 -05:00
|
|
|
tempfile: filepath,
|
2020-03-28 13:03:49 -04:00
|
|
|
size,
|
2019-02-10 18:49:48 -05:00
|
|
|
};
|
|
|
|
} catch (e) {
|
2020-06-12 15:23:38 -04:00
|
|
|
await Deno.remove(filepath);
|
2020-04-29 16:38:24 -04:00
|
|
|
throw e;
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
formFile = {
|
|
|
|
filename: p.fileName,
|
2020-02-07 02:23:38 -05:00
|
|
|
type: contentType,
|
2019-02-10 18:49:48 -05:00
|
|
|
content: buf.bytes(),
|
2020-03-28 13:03:49 -04:00
|
|
|
size: buf.length,
|
2019-02-10 18:49:48 -05:00
|
|
|
};
|
|
|
|
maxMemory -= n;
|
|
|
|
maxValueBytes -= n;
|
|
|
|
}
|
2020-04-12 01:24:58 -04:00
|
|
|
if (formFile) {
|
2020-06-01 18:39:47 -04:00
|
|
|
const mapVal = fileMap.get(p.formName);
|
|
|
|
if (mapVal !== undefined) {
|
|
|
|
if (Array.isArray(mapVal)) {
|
|
|
|
mapVal.push(formFile);
|
|
|
|
} else {
|
|
|
|
fileMap.set(p.formName, [mapVal, formFile]);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
fileMap.set(p.formName, formFile);
|
|
|
|
}
|
2020-04-12 01:24:58 -04:00
|
|
|
}
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
2020-04-12 01:24:58 -04:00
|
|
|
return multipatFormData(fileMap, valueMap);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
|
2019-05-30 08:59:30 -04:00
|
|
|
private currentPart: PartReader | undefined;
|
2019-10-05 12:02:34 -04:00
|
|
|
private partsRead = 0;
|
2019-02-10 18:49:48 -05:00
|
|
|
|
2020-04-28 12:40:43 -04:00
|
|
|
private async nextPart(): Promise<PartReader | null> {
|
2019-02-10 18:49:48 -05:00
|
|
|
if (this.currentPart) {
|
|
|
|
this.currentPart.close();
|
|
|
|
}
|
2020-12-06 09:51:13 -05:00
|
|
|
if (equals(this.dashBoundary, encoder.encode("--"))) {
|
2019-02-10 18:49:48 -05:00
|
|
|
throw new Error("boundary is empty");
|
|
|
|
}
|
|
|
|
let expectNewPart = false;
|
|
|
|
for (;;) {
|
2019-05-23 22:04:06 -04:00
|
|
|
const line = await this.bufReader.readSlice("\n".charCodeAt(0));
|
2020-04-28 12:40:43 -04:00
|
|
|
if (line === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
if (this.isBoundaryDelimiterLine(line)) {
|
|
|
|
this.partsRead++;
|
|
|
|
const r = new TextProtoReader(this.bufReader);
|
2019-05-23 22:04:06 -04:00
|
|
|
const headers = await r.readMIMEHeader();
|
2020-04-28 12:40:43 -04:00
|
|
|
if (headers === null) {
|
2020-03-13 21:40:13 -04:00
|
|
|
throw new Deno.errors.UnexpectedEof();
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
const np = new PartReader(this, headers);
|
|
|
|
this.currentPart = np;
|
|
|
|
return np;
|
|
|
|
}
|
|
|
|
if (this.isFinalBoundary(line)) {
|
2020-04-28 12:40:43 -04:00
|
|
|
return null;
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
if (expectNewPart) {
|
|
|
|
throw new Error(`expecting a new Part; got line ${line}`);
|
|
|
|
}
|
|
|
|
if (this.partsRead === 0) {
|
|
|
|
continue;
|
|
|
|
}
|
2020-12-06 09:51:13 -05:00
|
|
|
if (equals(line, this.newLine)) {
|
2019-02-10 18:49:48 -05:00
|
|
|
expectNewPart = true;
|
|
|
|
continue;
|
|
|
|
}
|
2019-05-23 22:04:06 -04:00
|
|
|
throw new Error(`unexpected line in nextPart(): ${line}`);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
private isFinalBoundary(line: Uint8Array): boolean {
|
2020-12-06 09:51:13 -05:00
|
|
|
if (!startsWith(line, this.dashBoundaryDash)) {
|
2019-02-10 18:49:48 -05:00
|
|
|
return false;
|
|
|
|
}
|
2019-10-05 12:02:34 -04:00
|
|
|
const rest = line.slice(this.dashBoundaryDash.length, line.length);
|
2020-12-06 09:51:13 -05:00
|
|
|
return rest.length === 0 || equals(skipLWSPChar(rest), this.newLine);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
private isBoundaryDelimiterLine(line: Uint8Array): boolean {
|
2020-12-06 09:51:13 -05:00
|
|
|
if (!startsWith(line, this.dashBoundary)) {
|
2019-02-10 18:49:48 -05:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
const rest = line.slice(this.dashBoundary.length);
|
2020-12-06 09:51:13 -05:00
|
|
|
return equals(skipLWSPChar(rest), this.newLine);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-12 01:24:58 -04:00
|
|
|
function multipatFormData(
|
2020-06-01 18:39:47 -04:00
|
|
|
fileMap: Map<string, FormFile | FormFile[]>,
|
2020-07-14 15:24:17 -04:00
|
|
|
valueMap: Map<string, string>,
|
2020-04-12 01:24:58 -04:00
|
|
|
): MultipartFormData {
|
2020-06-01 18:39:47 -04:00
|
|
|
function file(key: string): FormFile | FormFile[] | undefined {
|
2020-04-12 01:24:58 -04:00
|
|
|
return fileMap.get(key);
|
|
|
|
}
|
|
|
|
function value(key: string): string | undefined {
|
|
|
|
return valueMap.get(key);
|
|
|
|
}
|
|
|
|
function* entries(): IterableIterator<
|
2020-06-01 18:39:47 -04:00
|
|
|
[string, string | FormFile | FormFile[] | undefined]
|
2020-04-12 01:24:58 -04:00
|
|
|
> {
|
|
|
|
yield* fileMap;
|
|
|
|
yield* valueMap;
|
|
|
|
}
|
|
|
|
async function removeAll(): Promise<void> {
|
|
|
|
const promises: Array<Promise<void>> = [];
|
|
|
|
for (const val of fileMap.values()) {
|
2020-06-01 18:39:47 -04:00
|
|
|
if (Array.isArray(val)) {
|
|
|
|
for (const subVal of val) {
|
|
|
|
if (!subVal.tempfile) continue;
|
|
|
|
promises.push(Deno.remove(subVal.tempfile));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (!val.tempfile) continue;
|
|
|
|
promises.push(Deno.remove(val.tempfile));
|
|
|
|
}
|
2020-04-12 01:24:58 -04:00
|
|
|
}
|
|
|
|
await Promise.all(promises);
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
file,
|
|
|
|
value,
|
|
|
|
entries,
|
|
|
|
removeAll,
|
|
|
|
[Symbol.iterator](): IterableIterator<
|
2020-06-01 18:39:47 -04:00
|
|
|
[string, string | FormFile | FormFile[] | undefined]
|
2020-04-12 01:24:58 -04:00
|
|
|
> {
|
|
|
|
return entries();
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
class PartWriter implements Deno.Writer {
|
2019-02-10 18:49:48 -05:00
|
|
|
closed = false;
|
|
|
|
private readonly partHeader: string;
|
2019-10-05 12:02:34 -04:00
|
|
|
private headersWritten = false;
|
2019-02-10 18:49:48 -05:00
|
|
|
|
|
|
|
constructor(
|
2020-06-12 15:23:38 -04:00
|
|
|
private writer: Deno.Writer,
|
2019-02-10 18:49:48 -05:00
|
|
|
readonly boundary: string,
|
|
|
|
public headers: Headers,
|
2020-07-14 15:24:17 -04:00
|
|
|
isFirstBoundary: boolean,
|
2019-02-10 18:49:48 -05:00
|
|
|
) {
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
function checkBoundary(b: string): string {
|
2019-02-10 18:49:48 -05:00
|
|
|
if (b.length < 1 || b.length > 70) {
|
2019-03-04 19:53:35 -05:00
|
|
|
throw new Error(`invalid boundary length: ${b.length}`);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
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;
|
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
get boundary(): string {
|
2019-02-10 18:49:48 -05:00
|
|
|
return this._boundary;
|
|
|
|
}
|
|
|
|
|
2019-05-30 08:59:30 -04:00
|
|
|
private lastPart: PartWriter | undefined;
|
2019-02-10 18:49:48 -05:00
|
|
|
private bufWriter: BufWriter;
|
2019-10-05 12:02:34 -04:00
|
|
|
private isClosed = false;
|
2019-02-10 18:49:48 -05:00
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
constructor(private readonly writer: Deno.Writer, boundary?: string) {
|
2019-02-10 18:49:48 -05:00
|
|
|
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}`;
|
|
|
|
}
|
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
private createPart(headers: Headers): Deno.Writer {
|
2019-02-10 18:49:48 -05:00
|
|
|
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,
|
2020-07-14 15:24:17 -04:00
|
|
|
!this.lastPart,
|
2019-02-10 18:49:48 -05:00
|
|
|
);
|
|
|
|
this.lastPart = part;
|
|
|
|
return part;
|
|
|
|
}
|
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
createFormFile(field: string, filename: string): Deno.Writer {
|
2019-02-10 18:49:48 -05:00
|
|
|
const h = new Headers();
|
|
|
|
h.set(
|
|
|
|
"Content-Disposition",
|
2020-07-14 15:24:17 -04:00
|
|
|
`form-data; name="${field}"; filename="${filename}"`,
|
2019-02-10 18:49:48 -05:00
|
|
|
);
|
|
|
|
h.set("Content-Type", "application/octet-stream");
|
|
|
|
return this.createPart(h);
|
|
|
|
}
|
|
|
|
|
2020-06-12 15:23:38 -04:00
|
|
|
createFormField(field: string): Deno.Writer {
|
2019-02-10 18:49:48 -05:00
|
|
|
const h = new Headers();
|
|
|
|
h.set("Content-Disposition", `form-data; name="${field}"`);
|
|
|
|
h.set("Content-Type", "application/octet-stream");
|
|
|
|
return this.createPart(h);
|
|
|
|
}
|
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
async writeField(field: string, value: string): Promise<void> {
|
2019-02-10 18:49:48 -05:00
|
|
|
const f = await this.createFormField(field);
|
|
|
|
await f.write(encoder.encode(value));
|
|
|
|
}
|
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
async writeFile(
|
|
|
|
field: string,
|
|
|
|
filename: string,
|
2020-07-14 15:24:17 -04:00
|
|
|
file: Deno.Reader,
|
2019-03-04 19:53:35 -05:00
|
|
|
): Promise<void> {
|
2019-02-10 18:49:48 -05:00
|
|
|
const f = await this.createFormFile(field, filename);
|
2020-06-12 15:23:38 -04:00
|
|
|
await Deno.copy(file, f);
|
2019-02-10 18:49:48 -05:00
|
|
|
}
|
|
|
|
|
2019-05-23 22:04:06 -04:00
|
|
|
private flush(): Promise<void> {
|
2019-02-10 18:49:48 -05:00
|
|
|
return this.bufWriter.flush();
|
|
|
|
}
|
|
|
|
|
2020-05-14 00:38:42 -04:00
|
|
|
/** Close writer. No additional data can be written to stream */
|
2019-03-04 19:53:35 -05:00
|
|
|
async close(): Promise<void> {
|
2019-02-10 18:49:48 -05:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|