Http.php 19 KB

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