Http.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. * Check the integrity of the package.
  24. *
  25. * @param string $recv_buffer
  26. * @param TcpConnection $connection
  27. * @return int
  28. */
  29. public static function input($recv_buffer, TcpConnection $connection)
  30. {
  31. if (!strpos($recv_buffer, "\r\n\r\n")) {
  32. // Judge whether the package length exceeds the limit.
  33. if (strlen($recv_buffer) >= TcpConnection::$maxPackageSize) {
  34. $connection->close();
  35. return 0;
  36. }
  37. return 0;
  38. }
  39. list($header,) = explode("\r\n\r\n", $recv_buffer, 2);
  40. if (0 === strpos($recv_buffer, "POST")) {
  41. // find Content-Length
  42. $match = array();
  43. if (preg_match("/\r\nContent-Length: ?(\d+)/i", $header, $match)) {
  44. $content_length = $match[1];
  45. return $content_length + strlen($header) + 4;
  46. } else {
  47. return 0;
  48. }
  49. } elseif (0 === strpos($recv_buffer, "GET")) {
  50. return strlen($header) + 4;
  51. } else {
  52. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n", true);
  53. return 0;
  54. }
  55. }
  56. /**
  57. * Parse $_POST、$_GET、$_COOKIE.
  58. *
  59. * @param string $recv_buffer
  60. * @param TcpConnection $connection
  61. * @return array
  62. */
  63. public static function decode($recv_buffer, TcpConnection $connection)
  64. {
  65. // Init.
  66. $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
  67. $GLOBALS['HTTP_RAW_POST_DATA'] = '';
  68. // Clear cache.
  69. HttpCache::$header = array('Connection' => 'Connection: keep-alive');
  70. HttpCache::$instance = new HttpCache();
  71. // $_SERVER
  72. $_SERVER = array(
  73. 'QUERY_STRING' => '',
  74. 'REQUEST_METHOD' => '',
  75. 'REQUEST_URI' => '',
  76. 'SERVER_PROTOCOL' => '',
  77. 'SERVER_SOFTWARE' => 'workerman/'.Worker::VERSION,
  78. 'SERVER_NAME' => '',
  79. 'HTTP_HOST' => '',
  80. 'HTTP_USER_AGENT' => '',
  81. 'HTTP_ACCEPT' => '',
  82. 'HTTP_ACCEPT_LANGUAGE' => '',
  83. 'HTTP_ACCEPT_ENCODING' => '',
  84. 'HTTP_COOKIE' => '',
  85. 'HTTP_CONNECTION' => '',
  86. 'REMOTE_ADDR' => '',
  87. 'REMOTE_PORT' => '0',
  88. );
  89. // Parse headers.
  90. list($http_header, $http_body) = explode("\r\n\r\n", $recv_buffer, 2);
  91. $header_data = explode("\r\n", $http_header);
  92. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ',
  93. $header_data[0]);
  94. $http_post_boundary = '';
  95. unset($header_data[0]);
  96. foreach ($header_data as $content) {
  97. // \r\n\r\n
  98. if (empty($content)) {
  99. continue;
  100. }
  101. list($key, $value) = explode(':', $content, 2);
  102. $key = str_replace('-', '_', strtoupper($key));
  103. $value = trim($value);
  104. $_SERVER['HTTP_' . $key] = $value;
  105. switch ($key) {
  106. // HTTP_HOST
  107. case 'HOST':
  108. $tmp = explode(':', $value);
  109. $_SERVER['SERVER_NAME'] = $tmp[0];
  110. if (isset($tmp[1])) {
  111. $_SERVER['SERVER_PORT'] = $tmp[1];
  112. }
  113. break;
  114. // cookie
  115. case 'COOKIE':
  116. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  117. break;
  118. // content-type
  119. case 'CONTENT_TYPE':
  120. if (!preg_match('/boundary="?(\S+)"?/', $value, $match)) {
  121. $_SERVER['CONTENT_TYPE'] = $value;
  122. } else {
  123. $_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
  124. $http_post_boundary = '--' . $match[1];
  125. }
  126. break;
  127. case 'CONTENT_LENGTH':
  128. $_SERVER['CONTENT_LENGTH'] = $value;
  129. break;
  130. }
  131. }
  132. // Parse $_POST.
  133. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  134. if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'multipart/form-data') {
  135. self::parseUploadFiles($http_body, $http_post_boundary);
  136. } else {
  137. parse_str($http_body, $_POST);
  138. // $GLOBALS['HTTP_RAW_POST_DATA']
  139. $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
  140. }
  141. }
  142. // QUERY_STRING
  143. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  144. if ($_SERVER['QUERY_STRING']) {
  145. // $GET
  146. parse_str($_SERVER['QUERY_STRING'], $_GET);
  147. } else {
  148. $_SERVER['QUERY_STRING'] = '';
  149. }
  150. // REQUEST
  151. $_REQUEST = array_merge($_GET, $_POST);
  152. // REMOTE_ADDR REMOTE_PORT
  153. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  154. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  155. return array('get' => $_GET, 'post' => $_POST, 'cookie' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES);
  156. }
  157. /**
  158. * Http encode.
  159. *
  160. * @param string $content
  161. * @param TcpConnection $connection
  162. * @return string
  163. */
  164. public static function encode($content, TcpConnection $connection)
  165. {
  166. // Default http-code.
  167. if (!isset(HttpCache::$header['Http-Code'])) {
  168. $header = "HTTP/1.1 200 OK\r\n";
  169. } else {
  170. $header = HttpCache::$header['Http-Code'] . "\r\n";
  171. unset(HttpCache::$header['Http-Code']);
  172. }
  173. // Content-Type
  174. if (!isset(HttpCache::$header['Content-Type'])) {
  175. $header .= "Content-Type: text/html;charset=utf-8\r\n";
  176. }
  177. // other headers
  178. foreach (HttpCache::$header as $key => $item) {
  179. if ('Set-Cookie' === $key && is_array($item)) {
  180. foreach ($item as $it) {
  181. $header .= $it . "\r\n";
  182. }
  183. } else {
  184. $header .= $item . "\r\n";
  185. }
  186. }
  187. // header
  188. $header .= "Server: workerman/" . Worker::VERSION . "\r\nContent-Length: " . strlen($content) . "\r\n\r\n";
  189. // save session
  190. self::sessionWriteClose();
  191. // the whole http package
  192. return $header . $content;
  193. }
  194. /**
  195. * 设置http头
  196. *
  197. * @return bool|void
  198. */
  199. public static function header($content, $replace = true, $http_response_code = 0)
  200. {
  201. if (PHP_SAPI != 'cli') {
  202. return $http_response_code ? header($content, $replace, $http_response_code) : header($content, $replace);
  203. }
  204. if (strpos($content, 'HTTP') === 0) {
  205. $key = 'Http-Code';
  206. } else {
  207. $key = strstr($content, ":", true);
  208. if (empty($key)) {
  209. return false;
  210. }
  211. }
  212. if ('location' === strtolower($key) && !$http_response_code) {
  213. return self::header($content, true, 302);
  214. }
  215. if (isset(HttpCache::$codes[$http_response_code])) {
  216. HttpCache::$header['Http-Code'] = "HTTP/1.1 $http_response_code " . HttpCache::$codes[$http_response_code];
  217. if ($key === 'Http-Code') {
  218. return true;
  219. }
  220. }
  221. if ($key === 'Set-Cookie') {
  222. HttpCache::$header[$key][] = $content;
  223. } else {
  224. HttpCache::$header[$key] = $content;
  225. }
  226. return true;
  227. }
  228. /**
  229. * Remove header.
  230. *
  231. * @param string $name
  232. * @return void
  233. */
  234. public static function headerRemove($name)
  235. {
  236. if (PHP_SAPI != 'cli') {
  237. header_remove($name);
  238. return;
  239. }
  240. unset(HttpCache::$header[$name]);
  241. }
  242. /**
  243. * Set cookie.
  244. *
  245. * @param string $name
  246. * @param string $value
  247. * @param integer $maxage
  248. * @param string $path
  249. * @param string $domain
  250. * @param bool $secure
  251. * @param bool $HTTPOnly
  252. * @return bool|void
  253. */
  254. public static function setcookie(
  255. $name,
  256. $value = '',
  257. $maxage = 0,
  258. $path = '',
  259. $domain = '',
  260. $secure = false,
  261. $HTTPOnly = false
  262. ) {
  263. if (PHP_SAPI != 'cli') {
  264. return setcookie($name, $value, $maxage, $path, $domain, $secure, $HTTPOnly);
  265. }
  266. return self::header(
  267. 'Set-Cookie: ' . $name . '=' . rawurlencode($value)
  268. . (empty($domain) ? '' : '; Domain=' . $domain)
  269. . (empty($maxage) ? '' : '; Max-Age=' . $maxage)
  270. . (empty($path) ? '' : '; Path=' . $path)
  271. . (!$secure ? '' : '; Secure')
  272. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  273. }
  274. /**
  275. * sessionStart
  276. *
  277. * @return bool
  278. */
  279. public static function sessionStart()
  280. {
  281. if (PHP_SAPI != 'cli') {
  282. return session_start();
  283. }
  284. if (HttpCache::$instance->sessionStarted) {
  285. echo "already sessionStarted\nn";
  286. return true;
  287. }
  288. HttpCache::$instance->sessionStarted = true;
  289. // Generate a SID.
  290. if (!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName])) {
  291. $file_name = tempnam(HttpCache::$sessionPath, 'ses');
  292. if (!$file_name) {
  293. return false;
  294. }
  295. HttpCache::$instance->sessionFile = $file_name;
  296. $session_id = substr(basename($file_name), strlen('ses'));
  297. return self::setcookie(
  298. HttpCache::$sessionName
  299. , $session_id
  300. , ini_get('session.cookie_lifetime')
  301. , ini_get('session.cookie_path')
  302. , ini_get('session.cookie_domain')
  303. , ini_get('session.cookie_secure')
  304. , ini_get('session.cookie_httponly')
  305. );
  306. }
  307. if (!HttpCache::$instance->sessionFile) {
  308. HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName];
  309. }
  310. // Read session from session file.
  311. if (HttpCache::$instance->sessionFile) {
  312. $raw = file_get_contents(HttpCache::$instance->sessionFile);
  313. if ($raw) {
  314. session_decode($raw);
  315. }
  316. }
  317. return true;
  318. }
  319. /**
  320. * Save session.
  321. *
  322. * @return bool
  323. */
  324. public static function sessionWriteClose()
  325. {
  326. if (PHP_SAPI != 'cli') {
  327. return session_write_close();
  328. }
  329. if (!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION)) {
  330. $session_str = session_encode();
  331. if ($session_str && HttpCache::$instance->sessionFile) {
  332. return file_put_contents(HttpCache::$instance->sessionFile, $session_str);
  333. }
  334. }
  335. return empty($_SESSION);
  336. }
  337. /**
  338. * End, like call exit in php-fpm.
  339. *
  340. * @param string $msg
  341. * @throws \Exception
  342. */
  343. public static function end($msg = '')
  344. {
  345. if (PHP_SAPI != 'cli') {
  346. exit($msg);
  347. }
  348. if ($msg) {
  349. echo $msg;
  350. }
  351. throw new \Exception('jump_exit');
  352. }
  353. /**
  354. * Get mime types.
  355. *
  356. * @return string
  357. */
  358. public static function getMimeTypesFile()
  359. {
  360. return __DIR__ . '/Http/mime.types';
  361. }
  362. /**
  363. * Parse $_FILES.
  364. *
  365. * @param string $http_body
  366. * @param string $http_post_boundary
  367. * @return void
  368. */
  369. protected static function parseUploadFiles($http_body, $http_post_boundary)
  370. {
  371. $http_body = substr($http_body, 0, strlen($http_body) - (strlen($http_post_boundary) + 4));
  372. $boundary_data_array = explode($http_post_boundary . "\r\n", $http_body);
  373. if ($boundary_data_array[0] === '') {
  374. unset($boundary_data_array[0]);
  375. }
  376. foreach ($boundary_data_array as $boundary_data_buffer) {
  377. list($boundary_header_buffer, $boundary_value) = explode("\r\n\r\n", $boundary_data_buffer, 2);
  378. // Remove \r\n from the end of buffer.
  379. $boundary_value = substr($boundary_value, 0, -2);
  380. foreach (explode("\r\n", $boundary_header_buffer) as $item) {
  381. list($header_key, $header_value) = explode(": ", $item);
  382. $header_key = strtolower($header_key);
  383. switch ($header_key) {
  384. case "content-disposition":
  385. // Is file data.
  386. if (preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match)) {
  387. // Parse $_FILES.
  388. $_FILES[] = array(
  389. 'file_name' => $match[1],
  390. 'file_data' => $boundary_value,
  391. 'file_size' => strlen($boundary_value),
  392. );
  393. continue;
  394. } // Is post field.
  395. else {
  396. // Parse $_POST.
  397. if (preg_match('/name="(.*?)"$/', $header_value, $match)) {
  398. $_POST[$match[1]] = $boundary_value;
  399. }
  400. }
  401. break;
  402. }
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * Http cache for the current http response.
  409. */
  410. class HttpCache
  411. {
  412. public static $codes = array(
  413. 100 => 'Continue',
  414. 101 => 'Switching Protocols',
  415. 200 => 'OK',
  416. 201 => 'Created',
  417. 202 => 'Accepted',
  418. 203 => 'Non-Authoritative Information',
  419. 204 => 'No Content',
  420. 205 => 'Reset Content',
  421. 206 => 'Partial Content',
  422. 300 => 'Multiple Choices',
  423. 301 => 'Moved Permanently',
  424. 302 => 'Found',
  425. 303 => 'See Other',
  426. 304 => 'Not Modified',
  427. 305 => 'Use Proxy',
  428. 306 => '(Unused)',
  429. 307 => 'Temporary Redirect',
  430. 400 => 'Bad Request',
  431. 401 => 'Unauthorized',
  432. 402 => 'Payment Required',
  433. 403 => 'Forbidden',
  434. 404 => 'Not Found',
  435. 405 => 'Method Not Allowed',
  436. 406 => 'Not Acceptable',
  437. 407 => 'Proxy Authentication Required',
  438. 408 => 'Request Timeout',
  439. 409 => 'Conflict',
  440. 410 => 'Gone',
  441. 411 => 'Length Required',
  442. 412 => 'Precondition Failed',
  443. 413 => 'Request Entity Too Large',
  444. 414 => 'Request-URI Too Long',
  445. 415 => 'Unsupported Media Type',
  446. 416 => 'Requested Range Not Satisfiable',
  447. 417 => 'Expectation Failed',
  448. 422 => 'Unprocessable Entity',
  449. 423 => 'Locked',
  450. 500 => 'Internal Server Error',
  451. 501 => 'Not Implemented',
  452. 502 => 'Bad Gateway',
  453. 503 => 'Service Unavailable',
  454. 504 => 'Gateway Timeout',
  455. 505 => 'HTTP Version Not Supported',
  456. );
  457. /**
  458. * @var HttpCache
  459. */
  460. public static $instance = null;
  461. public static $header = array();
  462. public static $sessionPath = '';
  463. public static $sessionName = '';
  464. public $sessionStarted = false;
  465. public $sessionFile = '';
  466. public static function init()
  467. {
  468. self::$sessionName = ini_get('session.name');
  469. self::$sessionPath = session_save_path();
  470. if (!self::$sessionPath) {
  471. self::$sessionPath = sys_get_temp_dir();
  472. }
  473. @\session_start();
  474. }
  475. }