|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace CrowdSecBouncer; |
| 6 | + |
| 7 | +/** |
| 8 | + * Helper trait for Bouncer. |
| 9 | + * |
| 10 | + * @author CrowdSec team |
| 11 | + * |
| 12 | + * @see https://crowdsec.net CrowdSec Official Website |
| 13 | + * |
| 14 | + * @copyright Copyright (c) 2021+ CrowdSec |
| 15 | + * @license MIT License |
| 16 | + */ |
| 17 | +trait Helper |
| 18 | +{ |
| 19 | + /** |
| 20 | + * Build the raw body from superglobals. |
| 21 | + * |
| 22 | + * @param int $maxBodySize the maximum body size in KB |
| 23 | + * @param resource $stream The stream to read |
| 24 | + * @param array $serverData the $_SERVER superglobal |
| 25 | + * @param array $postData the $_POST superglobal |
| 26 | + * @param array $filesData the $_FILES superglobal |
| 27 | + * |
| 28 | + * @return string the raw body |
| 29 | + * |
| 30 | + * @throws BouncerException |
| 31 | + */ |
| 32 | + private function buildRawBodyFromSuperglobals( |
| 33 | + int $maxBodySize, |
| 34 | + $stream, |
| 35 | + array $serverData = [], // $_SERVER |
| 36 | + array $postData = [], // $_POST |
| 37 | + array $filesData = [] // $_FILES |
| 38 | + ): string { |
| 39 | + $contentType = $serverData['CONTENT_TYPE'] ?? ''; |
| 40 | + // The threshold is the maximum body size converted in bytes + 1 |
| 41 | + $sizeThreshold = ($maxBodySize * 1024) + 1; |
| 42 | + |
| 43 | + if (false !== strpos($contentType, 'multipart/')) { |
| 44 | + return $this->getMultipartRawBody($contentType, $sizeThreshold, $postData, $filesData); |
| 45 | + } |
| 46 | + |
| 47 | + return $this->getRawInput($sizeThreshold, $stream); |
| 48 | + } |
| 49 | + |
| 50 | + private function appendFileData( |
| 51 | + array $fileArray, |
| 52 | + ?int $index, |
| 53 | + string $fileKey, |
| 54 | + string $boundary, |
| 55 | + int $threshold, |
| 56 | + int &$currentSize |
| 57 | + ): string { |
| 58 | + $fileName = is_array($fileArray['name']) ? $fileArray['name'][$index] : $fileArray['name']; |
| 59 | + $fileTmpName = is_array($fileArray['tmp_name']) ? $fileArray['tmp_name'][$index] : $fileArray['tmp_name']; |
| 60 | + $fileType = is_array($fileArray['type']) ? $fileArray['type'][$index] : $fileArray['type']; |
| 61 | + |
| 62 | + $headerPart = '--' . $boundary . "\r\n"; |
| 63 | + $headerPart .= "Content-Disposition: form-data; name=\"$fileKey\"; filename=\"$fileName\"\r\n"; |
| 64 | + $headerPart .= "Content-Type: $fileType\r\n\r\n"; |
| 65 | + |
| 66 | + $currentSize += strlen($headerPart); |
| 67 | + if ($currentSize >= $threshold) { |
| 68 | + return substr($headerPart, 0, $threshold - ($currentSize - strlen($headerPart))); |
| 69 | + } |
| 70 | + |
| 71 | + $remainingSize = $threshold - $currentSize; |
| 72 | + $fileStream = fopen($fileTmpName, 'rb'); |
| 73 | + $fileContent = $this->readStream($fileStream, $remainingSize); |
| 74 | + // Add 2 bytes for the \r\n at the end of the file content |
| 75 | + $currentSize += strlen($fileContent) + 2; |
| 76 | + |
| 77 | + return $headerPart . $fileContent . "\r\n"; |
| 78 | + } |
| 79 | + |
| 80 | + private function buildFormData(string $boundary, string $key, string $value): string |
| 81 | + { |
| 82 | + return '--' . $boundary . "\r\n" . |
| 83 | + "Content-Disposition: form-data; name=\"$key\"\r\n\r\n" . |
| 84 | + "$value\r\n"; |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Extract the boundary from the Content-Type. |
| 89 | + * |
| 90 | + * Regex breakdown: |
| 91 | + * /boundary="?([^;"]+)"?/i |
| 92 | + * |
| 93 | + * - boundary= : Matches the literal string 'boundary=' which indicates the start of the boundary parameter. |
| 94 | + * - "? : Matches an optional double quote that may surround the boundary value. |
| 95 | + * - ([^;"]+) : Captures one or more characters that are not a semicolon (;) or a double quote (") into a group. |
| 96 | + * This ensures the boundary is extracted accurately, stopping at a semicolon if present, |
| 97 | + * and avoiding the inclusion of quotes in the captured value. |
| 98 | + * - "? : Matches an optional closing double quote (if the boundary is quoted). |
| 99 | + * - i : Case-insensitive flag to handle 'boundary=' in any case (e.g., 'Boundary=' or 'BOUNDARY='). |
| 100 | + * |
| 101 | + * @throws BouncerException |
| 102 | + */ |
| 103 | + private function extractBoundary(string $contentType): string |
| 104 | + { |
| 105 | + if (preg_match('/boundary="?([^;"]+)"?/i', $contentType, $matches)) { |
| 106 | + return trim($matches[1]); |
| 107 | + } |
| 108 | + throw new BouncerException("Failed to extract boundary from Content-Type: ($contentType)"); |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Return the raw body for multipart requests. |
| 113 | + * This method will read the raw body up to the specified threshold. |
| 114 | + * If the body is too large, it will return a truncated version of the body up to the threshold. |
| 115 | + * |
| 116 | + * @throws BouncerException |
| 117 | + */ |
| 118 | + private function getMultipartRawBody( |
| 119 | + string $contentType, |
| 120 | + int $threshold, |
| 121 | + array $postData, |
| 122 | + array $filesData |
| 123 | + ): string { |
| 124 | + try { |
| 125 | + $boundary = $this->extractBoundary($contentType); |
| 126 | + // Instead of concatenating strings, we will use an array to store the parts |
| 127 | + // and then join them with implode at the end to avoid performance issues. |
| 128 | + $parts = []; |
| 129 | + $currentSize = 0; |
| 130 | + |
| 131 | + foreach ($postData as $key => $value) { |
| 132 | + $formData = $this->buildFormData($boundary, $key, $value); |
| 133 | + $currentSize += strlen($formData); |
| 134 | + if ($currentSize >= $threshold) { |
| 135 | + return substr(implode('', $parts) . $formData, 0, $threshold); |
| 136 | + } |
| 137 | + |
| 138 | + $parts[] = $formData; |
| 139 | + } |
| 140 | + |
| 141 | + foreach ($filesData as $fileKey => $fileArray) { |
| 142 | + $fileNames = is_array($fileArray['name']) ? $fileArray['name'] : [$fileArray['name']]; |
| 143 | + foreach ($fileNames as $index => $fileName) { |
| 144 | + $remainingSize = $threshold - $currentSize; |
| 145 | + $fileData = |
| 146 | + $this->appendFileData($fileArray, $index, $fileKey, $boundary, $remainingSize, $currentSize); |
| 147 | + if ($currentSize >= $threshold) { |
| 148 | + return substr(implode('', $parts) . $fileData, 0, $threshold); |
| 149 | + } |
| 150 | + $parts[] = $fileData; |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + $endBoundary = '--' . $boundary . "--\r\n"; |
| 155 | + $currentSize += strlen($endBoundary); |
| 156 | + |
| 157 | + if ($currentSize >= $threshold) { |
| 158 | + return substr(implode('', $parts) . $endBoundary, 0, $threshold); |
| 159 | + } |
| 160 | + |
| 161 | + $parts[] = $endBoundary; |
| 162 | + |
| 163 | + return implode('', $parts); |
| 164 | + } catch (\Throwable $e) { |
| 165 | + throw new BouncerException('Failed to read multipart raw body: ' . $e->getMessage()); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + private function getRawInput(int $threshold, $stream): string |
| 170 | + { |
| 171 | + return $this->readStream($stream, $threshold); |
| 172 | + } |
| 173 | + |
| 174 | + /** |
| 175 | + * Read the stream up to the specified threshold. |
| 176 | + * |
| 177 | + * @param resource $stream The stream to read |
| 178 | + * @param int $threshold The maximum number of bytes to read |
| 179 | + * |
| 180 | + * @throws BouncerException |
| 181 | + */ |
| 182 | + private function readStream($stream, int $threshold): string |
| 183 | + { |
| 184 | + if (!is_resource($stream)) { |
| 185 | + throw new BouncerException('Stream is not a valid resource'); |
| 186 | + } |
| 187 | + $buffer = ''; |
| 188 | + $chunkSize = 8192; |
| 189 | + $bytesRead = 0; |
| 190 | + // We make sure there won't be infinite loop |
| 191 | + $maxLoops = (int) ceil($threshold / $chunkSize); |
| 192 | + $loopCount = -1; |
| 193 | + |
| 194 | + try { |
| 195 | + while (!feof($stream) && $bytesRead < $threshold) { |
| 196 | + ++$loopCount; |
| 197 | + if ($loopCount >= $maxLoops) { |
| 198 | + throw new BouncerException("Too many loops ($loopCount) while reading stream"); |
| 199 | + } |
| 200 | + $remainingSize = $threshold - $bytesRead; |
| 201 | + $readLength = min($chunkSize, $remainingSize); |
| 202 | + |
| 203 | + $data = fread($stream, $readLength); |
| 204 | + if (false === $data) { |
| 205 | + throw new BouncerException('Failed to read chunk from stream'); |
| 206 | + } |
| 207 | + |
| 208 | + $buffer .= $data; |
| 209 | + $bytesRead += strlen($data); |
| 210 | + |
| 211 | + if ($bytesRead >= $threshold) { |
| 212 | + break; |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | + return $buffer; |
| 217 | + } catch (\Throwable $e) { |
| 218 | + throw new BouncerException('Failed to read stream: ' . $e->getMessage()); |
| 219 | + } finally { |
| 220 | + fclose($stream); |
| 221 | + } |
| 222 | + } |
| 223 | +} |
0 commit comments