Http.php 16 KB

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