WebServer.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman;
  15. use \Workerman\Worker;
  16. use \Workerman\Protocols\Http;
  17. use \Workerman\Protocols\HttpCache;
  18. /**
  19. *
  20. * 基于Worker实现的一个简单的WebServer
  21. * 支持静态文件、支持文件上传、支持POST
  22. * HTTP协议
  23. */
  24. class WebServer extends Worker
  25. {
  26. /**
  27. * 默认mime类型
  28. * @var string
  29. */
  30. protected static $defaultMimeType = 'text/html; charset=utf-8';
  31. /**
  32. * 服务器名到文件路径的转换
  33. * @var array ['workerman.net'=>'/home', 'www.workerman.net'=>'home/www']
  34. */
  35. protected $serverRoot = array();
  36. /**
  37. * mime类型映射关系
  38. * @var array
  39. */
  40. protected static $mimeTypeMap = array();
  41. /**
  42. * 用来保存用户设置的onWorkerStart回调
  43. * @var callback
  44. */
  45. protected $_onWorkerStart = null;
  46. /**
  47. * 添加站点域名与站点目录的对应关系,类似nginx的
  48. * @param string $domain
  49. * @param string $root_path
  50. * @return void
  51. */
  52. public function addRoot($domain, $root_path)
  53. {
  54. $this->serverRoot[$domain] = $root_path;
  55. }
  56. /**
  57. * 构造函数
  58. * @param string $socket_name
  59. * @param array $context_option
  60. */
  61. public function __construct($socket_name, $context_option = array())
  62. {
  63. list($scheme, $address) = explode(':', $socket_name, 2);
  64. parent::__construct('http:'.$address, $context_option);
  65. $this->name = 'WebServer';
  66. }
  67. /**
  68. * 运行
  69. * @see Workerman.Worker::run()
  70. */
  71. public function run()
  72. {
  73. $this->_onWorkerStart = $this->onWorkerStart;
  74. $this->onWorkerStart = array($this, 'onWorkerStart');
  75. $this->onMessage = array($this, 'onMessage');
  76. parent::run();
  77. }
  78. /**
  79. * 进程启动的时候一些初始化工作
  80. * @throws \Exception
  81. */
  82. public function onWorkerStart()
  83. {
  84. if(empty($this->serverRoot))
  85. {
  86. throw new \Exception('server root not set, please use WebServer::addRoot($domain, $root_path) to set server root path');
  87. }
  88. // 初始化HttpCache
  89. HttpCache::init();
  90. // 初始化mimeMap
  91. $this->initMimeTypeMap();
  92. // 尝试执行开发者设定的onWorkerStart回调
  93. if($this->_onWorkerStart)
  94. {
  95. try
  96. {
  97. call_user_func($this->_onWorkerStart, $this);
  98. }
  99. catch(\Exception $e)
  100. {
  101. echo $e;
  102. exit(250);
  103. }
  104. }
  105. }
  106. /**
  107. * 初始化mimeType
  108. * @return void
  109. */
  110. public function initMimeTypeMap()
  111. {
  112. $mime_file = Http::getMimeTypesFile();
  113. if(!is_file($mime_file))
  114. {
  115. $this->notice("$mime_file mime.type file not fond");
  116. return;
  117. }
  118. $items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  119. if(!is_array($items))
  120. {
  121. $this->log("get $mime_file mime.type content fail");
  122. return;
  123. }
  124. foreach($items as $content)
  125. {
  126. if(preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match))
  127. {
  128. $mime_type = $match[1];
  129. $extension_var = $match[2];
  130. $extension_array = explode(' ', substr($extension_var, 0, -1));
  131. foreach($extension_array as $extension)
  132. {
  133. self::$mimeTypeMap[$extension] = $mime_type;
  134. }
  135. }
  136. }
  137. }
  138. /**
  139. * 当接收到完整的http请求后的处理逻辑
  140. * 1、如果请求的是以php为后缀的文件,则尝试加载
  141. * 2、如果请求的url没有后缀,则尝试加载对应目录的index.php
  142. * 3、如果请求的是非php为后缀的文件,尝试读取原始数据并发送
  143. * 4、如果请求的文件不存在,则返回404
  144. * @param TcpConnection $connection
  145. * @param mixed $data
  146. * @return void
  147. */
  148. public function onMessage($connection, $data)
  149. {
  150. // 请求的文件
  151. $url_info = parse_url($_SERVER['REQUEST_URI']);
  152. if(!$url_info)
  153. {
  154. Http::header('HTTP/1.1 400 Bad Request');
  155. return $connection->close('<h1>400 Bad Request</h1>');
  156. }
  157. $path = $url_info['path'];
  158. $path_info = pathinfo($path);
  159. $extension = isset($path_info['extension']) ? $path_info['extension'] : '' ;
  160. if($extension === '')
  161. {
  162. $path = ($len = strlen($path)) && $path[$len -1] === '/' ? $path.'index.php' : $path . '/index.php';
  163. $extension = 'php';
  164. }
  165. $root_dir = isset($this->serverRoot[$_SERVER['HTTP_HOST']]) ? $this->serverRoot[$_SERVER['HTTP_HOST']] : current($this->serverRoot);
  166. $file = "$root_dir/$path";
  167. // 对应的php文件不存在则直接使用根目录的index.php
  168. if($extension === 'php' && !is_file($file))
  169. {
  170. $file = "$root_dir/index.php";
  171. if(!is_file($file))
  172. {
  173. $file = "$root_dir/index.html";
  174. $extension = 'html';
  175. }
  176. }
  177. // 请求的文件存在
  178. if(is_file($file))
  179. {
  180. // 判断是否是站点目录里的文件
  181. if((!($request_realpath = realpath($file)) || !($root_dir_realpath = realpath($root_dir))) || 0 !== strpos($request_realpath, $root_dir_realpath))
  182. {
  183. Http::header('HTTP/1.1 400 Bad Request');
  184. return $connection->close('<h1>400 Bad Request</h1>');
  185. }
  186. $file = realpath($file);
  187. // 如果请求的是php文件
  188. if($extension === 'php')
  189. {
  190. $cwd = getcwd();
  191. chdir($root_dir);
  192. ini_set('display_errors', 'off');
  193. // 缓冲输出
  194. ob_start();
  195. // 载入php文件
  196. try
  197. {
  198. // $_SERVER变量
  199. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  200. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  201. include $file;
  202. }
  203. catch(\Exception $e)
  204. {
  205. // 如果不是exit
  206. if($e->getMessage() != 'jump_exit')
  207. {
  208. echo $e;
  209. }
  210. }
  211. $content = ob_get_clean();
  212. ini_set('display_errors', 'on');
  213. $connection->close($content);
  214. chdir($cwd);
  215. return ;
  216. }
  217. // 请求的是静态资源文件
  218. if(isset(self::$mimeTypeMap[$extension]))
  219. {
  220. Http::header('Content-Type: '. self::$mimeTypeMap[$extension]);
  221. }
  222. else
  223. {
  224. Http::header('Content-Type: '. self::$defaultMimeType);
  225. }
  226. // 获取文件信息
  227. $info = stat($file);
  228. $modified_time = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' GMT' : '';
  229. // 如果有$_SERVER['HTTP_IF_MODIFIED_SINCE']
  230. if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info)
  231. {
  232. // 文件没有更改则直接304
  233. if($modified_time === $_SERVER['HTTP_IF_MODIFIED_SINCE'])
  234. {
  235. // 304
  236. Http::header('HTTP/1.1 304 Not Modified');
  237. // 发送给客户端
  238. return $connection->close('');
  239. }
  240. }
  241. if($modified_time)
  242. {
  243. Http::header("Last-Modified: $modified_time");
  244. }
  245. // 发送给客户端
  246. return $connection->close(file_get_contents($file));
  247. }
  248. else
  249. {
  250. // 404
  251. Http::header("HTTP/1.1 404 Not Found");
  252. return $connection->close('<html><head><title>404 页面不存在</title></head><body><center><h3>404 Not Found</h3></center></body></html>');
  253. }
  254. }
  255. }