Http.php 19 KB

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