Http.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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\Websocket;
  17. use Workerman\Worker;
  18. /**
  19. * http protocol
  20. */
  21. class Http
  22. {
  23. /**
  24. * The supported HTTP methods
  25. * @var array
  26. */
  27. public static $methods = array('GET'=>'GET', 'POST'=>'POST', 'PUT'=>'PUT', 'DELETE'=>'DELETE', 'HEAD'=>'HEAD', 'OPTIONS'=>'OPTIONS');
  28. /**
  29. * Cache.
  30. * @var array
  31. */
  32. protected static $_cache = [];
  33. /**
  34. * Check the integrity of the package.
  35. *
  36. * @param string $recv_buffer
  37. * @param TcpConnection $connection
  38. * @return int
  39. */
  40. public static function input($recv_buffer, TcpConnection $connection)
  41. {
  42. if (isset(static::$_cache[$recv_buffer]['input'])) {
  43. return static::$_cache[$recv_buffer]['input'];
  44. }
  45. $recv_len = \strlen($recv_buffer);
  46. $crlf_post = \strpos($recv_buffer, "\r\n\r\n");
  47. if (!$crlf_post) {
  48. // Judge whether the package length exceeds the limit.
  49. if ($recv_len >= $connection->maxPackageSize) {
  50. $connection->close();
  51. }
  52. return 0;
  53. }
  54. $method = \substr($recv_buffer, 0, \strpos($recv_buffer, ' '));
  55. if (!isset(static::$methods[$method])) {
  56. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n", true);
  57. $connection->consumeRecvBuffer($recv_len);
  58. return 0;
  59. }
  60. if ($method === 'GET' || $method === 'OPTIONS' || $method === 'HEAD') {
  61. static::$_cache[$recv_buffer]['input'] = $recv_len;
  62. return $recv_len;
  63. }
  64. $match = array();
  65. if (\preg_match("/\r\nContent-Length: ?(\d+)/i", $recv_buffer, $match)) {
  66. $content_length = isset($match[1]) ? $match[1] : 0;
  67. $total_length = $content_length + $crlf_post + 4;
  68. static::$_cache[$recv_buffer]['input'] = $total_length;
  69. return $total_length;
  70. }
  71. return $method === 'DELETE' ? $recv_len : 0;
  72. }
  73. /**
  74. * Parse $_POST、$_GET、$_COOKIE.
  75. *
  76. * @param string $recv_buffer
  77. * @param TcpConnection $connection
  78. * @return array
  79. */
  80. public static function decode($recv_buffer, TcpConnection $connection)
  81. {
  82. if (isset(static::$_cache[$recv_buffer]['decode'])) {
  83. HttpCache::reset();
  84. $cache = static::$_cache[$recv_buffer]['decode'];
  85. //$cache['server']['REQUEST_TIME_FLOAT'] = \microtime(true);
  86. //$cache['server']['REQUEST_TIME'] = (int)$cache['server']['REQUEST_TIME_FLOAT'];
  87. $_SERVER = $cache['server'];
  88. $_POST = $cache['post'];
  89. $_GET = $cache['get'];
  90. $_COOKIE = $cache['cookie'];
  91. $_REQUEST = $cache['request'];
  92. $GLOBALS['HTTP_RAW_POST_DATA'] = $GLOBALS['HTTP_RAW_REQUEST_DATA'] = '';
  93. return static::$_cache[$recv_buffer]['decode'];
  94. }
  95. // Init.
  96. $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
  97. $GLOBALS['HTTP_RAW_POST_DATA'] = '';
  98. // Clear cache.
  99. HttpCache::reset();
  100. //$microtime = \microtime(true);
  101. // $_SERVER
  102. $_SERVER = array(
  103. 'QUERY_STRING' => '',
  104. 'REQUEST_METHOD' => '',
  105. 'REQUEST_URI' => '',
  106. 'SERVER_PROTOCOL' => '',
  107. 'SERVER_SOFTWARE' => 'workerman/'.Worker::VERSION,
  108. 'SERVER_NAME' => '',
  109. 'HTTP_HOST' => '',
  110. 'HTTP_USER_AGENT' => '',
  111. 'HTTP_ACCEPT' => '',
  112. 'HTTP_ACCEPT_LANGUAGE' => '',
  113. 'HTTP_ACCEPT_ENCODING' => '',
  114. 'HTTP_COOKIE' => '',
  115. 'HTTP_CONNECTION' => '',
  116. 'CONTENT_TYPE' => '',
  117. 'REMOTE_ADDR' => '',
  118. 'REMOTE_PORT' => '0',
  119. //'REQUEST_TIME' => (int)$microtime,
  120. //'REQUEST_TIME_FLOAT' => $microtime //compatible php5.4
  121. );
  122. // Parse headers.
  123. list($http_header, $http_body) = \explode("\r\n\r\n", $recv_buffer, 2);
  124. $header_data = \explode("\r\n", $http_header);
  125. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = \explode(' ',
  126. $header_data[0]);
  127. $http_post_boundary = '';
  128. unset($header_data[0]);
  129. foreach ($header_data as $content) {
  130. // \r\n\r\n
  131. if (empty($content)) {
  132. continue;
  133. }
  134. list($key, $value) = \explode(':', $content, 2);
  135. $key = \str_replace('-', '_', strtoupper($key));
  136. $value = \trim($value);
  137. $_SERVER['HTTP_' . $key] = $value;
  138. switch ($key) {
  139. // HTTP_HOST
  140. case 'HOST':
  141. $tmp = \explode(':', $value);
  142. $_SERVER['SERVER_NAME'] = $tmp[0];
  143. if (isset($tmp[1])) {
  144. $_SERVER['SERVER_PORT'] = $tmp[1];
  145. }
  146. break;
  147. // cookie
  148. case 'COOKIE':
  149. \parse_str(\str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  150. break;
  151. // content-type
  152. case 'CONTENT_TYPE':
  153. if (!\preg_match('/boundary="?(\S+)"?/', $value, $match)) {
  154. if ($pos = \strpos($value, ';')) {
  155. $_SERVER['CONTENT_TYPE'] = \substr($value, 0, $pos);
  156. } else {
  157. $_SERVER['CONTENT_TYPE'] = $value;
  158. }
  159. } else {
  160. $_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
  161. $http_post_boundary = '--' . $match[1];
  162. }
  163. break;
  164. case 'CONTENT_LENGTH':
  165. $_SERVER['CONTENT_LENGTH'] = $value;
  166. break;
  167. case 'UPGRADE':
  168. if($value === 'websocket'){
  169. $connection->protocol = '\Workerman\Protocols\Websocket';
  170. return Websocket::input($recv_buffer,$connection);
  171. }
  172. break;
  173. }
  174. }
  175. // Parse $_POST.
  176. if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['CONTENT_TYPE']) {
  177. switch ($_SERVER['CONTENT_TYPE']) {
  178. case 'multipart/form-data':
  179. self::parseUploadFiles($http_body, $http_post_boundary);
  180. break;
  181. case 'application/json':
  182. $_POST = \json_decode($http_body, true);
  183. break;
  184. case 'application/x-www-form-urlencoded':
  185. \parse_str($http_body, $_POST);
  186. break;
  187. }
  188. }
  189. // Parse other HTTP action parameters
  190. if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== "POST") {
  191. $data = array();
  192. if ($_SERVER['CONTENT_TYPE'] === "application/x-www-form-urlencoded") {
  193. \parse_str($http_body, $data);
  194. } elseif ($_SERVER['CONTENT_TYPE'] === "application/json") {
  195. $data = \json_decode($http_body, true);
  196. }
  197. $_REQUEST = \array_merge($_REQUEST, $data);
  198. }
  199. // HTTP_RAW_REQUEST_DATA HTTP_RAW_POST_DATA
  200. $GLOBALS['HTTP_RAW_REQUEST_DATA'] = $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
  201. // QUERY_STRING
  202. $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], \PHP_URL_QUERY);
  203. if ($_SERVER['QUERY_STRING']) {
  204. // $GET
  205. \parse_str($_SERVER['QUERY_STRING'], $_GET);
  206. } else {
  207. $_SERVER['QUERY_STRING'] = '';
  208. }
  209. if (\is_array($_POST)) {
  210. // REQUEST
  211. $_REQUEST = \array_merge($_GET, $_POST, $_REQUEST);
  212. } else {
  213. // REQUEST
  214. $_REQUEST = \array_merge($_GET, $_REQUEST);
  215. }
  216. // REMOTE_ADDR REMOTE_PORT
  217. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  218. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  219. $ret = array('get' => $_GET, 'post' => $_POST, 'cookie' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES, 'request'=>$_REQUEST);
  220. if ($_SERVER['REQUEST_METHOD'] === 'GET') {
  221. static::$_cache[$recv_buffer]['decode'] = $ret;
  222. if (\count(static::$_cache) > 256) {
  223. unset(static::$_cache[key(static::$_cache)]);
  224. }
  225. }
  226. return $ret;
  227. }
  228. /**
  229. * Http encode.
  230. *
  231. * @param string $content
  232. * @param TcpConnection $connection
  233. * @return string
  234. */
  235. public static function encode($content, TcpConnection $connection)
  236. {
  237. // http-code status line.
  238. $header = HttpCache::$status . "\r\n";
  239. // Cookie headers
  240. if(HttpCache::$cookie) {
  241. $header .= \implode("\r\n", HttpCache::$cookie) . "\r\n";
  242. }
  243. // other headers
  244. if (HttpCache::$header) {
  245. $header .= \implode("\r\n", HttpCache::$header) . "\r\n";
  246. }
  247. if(!empty($connection->gzip)) {
  248. $header .= "Content-Encoding: gzip\r\n";
  249. $content = \gzencode($content,$connection->gzip);
  250. }
  251. // header
  252. $header .= 'Content-Length: ' . \strlen($content) . "\r\n\r\n";
  253. // save session
  254. self::sessionWriteClose();
  255. // the whole http package
  256. return $header . $content;
  257. }
  258. /**
  259. * Send a raw HTTP header
  260. *
  261. * @param string $content
  262. * @param bool $replace
  263. * @param int $http_response_code
  264. *
  265. * @return bool|void
  266. */
  267. public static function header($content, $replace = true, $http_response_code = null)
  268. {
  269. if (NO_CLI) {
  270. \header($content, $replace, $http_response_code);
  271. return;
  272. }
  273. if (\strpos($content, 'HTTP') === 0) {
  274. HttpCache::$status = $content;
  275. return true;
  276. }
  277. $key = \strstr($content, ':', true);
  278. if (empty($key)) {
  279. return false;
  280. }
  281. if ('location' === \strtolower($key)) {
  282. if (!$http_response_code) {
  283. $http_response_code = 302;
  284. }
  285. self::responseCode($http_response_code);
  286. }
  287. if ($key === 'Set-Cookie') {
  288. HttpCache::$cookie[] = $content;
  289. } else {
  290. HttpCache::$header[$key] = $content;
  291. }
  292. return true;
  293. }
  294. /**
  295. * Remove previously set headers
  296. *
  297. * @param string $name
  298. * @return void
  299. */
  300. public static function headerRemove($name)
  301. {
  302. if (NO_CLI) {
  303. \header_remove($name);
  304. return;
  305. }
  306. unset(HttpCache::$header[$name]);
  307. }
  308. /**
  309. * Sets the HTTP response status code.
  310. *
  311. * @param int $code The response code
  312. * @return boolean|int The valid status code or FALSE if code is not provided and it is not invoked in a web server environment
  313. */
  314. public static function responseCode($code)
  315. {
  316. if (NO_CLI) {
  317. return \http_response_code($code);
  318. }
  319. if (isset(HttpCache::$codes[$code])) {
  320. HttpCache::$status = "HTTP/1.1 $code " . HttpCache::$codes[$code];
  321. return $code;
  322. }
  323. return false;
  324. }
  325. /**
  326. * Set cookie.
  327. *
  328. * @param string $name
  329. * @param string $value
  330. * @param integer $maxage
  331. * @param string $path
  332. * @param string $domain
  333. * @param bool $secure
  334. * @param bool $HTTPOnly
  335. * @return bool|void
  336. */
  337. public static function setcookie(
  338. $name,
  339. $value = '',
  340. $maxage = 0,
  341. $path = '',
  342. $domain = '',
  343. $secure = false,
  344. $HTTPOnly = false
  345. ) {
  346. if (NO_CLI) {
  347. return \setcookie($name, $value, $maxage, $path, $domain, $secure, $HTTPOnly);
  348. }
  349. HttpCache::$cookie[] = 'Set-Cookie: ' . $name . '=' . rawurlencode($value)
  350. . (empty($domain) ? '' : '; Domain=' . $domain)
  351. . (empty($maxage) ? '' : '; Max-Age=' . $maxage)
  352. . (empty($path) ? '' : '; Path=' . $path)
  353. . (!$secure ? '' : '; Secure')
  354. . (!$HTTPOnly ? '' : '; HttpOnly');
  355. return true;
  356. }
  357. /**
  358. * sessionCreateId
  359. *
  360. * @return string
  361. */
  362. public static function sessionCreateId()
  363. {
  364. \mt_srand();
  365. return bin2hex(\pack('d', \microtime(true)) . \pack('N',\mt_rand(0, 2147483647)));
  366. }
  367. /**
  368. * Get and/or set the current session id
  369. *
  370. * @param string $id
  371. *
  372. * @return string|null
  373. */
  374. public static function sessionId($id = null)
  375. {
  376. if (NO_CLI) {
  377. return $id ? \session_id($id) : \session_id();
  378. }
  379. if (static::sessionStarted() && HttpCache::$instance->sessionFile) {
  380. return \str_replace('ses_', '', \basename(HttpCache::$instance->sessionFile));
  381. }
  382. return '';
  383. }
  384. /**
  385. * Get and/or set the current session name
  386. *
  387. * @param string $name
  388. *
  389. * @return string
  390. */
  391. public static function sessionName($name = null)
  392. {
  393. if (NO_CLI) {
  394. return $name ? \session_name($name) : \session_name();
  395. }
  396. $session_name = HttpCache::$sessionName;
  397. if ($name && ! static::sessionStarted()) {
  398. HttpCache::$sessionName = $name;
  399. }
  400. return $session_name;
  401. }
  402. /**
  403. * Get and/or set the current session save path
  404. *
  405. * @param string $path
  406. *
  407. * @return string
  408. */
  409. public static function sessionSavePath($path = null)
  410. {
  411. if (NO_CLI) {
  412. return $path ? \session_save_path($path) : \session_save_path();
  413. }
  414. if ($path && \is_dir($path) && \is_writable($path) && !static::sessionStarted()) {
  415. HttpCache::$sessionPath = $path;
  416. }
  417. return HttpCache::$sessionPath;
  418. }
  419. /**
  420. * sessionStarted
  421. *
  422. * @return bool
  423. */
  424. public static function sessionStarted()
  425. {
  426. if (!HttpCache::$instance) return false;
  427. return HttpCache::$instance->sessionStarted;
  428. }
  429. /**
  430. * sessionStart
  431. *
  432. * @return bool
  433. */
  434. public static function sessionStart()
  435. {
  436. if (NO_CLI) {
  437. return \session_start();
  438. }
  439. self::tryGcSessions();
  440. if (HttpCache::$instance->sessionStarted) {
  441. Worker::safeEcho("already sessionStarted\n");
  442. return true;
  443. }
  444. HttpCache::$instance->sessionStarted = true;
  445. // Generate a SID.
  446. if (!isset($_COOKIE[HttpCache::$sessionName]) || !\is_file(HttpCache::$sessionPath . '/ses_' . $_COOKIE[HttpCache::$sessionName])) {
  447. // Create a unique session_id and the associated file name.
  448. while (true) {
  449. $session_id = static::sessionCreateId();
  450. if (!\is_file($file_name = HttpCache::$sessionPath . '/ses_' . $session_id)) break;
  451. }
  452. HttpCache::$instance->sessionFile = $file_name;
  453. return self::setcookie(
  454. HttpCache::$sessionName
  455. , $session_id
  456. , \ini_get('session.cookie_lifetime')
  457. , \ini_get('session.cookie_path')
  458. , \ini_get('session.cookie_domain')
  459. , \ini_get('session.cookie_secure')
  460. , \ini_get('session.cookie_httponly')
  461. );
  462. }
  463. if (!HttpCache::$instance->sessionFile) {
  464. HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/ses_' . $_COOKIE[HttpCache::$sessionName];
  465. }
  466. // Read session from session file.
  467. if (HttpCache::$instance->sessionFile) {
  468. $raw = \file_get_contents(HttpCache::$instance->sessionFile);
  469. if ($raw) {
  470. $_SESSION = \unserialize($raw);
  471. }
  472. }
  473. return true;
  474. }
  475. /**
  476. * Save session.
  477. *
  478. * @return bool
  479. */
  480. public static function sessionWriteClose()
  481. {
  482. if (NO_CLI) {
  483. \session_write_close();
  484. return true;
  485. }
  486. if (!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION)) {
  487. $session_str = \serialize($_SESSION);
  488. if ($session_str && HttpCache::$instance->sessionFile) {
  489. return (bool) \file_put_contents(HttpCache::$instance->sessionFile, $session_str);
  490. }
  491. }
  492. return empty($_SESSION);
  493. }
  494. /**
  495. * End, like call exit in php-fpm.
  496. *
  497. * @param string $msg
  498. * @throws \Exception
  499. */
  500. public static function end($msg = '')
  501. {
  502. if (NO_CLI) {
  503. exit($msg);
  504. }
  505. if ($msg) {
  506. echo $msg;
  507. }
  508. throw new \Exception('jump_exit');
  509. }
  510. /**
  511. * Get mime types.
  512. *
  513. * @return string
  514. */
  515. public static function getMimeTypesFile()
  516. {
  517. return __DIR__ . '/Http/mime.types';
  518. }
  519. /**
  520. * Parse $_FILES.
  521. *
  522. * @param string $http_body
  523. * @param string $http_post_boundary
  524. * @return void
  525. */
  526. protected static function parseUploadFiles($http_body, $http_post_boundary)
  527. {
  528. $http_body = \substr($http_body, 0, \strlen($http_body) - (\strlen($http_post_boundary) + 4));
  529. $boundary_data_array = \explode($http_post_boundary . "\r\n", $http_body);
  530. if ($boundary_data_array[0] === '') {
  531. unset($boundary_data_array[0]);
  532. }
  533. $key = -1;
  534. foreach ($boundary_data_array as $boundary_data_buffer) {
  535. list($boundary_header_buffer, $boundary_value) = \explode("\r\n\r\n", $boundary_data_buffer, 2);
  536. // Remove \r\n from the end of buffer.
  537. $boundary_value = \substr($boundary_value, 0, -2);
  538. $key ++;
  539. foreach (\explode("\r\n", $boundary_header_buffer) as $item) {
  540. list($header_key, $header_value) = \explode(": ", $item);
  541. $header_key = \strtolower($header_key);
  542. switch ($header_key) {
  543. case "content-disposition":
  544. // Is file data.
  545. if (\preg_match('/name="(.*?)"; filename="(.*?)"$/', $header_value, $match)) {
  546. // Parse $_FILES.
  547. $_FILES[$key] = array(
  548. 'name' => $match[1],
  549. 'file_name' => $match[2],
  550. 'file_data' => $boundary_value,
  551. 'file_size' => \strlen($boundary_value),
  552. );
  553. break;
  554. } // Is post field.
  555. else {
  556. // Parse $_POST.
  557. if (\preg_match('/name="(.*?)"$/', $header_value, $match)) {
  558. $_POST[$match[1]] = $boundary_value;
  559. }
  560. }
  561. break;
  562. case "content-type":
  563. // add file_type
  564. $_FILES[$key]['file_type'] = \trim($header_value);
  565. break;
  566. }
  567. }
  568. }
  569. }
  570. /**
  571. * Try GC sessions.
  572. *
  573. * @return void
  574. */
  575. public static function tryGcSessions()
  576. {
  577. if (HttpCache::$sessionGcProbability <= 0 ||
  578. HttpCache::$sessionGcDivisor <= 0 ||
  579. \rand(1, HttpCache::$sessionGcDivisor) > HttpCache::$sessionGcProbability) {
  580. return;
  581. }
  582. $time_now = \time();
  583. foreach(glob(HttpCache::$sessionPath.'/ses*') as $file) {
  584. if(\is_file($file) && $time_now - \filemtime($file) > HttpCache::$sessionGcMaxLifeTime) {
  585. \unlink($file);
  586. }
  587. }
  588. }
  589. }
  590. /**
  591. * Http cache for the current http response.
  592. */
  593. class HttpCache
  594. {
  595. public static $codes = array(
  596. 100 => 'Continue',
  597. 101 => 'Switching Protocols',
  598. 200 => 'OK',
  599. 201 => 'Created',
  600. 202 => 'Accepted',
  601. 203 => 'Non-Authoritative Information',
  602. 204 => 'No Content',
  603. 205 => 'Reset Content',
  604. 206 => 'Partial Content',
  605. 300 => 'Multiple Choices',
  606. 301 => 'Moved Permanently',
  607. 302 => 'Found',
  608. 303 => 'See Other',
  609. 304 => 'Not Modified',
  610. 305 => 'Use Proxy',
  611. 306 => '(Unused)',
  612. 307 => 'Temporary Redirect',
  613. 400 => 'Bad Request',
  614. 401 => 'Unauthorized',
  615. 402 => 'Payment Required',
  616. 403 => 'Forbidden',
  617. 404 => 'Not Found',
  618. 405 => 'Method Not Allowed',
  619. 406 => 'Not Acceptable',
  620. 407 => 'Proxy Authentication Required',
  621. 408 => 'Request Timeout',
  622. 409 => 'Conflict',
  623. 410 => 'Gone',
  624. 411 => 'Length Required',
  625. 412 => 'Precondition Failed',
  626. 413 => 'Request Entity Too Large',
  627. 414 => 'Request-URI Too Long',
  628. 415 => 'Unsupported Media Type',
  629. 416 => 'Requested Range Not Satisfiable',
  630. 417 => 'Expectation Failed',
  631. 422 => 'Unprocessable Entity',
  632. 423 => 'Locked',
  633. 500 => 'Internal Server Error',
  634. 501 => 'Not Implemented',
  635. 502 => 'Bad Gateway',
  636. 503 => 'Service Unavailable',
  637. 504 => 'Gateway Timeout',
  638. 505 => 'HTTP Version Not Supported',
  639. );
  640. public static $default = array(
  641. 'Content-Type' => 'Content-Type: text/html;charset=utf-8',
  642. 'Connection' => 'Connection: keep-alive',
  643. 'Server' => 'Server: workerman'
  644. );
  645. /**
  646. * @var HttpCache
  647. */
  648. public static $instance = null;
  649. public static $status = '';
  650. public static $header = array();
  651. public static $cookie = array();
  652. public static $sessionPath = '';
  653. public static $sessionName = '';
  654. public static $sessionGcProbability = 1;
  655. public static $sessionGcDivisor = 1000;
  656. public static $sessionGcMaxLifeTime = 1440;
  657. public $sessionStarted = false;
  658. public $sessionFile = '';
  659. public static function reset()
  660. {
  661. self::$status = 'HTTP/1.1 200 OK';
  662. self::$header = self::$default;
  663. self::$cookie = array();
  664. self::$instance->sessionFile = '';
  665. self::$instance->sessionStarted = false;
  666. }
  667. public static function init()
  668. {
  669. if (!self::$sessionName) {
  670. self::$sessionName = \ini_get('session.name');
  671. }
  672. if (!self::$sessionPath) {
  673. self::$sessionPath = @\session_save_path();
  674. }
  675. if (!self::$sessionPath || \strpos(self::$sessionPath, 'tcp://') === 0) {
  676. self::$sessionPath = \sys_get_temp_dir();
  677. }
  678. if ($gc_probability = \ini_get('session.gc_probability')) {
  679. self::$sessionGcProbability = $gc_probability;
  680. }
  681. if ($gc_divisor = \ini_get('session.gc_divisor')) {
  682. self::$sessionGcDivisor = $gc_divisor;
  683. }
  684. if ($gc_max_life_time = \ini_get('session.gc_maxlifetime')) {
  685. self::$sessionGcMaxLifeTime = $gc_max_life_time;
  686. }
  687. self::$instance = new HttpCache();
  688. }
  689. }
  690. HttpCache::init();
  691. define('NO_CLI', \PHP_SAPI !== 'cli');