Http.php 21 KB

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