Http.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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+)/i", $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. case 'x-requested-with':
  153. $_SERVER["HTTP_X_REQUESTED_WITH"] = $value;
  154. break;
  155. }
  156. }
  157. // Parse $_POST.
  158. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  159. if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'multipart/form-data') {
  160. self::parseUploadFiles($http_body, $http_post_boundary);
  161. } else {
  162. parse_str($http_body, $_POST);
  163. // $GLOBALS['HTTP_RAW_POST_DATA']
  164. $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
  165. }
  166. }
  167. // QUERY_STRING
  168. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  169. if ($_SERVER['QUERY_STRING']) {
  170. // $GET
  171. parse_str($_SERVER['QUERY_STRING'], $_GET);
  172. } else {
  173. $_SERVER['QUERY_STRING'] = '';
  174. }
  175. // REQUEST
  176. $_REQUEST = array_merge($_GET, $_POST);
  177. // REMOTE_ADDR REMOTE_PORT
  178. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  179. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  180. return array('get' => $_GET, 'post' => $_POST, 'cookie' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES);
  181. }
  182. /**
  183. * Http encode.
  184. *
  185. * @param string $content
  186. * @param TcpConnection $connection
  187. * @return string
  188. */
  189. public static function encode($content, TcpConnection $connection)
  190. {
  191. // Default http-code.
  192. if (!isset(HttpCache::$header['Http-Code'])) {
  193. $header = "HTTP/1.1 200 OK\r\n";
  194. } else {
  195. $header = HttpCache::$header['Http-Code'] . "\r\n";
  196. unset(HttpCache::$header['Http-Code']);
  197. }
  198. // Content-Type
  199. if (!isset(HttpCache::$header['Content-Type'])) {
  200. $header .= "Content-Type: text/html;charset=utf-8\r\n";
  201. }
  202. // other headers
  203. foreach (HttpCache::$header as $key => $item) {
  204. if ('Set-Cookie' === $key && is_array($item)) {
  205. foreach ($item as $it) {
  206. $header .= $it . "\r\n";
  207. }
  208. } else {
  209. $header .= $item . "\r\n";
  210. }
  211. }
  212. // header
  213. $header .= "Server: WorkerMan/3.0\r\nContent-Length: " . strlen($content) . "\r\n\r\n";
  214. // save session
  215. self::sessionWriteClose();
  216. // the whole http package
  217. return $header . $content;
  218. }
  219. /**
  220. * 设置http头
  221. *
  222. * @return bool|void
  223. */
  224. public static function header($content, $replace = true, $http_response_code = 0)
  225. {
  226. if (PHP_SAPI != 'cli') {
  227. return $http_response_code ? header($content, $replace, $http_response_code) : header($content, $replace);
  228. }
  229. if (strpos($content, 'HTTP') === 0) {
  230. $key = 'Http-Code';
  231. } else {
  232. $key = strstr($content, ":", true);
  233. if (empty($key)) {
  234. return false;
  235. }
  236. }
  237. if ('location' === strtolower($key) && !$http_response_code) {
  238. return self::header($content, true, 302);
  239. }
  240. if (isset(HttpCache::$codes[$http_response_code])) {
  241. HttpCache::$header['Http-Code'] = "HTTP/1.1 $http_response_code " . HttpCache::$codes[$http_response_code];
  242. if ($key === 'Http-Code') {
  243. return true;
  244. }
  245. }
  246. if ($key === 'Set-Cookie') {
  247. HttpCache::$header[$key][] = $content;
  248. } else {
  249. HttpCache::$header[$key] = $content;
  250. }
  251. return true;
  252. }
  253. /**
  254. * Remove header.
  255. *
  256. * @param string $name
  257. * @return void
  258. */
  259. public static function headerRemove($name)
  260. {
  261. if (PHP_SAPI != 'cli') {
  262. header_remove($name);
  263. return;
  264. }
  265. unset(HttpCache::$header[$name]);
  266. }
  267. /**
  268. * Set cookie.
  269. *
  270. * @param string $name
  271. * @param string $value
  272. * @param integer $maxage
  273. * @param string $path
  274. * @param string $domain
  275. * @param bool $secure
  276. * @param bool $HTTPOnly
  277. * @return bool|void
  278. */
  279. public static function setcookie(
  280. $name,
  281. $value = '',
  282. $maxage = 0,
  283. $path = '',
  284. $domain = '',
  285. $secure = false,
  286. $HTTPOnly = false
  287. ) {
  288. if (PHP_SAPI != 'cli') {
  289. return setcookie($name, $value, $maxage, $path, $domain, $secure, $HTTPOnly);
  290. }
  291. return self::header(
  292. 'Set-Cookie: ' . $name . '=' . rawurlencode($value)
  293. . (empty($domain) ? '' : '; Domain=' . $domain)
  294. . (empty($maxage) ? '' : '; Max-Age=' . $maxage)
  295. . (empty($path) ? '' : '; Path=' . $path)
  296. . (!$secure ? '' : '; Secure')
  297. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  298. }
  299. /**
  300. * sessionStart
  301. *
  302. * @return bool
  303. */
  304. public static function sessionStart()
  305. {
  306. if (PHP_SAPI != 'cli') {
  307. return session_start();
  308. }
  309. if (HttpCache::$instance->sessionStarted) {
  310. echo "already sessionStarted\nn";
  311. return true;
  312. }
  313. HttpCache::$instance->sessionStarted = true;
  314. // Generate a SID.
  315. if (!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName])) {
  316. $file_name = tempnam(HttpCache::$sessionPath, 'ses');
  317. if (!$file_name) {
  318. return false;
  319. }
  320. HttpCache::$instance->sessionFile = $file_name;
  321. $session_id = substr(basename($file_name), strlen('ses'));
  322. return self::setcookie(
  323. HttpCache::$sessionName
  324. , $session_id
  325. , ini_get('session.cookie_lifetime')
  326. , ini_get('session.cookie_path')
  327. , ini_get('session.cookie_domain')
  328. , ini_get('session.cookie_secure')
  329. , ini_get('session.cookie_httponly')
  330. );
  331. }
  332. if (!HttpCache::$instance->sessionFile) {
  333. HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName];
  334. }
  335. // Read session from session file.
  336. if (HttpCache::$instance->sessionFile) {
  337. $raw = file_get_contents(HttpCache::$instance->sessionFile);
  338. if ($raw) {
  339. session_decode($raw);
  340. }
  341. }
  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. foreach (explode("\r\n", $boundary_header_buffer) as $item) {
  405. list($header_key, $header_value) = explode(": ", $item);
  406. $header_key = strtolower($header_key);
  407. switch ($header_key) {
  408. case "content-disposition":
  409. // Is file data.
  410. if (preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match)) {
  411. // Parse $_FILES.
  412. $_FILES[] = array(
  413. 'file_name' => $match[1],
  414. 'file_data' => $boundary_value,
  415. 'file_size' => strlen($boundary_value),
  416. );
  417. continue;
  418. } // Is post field.
  419. else {
  420. // Parse $_POST.
  421. if (preg_match('/name="(.*?)"$/', $header_value, $match)) {
  422. $_POST[$match[1]] = $boundary_value;
  423. }
  424. }
  425. break;
  426. }
  427. }
  428. }
  429. }
  430. }
  431. /**
  432. * Http cache for the current http response.
  433. */
  434. class HttpCache
  435. {
  436. public static $codes = array(
  437. 100 => 'Continue',
  438. 101 => 'Switching Protocols',
  439. 200 => 'OK',
  440. 201 => 'Created',
  441. 202 => 'Accepted',
  442. 203 => 'Non-Authoritative Information',
  443. 204 => 'No Content',
  444. 205 => 'Reset Content',
  445. 206 => 'Partial Content',
  446. 300 => 'Multiple Choices',
  447. 301 => 'Moved Permanently',
  448. 302 => 'Found',
  449. 303 => 'See Other',
  450. 304 => 'Not Modified',
  451. 305 => 'Use Proxy',
  452. 306 => '(Unused)',
  453. 307 => 'Temporary Redirect',
  454. 400 => 'Bad Request',
  455. 401 => 'Unauthorized',
  456. 402 => 'Payment Required',
  457. 403 => 'Forbidden',
  458. 404 => 'Not Found',
  459. 405 => 'Method Not Allowed',
  460. 406 => 'Not Acceptable',
  461. 407 => 'Proxy Authentication Required',
  462. 408 => 'Request Timeout',
  463. 409 => 'Conflict',
  464. 410 => 'Gone',
  465. 411 => 'Length Required',
  466. 412 => 'Precondition Failed',
  467. 413 => 'Request Entity Too Large',
  468. 414 => 'Request-URI Too Long',
  469. 415 => 'Unsupported Media Type',
  470. 416 => 'Requested Range Not Satisfiable',
  471. 417 => 'Expectation Failed',
  472. 422 => 'Unprocessable Entity',
  473. 423 => 'Locked',
  474. 500 => 'Internal Server Error',
  475. 501 => 'Not Implemented',
  476. 502 => 'Bad Gateway',
  477. 503 => 'Service Unavailable',
  478. 504 => 'Gateway Timeout',
  479. 505 => 'HTTP Version Not Supported',
  480. );
  481. /**
  482. * @var HttpCache
  483. */
  484. public static $instance = null;
  485. public static $header = array();
  486. public static $sessionPath = '';
  487. public static $sessionName = '';
  488. public $sessionStarted = false;
  489. public $sessionFile = '';
  490. public static function init()
  491. {
  492. self::$sessionName = ini_get('session.name');
  493. self::$sessionPath = session_save_path();
  494. if (!self::$sessionPath) {
  495. self::$sessionPath = sys_get_temp_dir();
  496. }
  497. @\session_start();
  498. }
  499. }