Http.php 19 KB

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