Http.php 10 KB

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