Http.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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;
  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. // GET
  165. parse_str($_SERVER['QUERY_STRING'], $_GET);
  166. // REQUEST
  167. $_REQUEST = array_merge($_GET, $_POST);
  168. // REMOTE_ADDR REMOTE_PORT
  169. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  170. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  171. }
  172. /**
  173. * 编码,增加HTTP头
  174. * @param string $content
  175. * @param ConnectionInterface $connection
  176. * @return string
  177. */
  178. public static function encode($content, ConnectionInterface $connection)
  179. {
  180. // 没有http-code默认给个
  181. if(!isset(HttpCache::$header['Http-Code']))
  182. {
  183. $header = "HTTP/1.1 200 OK\r\n";
  184. }
  185. else
  186. {
  187. $header = HttpCache::$header['Http-Code']."\r\n";
  188. unset(HttpCache::$header['Http-Code']);
  189. }
  190. // Content-Type
  191. if(!isset(HttpCache::$header['Content-Type']))
  192. {
  193. $header .= "Content-Type: text/html;charset=utf-8\r\n";
  194. }
  195. // other headers
  196. foreach(HttpCache::$header as $key=>$item)
  197. {
  198. if('Set-Cookie' == $key && is_array($item))
  199. {
  200. foreach($item as $it)
  201. {
  202. $header .= $it."\r\n";
  203. }
  204. }
  205. else
  206. {
  207. $header .= $item."\r\n";
  208. }
  209. }
  210. // header
  211. $header .= "Server: WorkerMan/3.0\r\nContent-Length: ".strlen($content)."\r\n\r\n";
  212. // save session
  213. self::sessionWriteClose();
  214. // the whole http package
  215. return $header.$content;
  216. }
  217. /**
  218. * 设置http头
  219. * @return bool
  220. */
  221. public static function header($content, $replace = true, $http_response_code = 0)
  222. {
  223. if(PHP_SAPI != 'cli')
  224. {
  225. return $http_response_code ? header($content, $replace, $http_response_code) : header($content, $replace);
  226. }
  227. if(strpos($content, 'HTTP') === 0)
  228. {
  229. $key = 'Http-Code';
  230. }
  231. else
  232. {
  233. $key = strstr($content, ":", true);
  234. if(empty($key))
  235. {
  236. return false;
  237. }
  238. }
  239. if('location' == strtolower($key) && !$http_response_code)
  240. {
  241. return self::header($content, true, 302);
  242. }
  243. if(isset(HttpCache::$codes[$http_response_code]))
  244. {
  245. HttpCache::$header['Http-Code'] = "HTTP/1.1 $http_response_code " . HttpCache::$codes[$http_response_code];
  246. if($key == 'Http-Code')
  247. {
  248. return true;
  249. }
  250. }
  251. if($key == 'Set-Cookie')
  252. {
  253. HttpCache::$header[$key][] = $content;
  254. }
  255. else
  256. {
  257. HttpCache::$header[$key] = $content;
  258. }
  259. return true;
  260. }
  261. /**
  262. * 删除一个header
  263. * @param string $name
  264. * @return void
  265. */
  266. public static function headerRemove($name)
  267. {
  268. if(PHP_SAPI != 'cli')
  269. {
  270. return header_remove($name);
  271. }
  272. unset( HttpCache::$header[$name]);
  273. }
  274. /**
  275. * 设置cookie
  276. * @param string $name
  277. * @param string $value
  278. * @param integer $maxage
  279. * @param string $path
  280. * @param string $domain
  281. * @param bool $secure
  282. * @param bool $HTTPOnly
  283. */
  284. public static function setcookie($name, $value = '', $maxage = 0, $path = '', $domain = '', $secure = false, $HTTPOnly = false) {
  285. if(PHP_SAPI != 'cli')
  286. {
  287. return setcookie($name, $value, $maxage, $path, $domain, $secure, $HTTPOnly);
  288. }
  289. return self::header(
  290. 'Set-Cookie: ' . $name . '=' . rawurlencode($value)
  291. . (empty($domain) ? '' : '; Domain=' . $domain)
  292. . (empty($maxage) ? '' : '; Max-Age=' . $maxage)
  293. . (empty($path) ? '' : '; Path=' . $path)
  294. . (!$secure ? '' : '; Secure')
  295. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  296. }
  297. /**
  298. * sessionStart
  299. * @return bool
  300. */
  301. public static function sessionStart()
  302. {
  303. if(PHP_SAPI != 'cli')
  304. {
  305. return session_start();
  306. }
  307. if(HttpCache::$instance->sessionStarted)
  308. {
  309. echo "already sessionStarted\nn";
  310. return true;
  311. }
  312. HttpCache::$instance->sessionStarted = true;
  313. // 没有sid,则创建一个session文件,生成一个sid
  314. if(!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/sess_' . $_COOKIE[HttpCache::$sessionName]))
  315. {
  316. $file_name = tempnam(HttpCache::$sessionPath, 'sess_');
  317. if(!$file_name)
  318. {
  319. return false;
  320. }
  321. HttpCache::$instance->sessionFile = $file_name;
  322. $session_id = substr(basename($file_name), strlen('sess_'));
  323. return self::setcookie(
  324. HttpCache::$sessionName
  325. , $session_id
  326. , ini_get('session.cookie_lifetime')
  327. , ini_get('session.cookie_path')
  328. , ini_get('session.cookie_domain')
  329. , ini_get('session.cookie_secure')
  330. , ini_get('session.cookie_httponly')
  331. );
  332. }
  333. if(!HttpCache::$instance->sessionFile)
  334. {
  335. HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/sess_' . $_COOKIE[HttpCache::$sessionName];
  336. }
  337. // 有sid则打开文件,读取session值
  338. if(HttpCache::$instance->sessionFile)
  339. {
  340. $raw = file_get_contents(HttpCache::$instance->sessionFile);
  341. if($raw)
  342. {
  343. session_decode($raw);
  344. }
  345. }
  346. }
  347. /**
  348. * 保存session
  349. * @return bool
  350. */
  351. public static function sessionWriteClose()
  352. {
  353. if(PHP_SAPI != 'cli')
  354. {
  355. return session_write_close();
  356. }
  357. if(!empty(HttpCache::$instance->sessionStarted) && !empty($_SESSION))
  358. {
  359. $session_str = session_encode();
  360. if($session_str && HttpCache::$instance->sessionFile)
  361. {
  362. return file_put_contents(HttpCache::$instance->sessionFile, $session_str);
  363. }
  364. }
  365. return empty($_SESSION);
  366. }
  367. /**
  368. * 退出
  369. * @param string $msg
  370. * @throws \Exception
  371. */
  372. public static function end($msg = '')
  373. {
  374. if(PHP_SAPI != 'cli')
  375. {
  376. exit($msg);
  377. }
  378. if($msg)
  379. {
  380. echo $msg;
  381. }
  382. throw new \Exception('jump_exit');
  383. }
  384. /**
  385. * get mime types
  386. */
  387. public static function getMimeTypesFile()
  388. {
  389. return __DIR__.'/Http/mime.types';
  390. }
  391. /**
  392. * 解析$_FILES
  393. */
  394. protected function parseUploadFiles($http_body, $http_post_boundary)
  395. {
  396. $http_body = substr($http_body, 0, strlen($http_body) - (strlen($http_post_boundary) + 4));
  397. $boundary_data_array = explode($http_post_boundary."\r\n", $http_body);
  398. if($boundary_data_array[0] === '')
  399. {
  400. unset($boundary_data_array[0]);
  401. }
  402. foreach($boundary_data_array as $boundary_data_buffer)
  403. {
  404. list($boundary_header_buffer, $boundary_value) = explode("\r\n\r\n", $boundary_data_buffer, 2);
  405. // 去掉末尾\r\n
  406. $boundary_value = substr($boundary_value, 0, -2);
  407. foreach (explode("\r\n", $boundary_header_buffer) as $item)
  408. {
  409. list($header_key, $header_value) = explode(": ", $item);
  410. $header_key = strtolower($header_key);
  411. switch ($header_key)
  412. {
  413. case "content-disposition":
  414. // 是文件
  415. if(preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match))
  416. {
  417. $_FILES[] = array(
  418. 'file_name' => $match[1],
  419. 'file_data' => $boundary_value,
  420. 'file_size' => strlen($boundary_value),
  421. );
  422. continue;
  423. }
  424. // 是post field
  425. else
  426. {
  427. // 收集post
  428. if(preg_match('/name="(.*?)"$/', $header_value, $match))
  429. {
  430. $_POST[$match[1]] = $boundary_value;
  431. }
  432. }
  433. break;
  434. }
  435. }
  436. }
  437. }
  438. }
  439. /**
  440. * 解析http协议数据包 缓存先关
  441. * @author walkor
  442. */
  443. class HttpCache
  444. {
  445. public static $codes = array(
  446. 100 => 'Continue',
  447. 101 => 'Switching Protocols',
  448. 200 => 'OK',
  449. 201 => 'Created',
  450. 202 => 'Accepted',
  451. 203 => 'Non-Authoritative Information',
  452. 204 => 'No Content',
  453. 205 => 'Reset Content',
  454. 206 => 'Partial Content',
  455. 300 => 'Multiple Choices',
  456. 301 => 'Moved Permanently',
  457. 302 => 'Found',
  458. 303 => 'See Other',
  459. 304 => 'Not Modified',
  460. 305 => 'Use Proxy',
  461. 306 => '(Unused)',
  462. 307 => 'Temporary Redirect',
  463. 400 => 'Bad Request',
  464. 401 => 'Unauthorized',
  465. 402 => 'Payment Required',
  466. 403 => 'Forbidden',
  467. 404 => 'Not Found',
  468. 405 => 'Method Not Allowed',
  469. 406 => 'Not Acceptable',
  470. 407 => 'Proxy Authentication Required',
  471. 408 => 'Request Timeout',
  472. 409 => 'Conflict',
  473. 410 => 'Gone',
  474. 411 => 'Length Required',
  475. 412 => 'Precondition Failed',
  476. 413 => 'Request Entity Too Large',
  477. 414 => 'Request-URI Too Long',
  478. 415 => 'Unsupported Media Type',
  479. 416 => 'Requested Range Not Satisfiable',
  480. 417 => 'Expectation Failed',
  481. 422 => 'Unprocessable Entity',
  482. 423 => 'Locked',
  483. 500 => 'Internal Server Error',
  484. 501 => 'Not Implemented',
  485. 502 => 'Bad Gateway',
  486. 503 => 'Service Unavailable',
  487. 504 => 'Gateway Timeout',
  488. 505 => 'HTTP Version Not Supported',
  489. );
  490. public static $instance = null;
  491. public static $header = array();
  492. public static $sessionPath = '';
  493. public static $sessionName = '';
  494. public $sessionStarted = false;
  495. public $sessionFile = '';
  496. public static function init()
  497. {
  498. self::$sessionName = ini_get('session.name');
  499. self::$sessionPath = session_save_path();
  500. if(!self::$sessionPath)
  501. {
  502. self::$sessionPath = sys_get_temp_dir();
  503. }
  504. @\session_start();
  505. }
  506. }