Http.php 17 KB

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