Http.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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\Worker;
  17. /**
  18. * http protocol
  19. */
  20. class Http
  21. {
  22. /**
  23. * Check the integrity of the package.
  24. *
  25. * @param string $recv_buffer
  26. * @param TcpConnection $connection
  27. * @return int
  28. */
  29. public static function input($recv_buffer, TcpConnection $connection)
  30. {
  31. if (!strpos($recv_buffer, "\r\n\r\n")) {
  32. // Judge whether the package length exceeds the limit.
  33. if (strlen($recv_buffer) >= TcpConnection::$maxPackageSize) {
  34. $connection->close();
  35. return 0;
  36. }
  37. return 0;
  38. }
  39. list($header,) = explode("\r\n\r\n", $recv_buffer, 2);
  40. if (0 === strpos($recv_buffer, "POST")) {
  41. // find Content-Length
  42. $match = array();
  43. if (preg_match("/\r\nContent-Length: ?(\d+)/i", $header, $match)) {
  44. $content_length = $match[1];
  45. return $content_length + strlen($header) + 4;
  46. } else {
  47. return 0;
  48. }
  49. } elseif (0 === strpos($recv_buffer, "GET")) {
  50. return strlen($header) + 4;
  51. } else {
  52. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n", true);
  53. return 0;
  54. }
  55. }
  56. /**
  57. * Parse $_POST、$_GET、$_COOKIE.
  58. *
  59. * @param string $recv_buffer
  60. * @param TcpConnection $connection
  61. * @return array
  62. */
  63. public static function decode($recv_buffer, TcpConnection $connection)
  64. {
  65. // Init.
  66. $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
  67. $GLOBALS['HTTP_RAW_POST_DATA'] = '';
  68. // Clear cache.
  69. HttpCache::$header = array('Connection' => 'Connection: keep-alive');
  70. HttpCache::$instance = new HttpCache();
  71. // $_SERVER
  72. $_SERVER = array(
  73. 'QUERY_STRING' => '',
  74. 'REQUEST_METHOD' => '',
  75. 'REQUEST_URI' => '',
  76. 'SERVER_PROTOCOL' => '',
  77. 'SERVER_SOFTWARE' => 'workerman/'.Worker::VERSION,
  78. 'SERVER_NAME' => '',
  79. 'HTTP_HOST' => '',
  80. 'HTTP_USER_AGENT' => '',
  81. 'HTTP_ACCEPT' => '',
  82. 'HTTP_ACCEPT_LANGUAGE' => '',
  83. 'HTTP_ACCEPT_ENCODING' => '',
  84. 'HTTP_COOKIE' => '',
  85. 'HTTP_CONNECTION' => '',
  86. 'REMOTE_ADDR' => '',
  87. 'REMOTE_PORT' => '0',
  88. );
  89. // Parse headers.
  90. list($http_header, $http_body) = explode("\r\n\r\n", $recv_buffer, 2);
  91. $header_data = explode("\r\n", $http_header);
  92. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ',
  93. $header_data[0]);
  94. $http_post_boundary = '';
  95. unset($header_data[0]);
  96. foreach ($header_data as $content) {
  97. // \r\n\r\n
  98. if (empty($content)) {
  99. continue;
  100. }
  101. list($key, $value) = explode(':', $content, 2);
  102. $key = str_replace('-', '_', strtoupper($key));
  103. $value = trim($value);
  104. $_SERVER['HTTP_' . $key] = $value;
  105. switch ($key) {
  106. // HTTP_HOST
  107. case 'HOST':
  108. $tmp = explode(':', $value);
  109. $_SERVER['SERVER_NAME'] = $tmp[0];
  110. if (isset($tmp[1])) {
  111. $_SERVER['SERVER_PORT'] = $tmp[1];
  112. }
  113. break;
  114. // cookie
  115. case 'COOKIE':
  116. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  117. break;
  118. // content-type
  119. case 'CONTENT_TYPE':
  120. if (!preg_match('/boundary="?(\S+)"?/', $value, $match)) {
  121. $_SERVER['CONTENT_TYPE'] = $value;
  122. } else {
  123. $_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
  124. $http_post_boundary = '--' . $match[1];
  125. }
  126. break;
  127. case 'CONTENT_LENGTH':
  128. $_SERVER['CONTENT_LENGTH'] = $value;
  129. break;
  130. }
  131. }
  132. // Parse $_POST.
  133. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  134. if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'multipart/form-data') {
  135. self::parseUploadFiles($http_body, $http_post_boundary);
  136. } else {
  137. parse_str($http_body, $_POST);
  138. // $GLOBALS['HTTP_RAW_POST_DATA']
  139. $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
  140. }
  141. }
  142. // QUERY_STRING
  143. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  144. if ($_SERVER['QUERY_STRING']) {
  145. // $GET
  146. parse_str($_SERVER['QUERY_STRING'], $_GET);
  147. } else {
  148. $_SERVER['QUERY_STRING'] = '';
  149. }
  150. // REQUEST
  151. $_REQUEST = array_merge($_GET, $_POST);
  152. // REMOTE_ADDR REMOTE_PORT
  153. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  154. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  155. return array('get' => $_GET, 'post' => $_POST, 'cookie' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES);
  156. }
  157. /**
  158. * Http encode.
  159. *
  160. * @param string $content
  161. * @param TcpConnection $connection
  162. * @return string
  163. */
  164. public static function encode($content, TcpConnection $connection)
  165. {
  166. // Default http-code.
  167. if (!isset(HttpCache::$header['Http-Code'])) {
  168. $header = "HTTP/1.1 200 OK\r\n";
  169. } else {
  170. $header = HttpCache::$header['Http-Code'] . "\r\n";
  171. unset(HttpCache::$header['Http-Code']);
  172. }
  173. // Content-Type
  174. if (!isset(HttpCache::$header['Content-Type'])) {
  175. $header .= "Content-Type: text/html;charset=utf-8\r\n";
  176. }
  177. // other headers
  178. foreach (HttpCache::$header as $key => $item) {
  179. if ('Set-Cookie' === $key && is_array($item)) {
  180. foreach ($item as $it) {
  181. $header .= $it . "\r\n";
  182. }
  183. } else {
  184. $header .= $item . "\r\n";
  185. }
  186. }
  187. // header
  188. $header .= "Server: workerman/" . Worker::VERSION . "\r\nContent-Length: " . strlen($content) . "\r\n\r\n";
  189. // save session
  190. self::sessionWriteClose();
  191. // the whole http package
  192. return $header . $content;
  193. }
  194. /**
  195. * 设置http头
  196. *
  197. * @return bool|void
  198. */
  199. public static function header($content, $replace = true, $http_response_code = 0)
  200. {
  201. if (PHP_SAPI != 'cli') {
  202. return $http_response_code ? header($content, $replace, $http_response_code) : header($content, $replace);
  203. }
  204. if (strpos($content, 'HTTP') === 0) {
  205. $key = 'Http-Code';
  206. } else {
  207. $key = strstr($content, ":", true);
  208. if (empty($key)) {
  209. return false;
  210. }
  211. }
  212. if ('location' === strtolower($key) && !$http_response_code) {
  213. return self::header($content, true, 302);
  214. }
  215. if (isset(HttpCache::$codes[$http_response_code])) {
  216. HttpCache::$header['Http-Code'] = "HTTP/1.1 $http_response_code " . HttpCache::$codes[$http_response_code];
  217. if ($key === 'Http-Code') {
  218. return true;
  219. }
  220. }
  221. if ($key === 'Set-Cookie') {
  222. HttpCache::$header[$key][] = $content;
  223. } else {
  224. HttpCache::$header[$key] = $content;
  225. }
  226. return true;
  227. }
  228. /**
  229. * Remove header.
  230. *
  231. * @param string $name
  232. * @return void
  233. */
  234. public static function headerRemove($name)
  235. {
  236. if (PHP_SAPI != 'cli') {
  237. header_remove($name);
  238. return;
  239. }
  240. unset(HttpCache::$header[$name]);
  241. }
  242. /**
  243. * Set cookie.
  244. *
  245. * @param string $name
  246. * @param string $value
  247. * @param integer $maxage
  248. * @param string $path
  249. * @param string $domain
  250. * @param bool $secure
  251. * @param bool $HTTPOnly
  252. * @return bool|void
  253. */
  254. public static function setcookie(
  255. $name,
  256. $value = '',
  257. $maxage = 0,
  258. $path = '',
  259. $domain = '',
  260. $secure = false,
  261. $HTTPOnly = false
  262. ) {
  263. if (PHP_SAPI != 'cli') {
  264. return setcookie($name, $value, $maxage, $path, $domain, $secure, $HTTPOnly);
  265. }
  266. return self::header(
  267. 'Set-Cookie: ' . $name . '=' . rawurlencode($value)
  268. . (empty($domain) ? '' : '; Domain=' . $domain)
  269. . (empty($maxage) ? '' : '; Max-Age=' . $maxage)
  270. . (empty($path) ? '' : '; Path=' . $path)
  271. . (!$secure ? '' : '; Secure')
  272. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  273. }
  274. /**
  275. * sessionStart
  276. *
  277. * @return bool
  278. */
  279. public static function sessionStart()
  280. {
  281. if (PHP_SAPI != 'cli') {
  282. return session_start();
  283. }
  284. self::tryGcSessions();
  285. if (HttpCache::$instance->sessionStarted) {
  286. echo "already sessionStarted\n";
  287. return true;
  288. }
  289. HttpCache::$instance->sessionStarted = true;
  290. // Generate a SID.
  291. if (!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName])) {
  292. $file_name = tempnam(HttpCache::$sessionPath, 'ses');
  293. if (!$file_name) {
  294. return false;
  295. }
  296. HttpCache::$instance->sessionFile = $file_name;
  297. $session_id = substr(basename($file_name), strlen('ses'));
  298. return self::setcookie(
  299. HttpCache::$sessionName
  300. , $session_id
  301. , ini_get('session.cookie_lifetime')
  302. , ini_get('session.cookie_path')
  303. , ini_get('session.cookie_domain')
  304. , ini_get('session.cookie_secure')
  305. , ini_get('session.cookie_httponly')
  306. );
  307. }
  308. if (!HttpCache::$instance->sessionFile) {
  309. HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName];
  310. }
  311. // Read session from session file.
  312. if (HttpCache::$instance->sessionFile) {
  313. $raw = file_get_contents(HttpCache::$instance->sessionFile);
  314. if ($raw) {
  315. session_decode($raw);
  316. }
  317. }
  318. return true;
  319. }
  320. /**
  321. * Save session.
  322. *
  323. * @return bool
  324. */
  325. public static function sessionWriteClose()
  326. {
  327. if (PHP_SAPI != 'cli') {
  328. return session_write_close();
  329. }
  330. if (!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION)) {
  331. $session_str = session_encode();
  332. if ($session_str && HttpCache::$instance->sessionFile) {
  333. return file_put_contents(HttpCache::$instance->sessionFile, $session_str);
  334. }
  335. }
  336. return empty($_SESSION);
  337. }
  338. /**
  339. * End, like call exit in php-fpm.
  340. *
  341. * @param string $msg
  342. * @throws \Exception
  343. */
  344. public static function end($msg = '')
  345. {
  346. if (PHP_SAPI != 'cli') {
  347. exit($msg);
  348. }
  349. if ($msg) {
  350. echo $msg;
  351. }
  352. throw new \Exception('jump_exit');
  353. }
  354. /**
  355. * Get mime types.
  356. *
  357. * @return string
  358. */
  359. public static function getMimeTypesFile()
  360. {
  361. return __DIR__ . '/Http/mime.types';
  362. }
  363. /**
  364. * Parse $_FILES.
  365. *
  366. * @param string $http_body
  367. * @param string $http_post_boundary
  368. * @return void
  369. */
  370. protected static function parseUploadFiles($http_body, $http_post_boundary)
  371. {
  372. $http_body = substr($http_body, 0, strlen($http_body) - (strlen($http_post_boundary) + 4));
  373. $boundary_data_array = explode($http_post_boundary . "\r\n", $http_body);
  374. if ($boundary_data_array[0] === '') {
  375. unset($boundary_data_array[0]);
  376. }
  377. foreach ($boundary_data_array as $boundary_data_buffer) {
  378. list($boundary_header_buffer, $boundary_value) = explode("\r\n\r\n", $boundary_data_buffer, 2);
  379. // Remove \r\n from the end of buffer.
  380. $boundary_value = substr($boundary_value, 0, -2);
  381. foreach (explode("\r\n", $boundary_header_buffer) as $item) {
  382. list($header_key, $header_value) = explode(": ", $item);
  383. $header_key = strtolower($header_key);
  384. switch ($header_key) {
  385. case "content-disposition":
  386. // Is file data.
  387. if (preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match)) {
  388. // Parse $_FILES.
  389. $_FILES[] = array(
  390. 'file_name' => $match[1],
  391. 'file_data' => $boundary_value,
  392. 'file_size' => strlen($boundary_value),
  393. );
  394. continue;
  395. } // Is post field.
  396. else {
  397. // Parse $_POST.
  398. if (preg_match('/name="(.*?)"$/', $header_value, $match)) {
  399. $_POST[$match[1]] = $boundary_value;
  400. }
  401. }
  402. break;
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * Try GC sessions.
  409. *
  410. * @return void
  411. */
  412. public static function tryGcSessions()
  413. {
  414. if (HttpCache::$sessionGcProbability <= 0 ||
  415. HttpCache::$sessionGcDivisor <= 0 ||
  416. rand(1, HttpCache::$sessionGcDivisor) > HttpCache::$sessionGcProbability) {
  417. return;
  418. }
  419. $time_now = time();
  420. foreach(glob(HttpCache::$sessionPath.'/ses*') as $file) {
  421. if(is_file($file) && $time_now - filemtime($file) > HttpCache::$sessionGcMaxLifeTime) {
  422. unlink($file);
  423. }
  424. }
  425. }
  426. }
  427. /**
  428. * Http cache for the current http response.
  429. */
  430. class HttpCache
  431. {
  432. public static $codes = array(
  433. 100 => 'Continue',
  434. 101 => 'Switching Protocols',
  435. 200 => 'OK',
  436. 201 => 'Created',
  437. 202 => 'Accepted',
  438. 203 => 'Non-Authoritative Information',
  439. 204 => 'No Content',
  440. 205 => 'Reset Content',
  441. 206 => 'Partial Content',
  442. 300 => 'Multiple Choices',
  443. 301 => 'Moved Permanently',
  444. 302 => 'Found',
  445. 303 => 'See Other',
  446. 304 => 'Not Modified',
  447. 305 => 'Use Proxy',
  448. 306 => '(Unused)',
  449. 307 => 'Temporary Redirect',
  450. 400 => 'Bad Request',
  451. 401 => 'Unauthorized',
  452. 402 => 'Payment Required',
  453. 403 => 'Forbidden',
  454. 404 => 'Not Found',
  455. 405 => 'Method Not Allowed',
  456. 406 => 'Not Acceptable',
  457. 407 => 'Proxy Authentication Required',
  458. 408 => 'Request Timeout',
  459. 409 => 'Conflict',
  460. 410 => 'Gone',
  461. 411 => 'Length Required',
  462. 412 => 'Precondition Failed',
  463. 413 => 'Request Entity Too Large',
  464. 414 => 'Request-URI Too Long',
  465. 415 => 'Unsupported Media Type',
  466. 416 => 'Requested Range Not Satisfiable',
  467. 417 => 'Expectation Failed',
  468. 422 => 'Unprocessable Entity',
  469. 423 => 'Locked',
  470. 500 => 'Internal Server Error',
  471. 501 => 'Not Implemented',
  472. 502 => 'Bad Gateway',
  473. 503 => 'Service Unavailable',
  474. 504 => 'Gateway Timeout',
  475. 505 => 'HTTP Version Not Supported',
  476. );
  477. /**
  478. * @var HttpCache
  479. */
  480. public static $instance = null;
  481. public static $header = array();
  482. public static $sessionPath = '';
  483. public static $sessionName = '';
  484. public static $sessionGcProbability = 1;
  485. public static $sessionGcDivisor = 1000;
  486. public static $sessionGcMaxLifeTime = 1440;
  487. public $sessionStarted = false;
  488. public $sessionFile = '';
  489. public static function init()
  490. {
  491. self::$sessionName = ini_get('session.name');
  492. self::$sessionPath = session_save_path();
  493. if (!self::$sessionPath || strpos(self::$sessionPath, 'tcp://') === 0) {
  494. self::$sessionPath = sys_get_temp_dir();
  495. }
  496. if ($gc_probability = ini_get('session.gc_probability')) {
  497. self::$sessionGcProbability = $gc_probability;
  498. }
  499. if ($gc_divisor = ini_get('session.gc_divisor')) {
  500. self::$sessionGcDivisor = $gc_divisor;
  501. }
  502. if ($gc_max_life_time = ini_get('session.gc_maxlifetime')) {
  503. self::$sessionGcMaxLifeTime = $gc_max_life_time;
  504. }
  505. @\session_start();
  506. }
  507. }
  508. HttpCache::init();