Http.php 10 KB

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