Debian Codegraph @

vendor/react/http/src/Io/MultipartParser.php

raw
1 <?php
2
3 namespace React\Http\Io;
4
5 use Psr\Http\Message\ServerRequestInterface;
6 use RingCentral\Psr7;
7
8 /**
9 * [Internal] Parses a string body with "Content-Type: multipart/form-data" into structured data
10 *
11 * This is use internally to parse incoming request bodies into structured data
12 * that resembles PHP's `$_POST` and `$_FILES` superglobals.
13 *
14 * @internal
15 * @link https://tools.ietf.org/html/rfc7578
16 * @link https://tools.ietf.org/html/rfc2046#section-5.1.1
17 */
18 final class MultipartParser
19 {
20 /**
21 * @var ServerRequestInterface|null
22 */
23 private $request;
24
25 /**
26 * @var int|null
27 */
28 private $maxFileSize;
29
30 /**
31 * ini setting "max_input_vars"
32 *
33 * Does not exist in PHP < 5.3.9 or HHVM, so assume PHP's default 1000 here.
34 *
35 * @var int
36 * @link http://php.net/manual/en/info.configuration.php#ini.max-input-vars
37 */
38 private $maxInputVars = 1000;
39
40 /**
41 * ini setting "max_input_nesting_level"
42 *
43 * Does not exist in HHVM, but assumes hard coded to 64 (PHP's default).
44 *
45 * @var int
46 * @link http://php.net/manual/en/info.configuration.php#ini.max-input-nesting-level
47 */
48 private $maxInputNestingLevel = 64;
49
50 /**
51 * ini setting "upload_max_filesize"
52 *
53 * @var int
54 */
55 private $uploadMaxFilesize;
56
57 /**
58 * ini setting "max_file_uploads"
59 *
60 * Additionally, setting "file_uploads = off" effectively sets this to zero.
61 *
62 * @var int
63 */
64 private $maxFileUploads;
65
66 private $postCount = 0;
67 private $filesCount = 0;
68 private $emptyCount = 0;
69
70 /**
71 * @param int|string|null $uploadMaxFilesize
72 * @param int|null $maxFileUploads
73 */
74 public function __construct($uploadMaxFilesize = null, $maxFileUploads = null)
75 {
76 $var = \ini_get('max_input_vars');
77 if ($var !== false) {
78 $this->maxInputVars = (int)$var;
79 }
80 $var = \ini_get('max_input_nesting_level');
81 if ($var !== false) {
82 $this->maxInputNestingLevel = (int)$var;
83 }
84
85 if ($uploadMaxFilesize === null) {
86 $uploadMaxFilesize = \ini_get('upload_max_filesize');
87 }
88
89 $this->uploadMaxFilesize = IniUtil::iniSizeToBytes($uploadMaxFilesize);
90 $this->maxFileUploads = $maxFileUploads === null ? (\ini_get('file_uploads') === '' ? 0 : (int)\ini_get('max_file_uploads')) : (int)$maxFileUploads;
91 }
92
93 public function parse(ServerRequestInterface $request)
94 {
95 $contentType = $request->getHeaderLine('content-type');
96 if(!\preg_match('/boundary="?(.*?)"?$/', $contentType, $matches)) {
97 return $request;
98 }
99
100 $this->request = $request;
101 $this->parseBody('--' . $matches[1], (string)$request->getBody());
102
103 $request = $this->request;
104 $this->request = null;
105 $this->postCount = 0;
106 $this->filesCount = 0;
107 $this->emptyCount = 0;
108 $this->maxFileSize = null;
109
110 return $request;
111 }
112
113 private function parseBody($boundary, $buffer)
114 {
115 $len = \strlen($boundary);
116
117 // ignore everything before initial boundary (SHOULD be empty)
118 $start = \strpos($buffer, $boundary . "\r\n");
119
120 while ($start !== false) {
121 // search following boundary (preceded by newline)
122 // ignore last if not followed by boundary (SHOULD end with "--")
123 $start += $len + 2;
124 $end = \strpos($buffer, "\r\n" . $boundary, $start);
125 if ($end === false) {
126 break;
127 }
128
129 // parse one part and continue searching for next
130 $this->parsePart(\substr($buffer, $start, $end - $start));
131 $start = $end;
132 }
133 }
134
135 private function parsePart($chunk)
136 {
137 $pos = \strpos($chunk, "\r\n\r\n");
138 if ($pos === false) {
139 return;
140 }
141
142 $headers = $this->parseHeaders((string)substr($chunk, 0, $pos));
143 $body = (string)\substr($chunk, $pos + 4);
144
145 if (!isset($headers['content-disposition'])) {
146 return;
147 }
148
149 $name = $this->getParameterFromHeader($headers['content-disposition'], 'name');
150 if ($name === null) {
151 return;
152 }
153
154 $filename = $this->getParameterFromHeader($headers['content-disposition'], 'filename');
155 if ($filename !== null) {
156 $this->parseFile(
157 $name,
158 $filename,
159 isset($headers['content-type'][0]) ? $headers['content-type'][0] : null,
160 $body
161 );
162 } else {
163 $this->parsePost($name, $body);
164 }
165 }
166
167 private function parseFile($name, $filename, $contentType, $contents)
168 {
169 $file = $this->parseUploadedFile($filename, $contentType, $contents);
170 if ($file === null) {
171 return;
172 }
173
174 $this->request = $this->request->withUploadedFiles($this->extractPost(
175 $this->request->getUploadedFiles(),
176 $name,
177 $file
178 ));
179 }
180
181 private function parseUploadedFile($filename, $contentType, $contents)
182 {
183 $size = \strlen($contents);
184
185 // no file selected (zero size and empty filename)
186 if ($size === 0 && $filename === '') {
187 // ignore excessive number of empty file uploads
188 if (++$this->emptyCount + $this->filesCount > $this->maxInputVars) {
189 return;
190 }
191
192 return new UploadedFile(
193 Psr7\stream_for(),
194 $size,
195 \UPLOAD_ERR_NO_FILE,
196 $filename,
197 $contentType
198 );
199 }
200
201 // ignore excessive number of file uploads
202 if (++$this->filesCount > $this->maxFileUploads) {
203 return;
204 }
205
206 // file exceeds "upload_max_filesize" ini setting
207 if ($size > $this->uploadMaxFilesize) {
208 return new UploadedFile(
209 Psr7\stream_for(),
210 $size,
211 \UPLOAD_ERR_INI_SIZE,
212 $filename,
213 $contentType
214 );
215 }
216
217 // file exceeds MAX_FILE_SIZE value
218 if ($this->maxFileSize !== null && $size > $this->maxFileSize) {
219 return new UploadedFile(
220 Psr7\stream_for(),
221 $size,
222 \UPLOAD_ERR_FORM_SIZE,
223 $filename,
224 $contentType
225 );
226 }
227
228 return new UploadedFile(
229 Psr7\stream_for($contents),
230 $size,
231 \UPLOAD_ERR_OK,
232 $filename,
233 $contentType
234 );
235 }
236
237 private function parsePost($name, $value)
238 {
239 // ignore excessive number of post fields
240 if (++$this->postCount > $this->maxInputVars) {
241 return;
242 }
243
244 $this->request = $this->request->withParsedBody($this->extractPost(
245 $this->request->getParsedBody(),
246 $name,
247 $value
248 ));
249
250 if (\strtoupper($name) === 'MAX_FILE_SIZE') {
251 $this->maxFileSize = (int)$value;
252
253 if ($this->maxFileSize === 0) {
254 $this->maxFileSize = null;
255 }
256 }
257 }
258
259 private function parseHeaders($header)
260 {
261 $headers = array();
262
263 foreach (\explode("\r\n", \trim($header)) as $line) {
264 $parts = \explode(':', $line, 2);
265 if (!isset($parts[1])) {
266 continue;
267 }
268
269 $key = \strtolower(trim($parts[0]));
270 $values = \explode(';', $parts[1]);
271 $values = \array_map('trim', $values);
272 $headers[$key] = $values;
273 }
274
275 return $headers;
276 }
277
278 private function getParameterFromHeader(array $header, $parameter)
279 {
280 foreach ($header as $part) {
281 if (\preg_match('/' . $parameter . '="?(.*?)"?$/', $part, $matches)) {
282 return $matches[1];
283 }
284 }
285
286 return null;
287 }
288
289 private function extractPost($postFields, $key, $value)
290 {
291 $chunks = \explode('[', $key);
292 if (\count($chunks) == 1) {
293 $postFields[$key] = $value;
294 return $postFields;
295 }
296
297 // ignore this key if maximum nesting level is exceeded
298 if (isset($chunks[$this->maxInputNestingLevel])) {
299 return $postFields;
300 }
301
302 $chunkKey = \rtrim($chunks[0], ']');
303 $parent = &$postFields;
304 for ($i = 1; isset($chunks[$i]); $i++) {
305 $previousChunkKey = $chunkKey;
306
307 if ($previousChunkKey === '') {
308 $parent[] = array();
309 \end($parent);
310 $parent = &$parent[\key($parent)];
311 } else {
312 if (!isset($parent[$previousChunkKey]) || !\is_array($parent[$previousChunkKey])) {
313 $parent[$previousChunkKey] = array();
314 }
315 $parent = &$parent[$previousChunkKey];
316 }
317
318 $chunkKey = \rtrim($chunks[$i], ']');
319 }
320
321 if ($chunkKey === '') {
322 $parent[] = $value;
323 } else {
324 $parent[$chunkKey] = $value;
325 }
326
327 return $postFields;
328 }
329 }