Http.php 16 KB

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