Http.php 18 KB

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