Http.php 17 KB

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