Http.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. /**
  17. * http protocol
  18. */
  19. class Http
  20. {
  21. /**
  22. * Check the integrity of the package.
  23. *
  24. * @param string $recv_buffer
  25. * @param TcpConnection $connection
  26. * @return int
  27. */
  28. public static function input($recv_buffer, TcpConnection $connection)
  29. {
  30. if (!strpos($recv_buffer, "\r\n\r\n")) {
  31. // Judge whether the package length exceeds the limit.
  32. if (strlen($recv_buffer) >= TcpConnection::$maxPackageSize) {
  33. $connection->close();
  34. return 0;
  35. }
  36. return 0;
  37. }
  38. list($header,) = explode("\r\n\r\n", $recv_buffer, 2);
  39. if (0 === strpos($recv_buffer, "POST")) {
  40. // find Content-Length
  41. $match = array();
  42. if (preg_match("/\r\nContent-Length: ?(\d+)/", $header, $match)) {
  43. $content_length = $match[1];
  44. return $content_length + strlen($header) + 4;
  45. } else {
  46. return 0;
  47. }
  48. } else {
  49. return strlen($header) + 4;
  50. }
  51. }
  52. /**
  53. * Parse $_POST、$_GET、$_COOKIE.
  54. *
  55. * @param string $recv_buffer
  56. * @param TcpConnection $connection
  57. * @return array
  58. */
  59. public static function decode($recv_buffer, TcpConnection $connection)
  60. {
  61. // Init.
  62. $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
  63. $GLOBALS['HTTP_RAW_POST_DATA'] = '';
  64. // Clear cache.
  65. HttpCache::$header = array('Connection' => 'Connection: keep-alive');
  66. HttpCache::$instance = new HttpCache();
  67. // $_SERVER
  68. $_SERVER = array(
  69. 'QUERY_STRING' => '',
  70. 'REQUEST_METHOD' => '',
  71. 'REQUEST_URI' => '',
  72. 'SERVER_PROTOCOL' => '',
  73. 'SERVER_SOFTWARE' => 'workerman/3.0',
  74. 'SERVER_NAME' => '',
  75. 'HTTP_HOST' => '',
  76. 'HTTP_USER_AGENT' => '',
  77. 'HTTP_ACCEPT' => '',
  78. 'HTTP_ACCEPT_LANGUAGE' => '',
  79. 'HTTP_ACCEPT_ENCODING' => '',
  80. 'HTTP_COOKIE' => '',
  81. 'HTTP_CONNECTION' => '',
  82. 'REMOTE_ADDR' => '',
  83. 'REMOTE_PORT' => '0',
  84. );
  85. // Parse headers.
  86. list($http_header, $http_body) = explode("\r\n\r\n", $recv_buffer, 2);
  87. $header_data = explode("\r\n", $http_header);
  88. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ',
  89. $header_data[0]);
  90. $http_post_boundary = '';
  91. unset($header_data[0]);
  92. foreach ($header_data as $content) {
  93. // \r\n\r\n
  94. if (empty($content)) {
  95. continue;
  96. }
  97. list($key, $value) = explode(':', $content, 2);
  98. $key = strtolower($key);
  99. $value = trim($value);
  100. switch ($key) {
  101. // HTTP_HOST
  102. case 'host':
  103. $_SERVER['HTTP_HOST'] = $value;
  104. $tmp = explode(':', $value);
  105. $_SERVER['SERVER_NAME'] = $tmp[0];
  106. if (isset($tmp[1])) {
  107. $_SERVER['SERVER_PORT'] = $tmp[1];
  108. }
  109. break;
  110. // cookie
  111. case 'cookie':
  112. $_SERVER['HTTP_COOKIE'] = $value;
  113. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  114. break;
  115. // user-agent
  116. case 'user-agent':
  117. $_SERVER['HTTP_USER_AGENT'] = $value;
  118. break;
  119. // accept
  120. case 'accept':
  121. $_SERVER['HTTP_ACCEPT'] = $value;
  122. break;
  123. // accept-language
  124. case 'accept-language':
  125. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $value;
  126. break;
  127. // accept-encoding
  128. case 'accept-encoding':
  129. $_SERVER['HTTP_ACCEPT_ENCODING'] = $value;
  130. break;
  131. // connection
  132. case 'connection':
  133. $_SERVER['HTTP_CONNECTION'] = $value;
  134. break;
  135. case 'referer':
  136. $_SERVER['HTTP_REFERER'] = $value;
  137. break;
  138. case 'if-modified-since':
  139. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $value;
  140. break;
  141. case 'if-none-match':
  142. $_SERVER['HTTP_IF_NONE_MATCH'] = $value;
  143. break;
  144. case 'content-type':
  145. if (!preg_match('/boundary="?(\S+)"?/', $value, $match)) {
  146. $_SERVER['CONTENT_TYPE'] = $value;
  147. } else {
  148. $_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
  149. $http_post_boundary = '--' . $match[1];
  150. }
  151. break;
  152. }
  153. }
  154. // Parse $_POST.
  155. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  156. if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'multipart/form-data') {
  157. self::parseUploadFiles($http_body, $http_post_boundary);
  158. } else {
  159. parse_str($http_body, $_POST);
  160. // $GLOBALS['HTTP_RAW_POST_DATA']
  161. $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
  162. }
  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/3.0\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. if (HttpCache::$instance->sessionStarted) {
  307. echo "already sessionStarted\nn";
  308. return true;
  309. }
  310. HttpCache::$instance->sessionStarted = true;
  311. // Generate a SID.
  312. if (!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName])) {
  313. $file_name = tempnam(HttpCache::$sessionPath, 'ses');
  314. if (!$file_name) {
  315. return false;
  316. }
  317. HttpCache::$instance->sessionFile = $file_name;
  318. $session_id = substr(basename($file_name), strlen('ses'));
  319. return self::setcookie(
  320. HttpCache::$sessionName
  321. , $session_id
  322. , ini_get('session.cookie_lifetime')
  323. , ini_get('session.cookie_path')
  324. , ini_get('session.cookie_domain')
  325. , ini_get('session.cookie_secure')
  326. , ini_get('session.cookie_httponly')
  327. );
  328. }
  329. if (!HttpCache::$instance->sessionFile) {
  330. HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName];
  331. }
  332. // Read session from session file.
  333. if (HttpCache::$instance->sessionFile) {
  334. $raw = file_get_contents(HttpCache::$instance->sessionFile);
  335. if ($raw) {
  336. session_decode($raw);
  337. }
  338. }
  339. }
  340. /**
  341. * Save session.
  342. *
  343. * @return bool
  344. */
  345. public static function sessionWriteClose()
  346. {
  347. if (PHP_SAPI != 'cli') {
  348. return session_write_close();
  349. }
  350. if (!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION)) {
  351. $session_str = session_encode();
  352. if ($session_str && HttpCache::$instance->sessionFile) {
  353. return file_put_contents(HttpCache::$instance->sessionFile, $session_str);
  354. }
  355. }
  356. return empty($_SESSION);
  357. }
  358. /**
  359. * End, like call exit in php-fpm.
  360. *
  361. * @param string $msg
  362. * @throws \Exception
  363. */
  364. public static function end($msg = '')
  365. {
  366. if (PHP_SAPI != 'cli') {
  367. exit($msg);
  368. }
  369. if ($msg) {
  370. echo $msg;
  371. }
  372. throw new \Exception('jump_exit');
  373. }
  374. /**
  375. * Get mime types.
  376. *
  377. * @return string
  378. */
  379. public static function getMimeTypesFile()
  380. {
  381. return __DIR__ . '/Http/mime.types';
  382. }
  383. /**
  384. * Parse $_FILES.
  385. *
  386. * @param string $http_body
  387. * @param string $http_post_boundary
  388. * @return void
  389. */
  390. protected static function parseUploadFiles($http_body, $http_post_boundary)
  391. {
  392. $http_body = substr($http_body, 0, strlen($http_body) - (strlen($http_post_boundary) + 4));
  393. $boundary_data_array = explode($http_post_boundary . "\r\n", $http_body);
  394. if ($boundary_data_array[0] === '') {
  395. unset($boundary_data_array[0]);
  396. }
  397. foreach ($boundary_data_array as $boundary_data_buffer) {
  398. list($boundary_header_buffer, $boundary_value) = explode("\r\n\r\n", $boundary_data_buffer, 2);
  399. // Remove \r\n from the end of buffer.
  400. $boundary_value = substr($boundary_value, 0, -2);
  401. foreach (explode("\r\n", $boundary_header_buffer) as $item) {
  402. list($header_key, $header_value) = explode(": ", $item);
  403. $header_key = strtolower($header_key);
  404. switch ($header_key) {
  405. case "content-disposition":
  406. // Is file data.
  407. if (preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match)) {
  408. // Parse $_FILES.
  409. $_FILES[] = array(
  410. 'file_name' => $match[1],
  411. 'file_data' => $boundary_value,
  412. 'file_size' => strlen($boundary_value),
  413. );
  414. continue;
  415. } // Is post field.
  416. else {
  417. // Parse $_POST.
  418. if (preg_match('/name="(.*?)"$/', $header_value, $match)) {
  419. $_POST[$match[1]] = $boundary_value;
  420. }
  421. }
  422. break;
  423. }
  424. }
  425. }
  426. }
  427. }
  428. /**
  429. * Http cache for the current http response.
  430. */
  431. class HttpCache
  432. {
  433. public static $codes = array(
  434. 100 => 'Continue',
  435. 101 => 'Switching Protocols',
  436. 200 => 'OK',
  437. 201 => 'Created',
  438. 202 => 'Accepted',
  439. 203 => 'Non-Authoritative Information',
  440. 204 => 'No Content',
  441. 205 => 'Reset Content',
  442. 206 => 'Partial Content',
  443. 300 => 'Multiple Choices',
  444. 301 => 'Moved Permanently',
  445. 302 => 'Found',
  446. 303 => 'See Other',
  447. 304 => 'Not Modified',
  448. 305 => 'Use Proxy',
  449. 306 => '(Unused)',
  450. 307 => 'Temporary Redirect',
  451. 400 => 'Bad Request',
  452. 401 => 'Unauthorized',
  453. 402 => 'Payment Required',
  454. 403 => 'Forbidden',
  455. 404 => 'Not Found',
  456. 405 => 'Method Not Allowed',
  457. 406 => 'Not Acceptable',
  458. 407 => 'Proxy Authentication Required',
  459. 408 => 'Request Timeout',
  460. 409 => 'Conflict',
  461. 410 => 'Gone',
  462. 411 => 'Length Required',
  463. 412 => 'Precondition Failed',
  464. 413 => 'Request Entity Too Large',
  465. 414 => 'Request-URI Too Long',
  466. 415 => 'Unsupported Media Type',
  467. 416 => 'Requested Range Not Satisfiable',
  468. 417 => 'Expectation Failed',
  469. 422 => 'Unprocessable Entity',
  470. 423 => 'Locked',
  471. 500 => 'Internal Server Error',
  472. 501 => 'Not Implemented',
  473. 502 => 'Bad Gateway',
  474. 503 => 'Service Unavailable',
  475. 504 => 'Gateway Timeout',
  476. 505 => 'HTTP Version Not Supported',
  477. );
  478. /**
  479. * @var HttpCache
  480. */
  481. public static $instance = null;
  482. public static $header = array();
  483. public static $sessionPath = '';
  484. public static $sessionName = '';
  485. public $sessionStarted = false;
  486. public $sessionFile = '';
  487. public static function init()
  488. {
  489. self::$sessionName = ini_get('session.name');
  490. self::$sessionPath = session_save_path();
  491. if (!self::$sessionPath) {
  492. self::$sessionPath = sys_get_temp_dir();
  493. }
  494. @\session_start();
  495. }
  496. }