Http.php 18 KB

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