Http.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. declare(strict_types=1);
  15. namespace Workerman\Protocols;
  16. use Workerman\Connection\TcpConnection;
  17. use Workerman\Protocols\Http\Request;
  18. use Workerman\Protocols\Http\Response;
  19. use function clearstatcache;
  20. use function explode;
  21. use function filesize;
  22. use function fopen;
  23. use function fread;
  24. use function fseek;
  25. use function ftell;
  26. use function in_array;
  27. use function ini_get;
  28. use function is_array;
  29. use function is_object;
  30. use function preg_match;
  31. use function strlen;
  32. use function strpos;
  33. use function strstr;
  34. use function substr;
  35. use function sys_get_temp_dir;
  36. /**
  37. * Class Http.
  38. * @package Workerman\Protocols
  39. */
  40. class Http
  41. {
  42. /**
  43. * Request class name.
  44. *
  45. * @var string
  46. */
  47. protected static string $requestClass = Request::class;
  48. /**
  49. * Upload tmp dir.
  50. *
  51. * @var string
  52. */
  53. protected static string $uploadTmpDir = '';
  54. /**
  55. * Get or set the request class name.
  56. *
  57. * @param class-string|null $className
  58. * @return string
  59. */
  60. public static function requestClass(?string $className = null): string
  61. {
  62. if ($className !== null) {
  63. static::$requestClass = $className;
  64. }
  65. return static::$requestClass;
  66. }
  67. /**
  68. * Check the integrity of the package.
  69. *
  70. * @param string $buffer
  71. * @param TcpConnection $connection
  72. * @return int
  73. */
  74. public static function input(string $buffer, TcpConnection $connection): int
  75. {
  76. $crlfPos = strpos($buffer, "\r\n\r\n");
  77. if (false === $crlfPos) {
  78. // Judge whether the package length exceeds the limit.
  79. if (strlen($buffer) >= 16384) {
  80. $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
  81. }
  82. return 0;
  83. }
  84. $length = $crlfPos + 4;
  85. $method = strstr($buffer, ' ', true);
  86. if (!in_array($method, ['GET', 'POST', 'OPTIONS', 'HEAD', 'DELETE', 'PUT', 'PATCH'])) {
  87. $connection->close("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n", true);
  88. return 0;
  89. }
  90. $header = substr($buffer, 0, $crlfPos);
  91. if ($pos = strpos($header, "\r\nContent-Length: ")) {
  92. $length += (int)substr($header, $pos + 18, 10);
  93. $hasContentLength = true;
  94. } else if (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) {
  95. $length += (int)$match[1];
  96. $hasContentLength = true;
  97. } else {
  98. $hasContentLength = false;
  99. if (str_contains($header, "\r\nTransfer-Encoding:")) {
  100. $connection->close("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n", true);
  101. return 0;
  102. }
  103. }
  104. if ($hasContentLength && $length > $connection->maxPackageSize) {
  105. $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
  106. return 0;
  107. }
  108. return $length;
  109. }
  110. /**
  111. * Http decode.
  112. *
  113. * @param string $buffer
  114. * @param TcpConnection $connection
  115. * @return Request
  116. */
  117. public static function decode(string $buffer, TcpConnection $connection): Request
  118. {
  119. static $requests = [];
  120. if (isset($requests[$buffer])) {
  121. $request = $requests[$buffer];
  122. $request->connection = $connection;
  123. $connection->request = $request;
  124. $request->properties = [];
  125. return $request;
  126. }
  127. $request = new static::$requestClass($buffer);
  128. if (!isset($buffer[TcpConnection::MAX_CACHE_STRING_LENGTH])) {
  129. $requests[$buffer] = $request;
  130. if (\count($requests) > TcpConnection::MAX_CACHE_SIZE) {
  131. unset($requests[key($requests)]);
  132. }
  133. $request = clone $request;
  134. }
  135. $request->connection = $connection;
  136. $connection->request = $request;
  137. return $request;
  138. }
  139. /**
  140. * Http encode.
  141. *
  142. * @param string|Response $response
  143. * @param TcpConnection $connection
  144. * @return string
  145. */
  146. public static function encode(mixed $response, TcpConnection $connection): string
  147. {
  148. if (isset($connection->request)) {
  149. $request = $connection->request;
  150. $request->session = $request->connection = $connection->request = null;
  151. }
  152. if (!is_object($response)) {
  153. $extHeader = '';
  154. $contentType = 'text/html;charset=utf-8';
  155. foreach ($connection->headers as $name => $value) {
  156. if ($name === 'Content-Type') {
  157. $contentType = $value;
  158. continue;
  159. }
  160. if (is_array($value)) {
  161. foreach ($value as $item) {
  162. $extHeader .= "$name: $item\r\n";
  163. }
  164. } else {
  165. $extHeader .= "$name: $value\r\n";
  166. }
  167. }
  168. $connection->headers = [];
  169. $response = (string)$response;
  170. $bodyLen = strlen($response);
  171. return "HTTP/1.1 200 OK\r\nServer: workerman\r\n{$extHeader}Connection: keep-alive\r\nContent-Type: $contentType\r\nContent-Length: $bodyLen\r\n\r\n$response";
  172. }
  173. if ($connection->headers) {
  174. $response->withHeaders($connection->headers);
  175. $connection->headers = [];
  176. }
  177. if (isset($response->file)) {
  178. $file = $response->file['file'];
  179. $offset = $response->file['offset'];
  180. $length = $response->file['length'];
  181. clearstatcache();
  182. $fileSize = (int)filesize($file);
  183. $bodyLen = $length > 0 ? $length : $fileSize - $offset;
  184. $response->withHeaders([
  185. 'Content-Length' => $bodyLen,
  186. 'Accept-Ranges' => 'bytes',
  187. ]);
  188. if ($offset || $length) {
  189. $offsetEnd = $offset + $bodyLen - 1;
  190. $response->header('Content-Range', "bytes $offset-$offsetEnd/$fileSize");
  191. }
  192. if ($bodyLen < 2 * 1024 * 1024) {
  193. $connection->send($response . file_get_contents($file, false, null, $offset, $bodyLen), true);
  194. return '';
  195. }
  196. $handler = fopen($file, 'r');
  197. if (false === $handler) {
  198. $connection->close(new Response(403, [], '403 Forbidden'));
  199. return '';
  200. }
  201. $connection->send((string)$response, true);
  202. static::sendStream($connection, $handler, $offset, $length);
  203. return '';
  204. }
  205. return (string)$response;
  206. }
  207. /**
  208. * Send remainder of a stream to client.
  209. *
  210. * @param TcpConnection $connection
  211. * @param resource $handler
  212. * @param int $offset
  213. * @param int $length
  214. */
  215. protected static function sendStream(TcpConnection $connection, $handler, int $offset = 0, int $length = 0): void
  216. {
  217. $connection->context->bufferFull = false;
  218. $connection->context->streamSending = true;
  219. if ($offset !== 0) {
  220. fseek($handler, $offset);
  221. }
  222. $offsetEnd = $offset + $length;
  223. // Read file content from disk piece by piece and send to client.
  224. $doWrite = function () use ($connection, $handler, $length, $offsetEnd) {
  225. // Send buffer not full.
  226. while ($connection->context->bufferFull === false) {
  227. // Read from disk.
  228. $size = 1024 * 1024;
  229. if ($length !== 0) {
  230. $tell = ftell($handler);
  231. $remainSize = $offsetEnd - $tell;
  232. if ($remainSize <= 0) {
  233. fclose($handler);
  234. $connection->onBufferDrain = null;
  235. return;
  236. }
  237. $size = min($remainSize, $size);
  238. }
  239. $buffer = fread($handler, $size);
  240. // Read eof.
  241. if ($buffer === '' || $buffer === false) {
  242. fclose($handler);
  243. $connection->onBufferDrain = null;
  244. $connection->context->streamSending = false;
  245. return;
  246. }
  247. $connection->send($buffer, true);
  248. }
  249. };
  250. // Send buffer full.
  251. $connection->onBufferFull = function ($connection) {
  252. $connection->context->bufferFull = true;
  253. };
  254. // Send buffer drain.
  255. $connection->onBufferDrain = function ($connection) use ($doWrite) {
  256. $connection->context->bufferFull = false;
  257. $doWrite();
  258. };
  259. $doWrite();
  260. }
  261. /**
  262. * Set or get uploadTmpDir.
  263. *
  264. * @param string|null $dir
  265. * @return string
  266. */
  267. public static function uploadTmpDir(string|null $dir = null): string
  268. {
  269. if (null !== $dir) {
  270. static::$uploadTmpDir = $dir;
  271. }
  272. if (static::$uploadTmpDir === '') {
  273. if ($uploadTmpDir = ini_get('upload_tmp_dir')) {
  274. static::$uploadTmpDir = $uploadTmpDir;
  275. } else if ($uploadTmpDir = sys_get_temp_dir()) {
  276. static::$uploadTmpDir = $uploadTmpDir;
  277. }
  278. }
  279. return static::$uploadTmpDir;
  280. }
  281. }