Http.php 10 KB

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