* The client sends a request with data. * * @private
(req: IncomingMessage, res: ServerResponse)
| 111 | * @private |
| 112 | */ |
| 113 | private onDataRequest(req: IncomingMessage, res: ServerResponse) { |
| 114 | if (this.dataReq) { |
| 115 | // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together' |
| 116 | this.onError("data request overlap from client"); |
| 117 | res.writeHead(400); |
| 118 | res.end(); |
| 119 | return; |
| 120 | } |
| 121 | |
| 122 | const isBinary = "application/octet-stream" === req.headers["content-type"]; |
| 123 | |
| 124 | if (isBinary && this.protocol === 4) { |
| 125 | this.onError("invalid content"); |
| 126 | return res.writeHead(400).end(); |
| 127 | } |
| 128 | |
| 129 | this.dataReq = req; |
| 130 | this.dataRes = res; |
| 131 | |
| 132 | let chunks = isBinary ? Buffer.concat([]) : ""; |
| 133 | |
| 134 | const cleanup = () => { |
| 135 | req.removeListener("data", onData); |
| 136 | req.removeListener("end", onEnd); |
| 137 | req.removeListener("close", onClose); |
| 138 | this.dataReq = this.dataRes = chunks = null; |
| 139 | }; |
| 140 | |
| 141 | const onClose = () => { |
| 142 | cleanup(); |
| 143 | this.onError("data request connection closed prematurely"); |
| 144 | }; |
| 145 | |
| 146 | const onData = (data) => { |
| 147 | let contentLength; |
| 148 | if (isBinary) { |
| 149 | chunks = Buffer.concat([chunks, data]); |
| 150 | contentLength = chunks.length; |
| 151 | } else { |
| 152 | chunks += data; |
| 153 | contentLength = Buffer.byteLength(chunks); |
| 154 | } |
| 155 | |
| 156 | if (contentLength > this.maxHttpBufferSize) { |
| 157 | res.writeHead(413).end(); |
| 158 | cleanup(); |
| 159 | } |
| 160 | }; |
| 161 | |
| 162 | const onEnd = () => { |
| 163 | this.onData(chunks); |
| 164 | |
| 165 | const headers = { |
| 166 | // text/html is required instead of text/plain to avoid an |
| 167 | // unwanted download dialog on certain user-agents (GH-43) |
| 168 | "Content-Type": "text/html", |
| 169 | "Content-Length": "2", |
| 170 | }; |