Http.php 14 KB

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