|
| 1 | +/** |
| 2 | + * Port of: https://github.com/nachomazzara/parse-multipart-data/blob/master/src/multipart.ts |
| 3 | + * Includes few changes for Deno compatibility. Textdiff should show the changes. |
| 4 | + * Copied from master with commit 56052e860bc4e3fa7fe4763f69e88ec79b295a3c |
| 5 | + * |
| 6 | + * |
| 7 | + * Multipart Parser (Finite State Machine) |
| 8 | + * usage: |
| 9 | + * const multipart = require('./multipart.js'); |
| 10 | + * const body = multipart.DemoData(); // raw body |
| 11 | + * const body = Buffer.from(event['body-json'].toString(),'base64'); // AWS case |
| 12 | + * const boundary = multipart.getBoundary(event.params.header['content-type']); |
| 13 | + * const parts = multipart.Parse(body,boundary); |
| 14 | + * each part is: |
| 15 | + * { filename: 'A.txt', type: 'text/plain', data: <Buffer 41 41 41 41 42 42 42 42> } |
| 16 | + * or { name: 'key', data: <Buffer 41 41 41 41 42 42 42 42> } |
| 17 | + */ |
| 18 | + |
| 19 | +type Part = { |
| 20 | + contentDispositionHeader: string; |
| 21 | + contentTypeHeader: string; |
| 22 | + part: number[]; |
| 23 | +}; |
| 24 | + |
| 25 | +type Input = { |
| 26 | + filename?: string; |
| 27 | + name?: string; |
| 28 | + type: string; |
| 29 | + data: Uint8Array; |
| 30 | +}; |
| 31 | + |
| 32 | +enum ParsingState { |
| 33 | + INIT, |
| 34 | + READING_HEADERS, |
| 35 | + READING_DATA, |
| 36 | + READING_PART_SEPARATOR, |
| 37 | +} |
| 38 | + |
| 39 | +export function parse( |
| 40 | + multipartBodyBuffer: Uint8Array, |
| 41 | + boundary: string |
| 42 | +): Input[] { |
| 43 | + let lastline = ""; |
| 44 | + let contentDispositionHeader = ""; |
| 45 | + let contentTypeHeader = ""; |
| 46 | + let state: ParsingState = ParsingState.INIT; |
| 47 | + let buffer: number[] = []; |
| 48 | + const allParts: Input[] = []; |
| 49 | + |
| 50 | + let currentPartHeaders: string[] = []; |
| 51 | + |
| 52 | + for (let i = 0; i < multipartBodyBuffer.length; i++) { |
| 53 | + const oneByte: number = multipartBodyBuffer[i]; |
| 54 | + const prevByte: number | null = i > 0 ? multipartBodyBuffer[i - 1] : null; |
| 55 | + // 0x0a => \n |
| 56 | + // 0x0d => \r |
| 57 | + const newLineDetected: boolean = oneByte === 0x0a && prevByte === 0x0d; |
| 58 | + const newLineChar: boolean = oneByte === 0x0a || oneByte === 0x0d; |
| 59 | + |
| 60 | + if (!newLineChar) lastline += String.fromCharCode(oneByte); |
| 61 | + if (ParsingState.INIT === state && newLineDetected) { |
| 62 | + // searching for boundary |
| 63 | + if ("--" + boundary === lastline) { |
| 64 | + state = ParsingState.READING_HEADERS; // found boundary. start reading headers |
| 65 | + } |
| 66 | + lastline = ""; |
| 67 | + } else if (ParsingState.READING_HEADERS === state && newLineDetected) { |
| 68 | + // parsing headers. Headers are separated by an empty line from the content. Stop reading headers when the line is empty |
| 69 | + if (lastline.length) { |
| 70 | + currentPartHeaders.push(lastline); |
| 71 | + } else { |
| 72 | + // found empty line. search for the headers we want and set the values |
| 73 | + for (const h of currentPartHeaders) { |
| 74 | + if (h.toLowerCase().startsWith("content-disposition:")) { |
| 75 | + contentDispositionHeader = h; |
| 76 | + } else if (h.toLowerCase().startsWith("content-type:")) { |
| 77 | + contentTypeHeader = h; |
| 78 | + } |
| 79 | + } |
| 80 | + state = ParsingState.READING_DATA; |
| 81 | + buffer = []; |
| 82 | + } |
| 83 | + lastline = ""; |
| 84 | + } else if (ParsingState.READING_DATA === state) { |
| 85 | + // parsing data |
| 86 | + if (lastline.length > boundary.length + 4) { |
| 87 | + lastline = ""; // mem save |
| 88 | + } |
| 89 | + if ("--" + boundary === lastline) { |
| 90 | + const j = buffer.length - lastline.length; |
| 91 | + const part = buffer.slice(0, j - 1); |
| 92 | + |
| 93 | + allParts.push( |
| 94 | + process({ contentDispositionHeader, contentTypeHeader, part }) |
| 95 | + ); |
| 96 | + buffer = []; |
| 97 | + currentPartHeaders = []; |
| 98 | + lastline = ""; |
| 99 | + state = ParsingState.READING_PART_SEPARATOR; |
| 100 | + contentDispositionHeader = ""; |
| 101 | + contentTypeHeader = ""; |
| 102 | + } else { |
| 103 | + buffer.push(oneByte); |
| 104 | + } |
| 105 | + if (newLineDetected) { |
| 106 | + lastline = ""; |
| 107 | + } |
| 108 | + } else if (ParsingState.READING_PART_SEPARATOR === state) { |
| 109 | + if (newLineDetected) { |
| 110 | + state = ParsingState.READING_HEADERS; |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + return allParts; |
| 115 | +} |
| 116 | + |
| 117 | +// read the boundary from the content-type header sent by the http client |
| 118 | +// this value may be similar to: |
| 119 | +// 'multipart/form-data; boundary=----WebKitFormBoundaryvm5A9tzU1ONaGP5B', |
| 120 | +export function getBoundary(header: string): string { |
| 121 | + const items = header.split(";"); |
| 122 | + if (items) { |
| 123 | + for (let i = 0; i < items.length; i++) { |
| 124 | + const item = new String(items[i]).trim(); |
| 125 | + if (item.indexOf("boundary") >= 0) { |
| 126 | + const k = item.split("="); |
| 127 | + return new String(k[1]).trim().replace(/^["']|["']$/g, ""); |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + return ""; |
| 132 | +} |
| 133 | + |
| 134 | +export function DemoData(): { body: Uint8Array; boundary: string } { |
| 135 | + let body = "trash1\r\n"; |
| 136 | + body += "------WebKitFormBoundaryvef1fLxmoUdYZWXp\r\n"; |
| 137 | + body += "Content-Type: text/plain\r\n"; |
| 138 | + body += |
| 139 | + 'Content-Disposition: form-data; name="uploads[]"; filename="A.txt"\r\n'; |
| 140 | + body += "\r\n"; |
| 141 | + body += "@11X"; |
| 142 | + body += "111Y\r\n"; |
| 143 | + body += "111Z\rCCCC\nCCCC\r\nCCCCC@\r\n\r\n"; |
| 144 | + body += "------WebKitFormBoundaryvef1fLxmoUdYZWXp\r\n"; |
| 145 | + body += "Content-Type: text/plain\r\n"; |
| 146 | + body += |
| 147 | + 'Content-Disposition: form-data; name="uploads[]"; filename="B.txt"\r\n'; |
| 148 | + body += "\r\n"; |
| 149 | + body += "@22X"; |
| 150 | + body += "222Y\r\n"; |
| 151 | + body += "222Z\r222W\n2220\r\n666@\r\n"; |
| 152 | + body += "------WebKitFormBoundaryvef1fLxmoUdYZWXp\r\n"; |
| 153 | + body += 'Content-Disposition: form-data; name="input1"\r\n'; |
| 154 | + body += "\r\n"; |
| 155 | + body += "value1\r\n"; |
| 156 | + body += "------WebKitFormBoundaryvef1fLxmoUdYZWXp--\r\n"; |
| 157 | + |
| 158 | + return { |
| 159 | + body: new TextEncoder().encode(body), |
| 160 | + boundary: "----WebKitFormBoundaryvef1fLxmoUdYZWXp", |
| 161 | + }; |
| 162 | +} |
| 163 | + |
| 164 | +function process(part: Part): Input { |
| 165 | + // will transform this object: |
| 166 | + // { header: 'Content-Disposition: form-data; name="uploads[]"; filename="A.txt"', |
| 167 | + // info: 'Content-Type: text/plain', |
| 168 | + // part: 'AAAABBBB' } |
| 169 | + // into this one: |
| 170 | + // { filename: 'A.txt', type: 'text/plain', data: <Buffer 41 41 41 41 42 42 42 42> } |
| 171 | + const obj = function (str: string) { |
| 172 | + const k = str.split("="); |
| 173 | + const a = k[0].trim(); |
| 174 | + |
| 175 | + const b = JSON.parse(k[1].trim()); |
| 176 | + const o = {}; |
| 177 | + Object.defineProperty(o, a, { |
| 178 | + value: b, |
| 179 | + writable: true, |
| 180 | + enumerable: true, |
| 181 | + configurable: true, |
| 182 | + }); |
| 183 | + return o; |
| 184 | + }; |
| 185 | + const header = part.contentDispositionHeader.split(";"); |
| 186 | + |
| 187 | + const filenameData = header[2]; |
| 188 | + let input = {}; |
| 189 | + if (filenameData) { |
| 190 | + input = obj(filenameData); |
| 191 | + const contentType = part.contentTypeHeader.split(":")[1].trim(); |
| 192 | + Object.defineProperty(input, "type", { |
| 193 | + value: contentType, |
| 194 | + writable: true, |
| 195 | + enumerable: true, |
| 196 | + configurable: true, |
| 197 | + }); |
| 198 | + } |
| 199 | + // always process the name field |
| 200 | + Object.defineProperty(input, "name", { |
| 201 | + value: header[1].split("=")[1].replace(/"/g, ""), |
| 202 | + writable: true, |
| 203 | + enumerable: true, |
| 204 | + configurable: true, |
| 205 | + }); |
| 206 | + |
| 207 | + Object.defineProperty(input, "data", { |
| 208 | + value: new Uint8Array(part.part), |
| 209 | + writable: true, |
| 210 | + enumerable: true, |
| 211 | + configurable: true, |
| 212 | + }); |
| 213 | + return input as Input; |
| 214 | +} |
0 commit comments