Http.php 17 KB

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