WebServer.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. call_user_func($this->_onWorkerStart, $this);
  96. }
  97. }
  98. /**
  99. * 初始化mimeType
  100. * @return void
  101. */
  102. public function initMimeTypeMap()
  103. {
  104. $mime_file = Http::getMimeTypesFile();
  105. if(!is_file($mime_file))
  106. {
  107. $this->notice("$mime_file mime.type file not fond");
  108. return;
  109. }
  110. $items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  111. if(!is_array($items))
  112. {
  113. $this->log("get $mime_file mime.type content fail");
  114. return;
  115. }
  116. foreach($items as $content)
  117. {
  118. if(preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match))
  119. {
  120. $mime_type = $match[1];
  121. $extension_var = $match[2];
  122. $extension_array = explode(' ', substr($extension_var, 0, -1));
  123. foreach($extension_array as $extension)
  124. {
  125. self::$mimeTypeMap[$extension] = $mime_type;
  126. }
  127. }
  128. }
  129. }
  130. /**
  131. * 当接收到完整的http请求后的处理逻辑
  132. * 1、如果请求的是以php为后缀的文件,则尝试加载
  133. * 2、如果请求的url没有后缀,则尝试加载对应目录的index.php
  134. * 3、如果请求的是非php为后缀的文件,尝试读取原始数据并发送
  135. * 4、如果请求的文件不存在,则返回404
  136. * @param TcpConnection $connection
  137. * @param mixed $data
  138. * @return void
  139. */
  140. public function onMessage($connection, $data)
  141. {
  142. // 请求的文件
  143. $url_info = parse_url($_SERVER['REQUEST_URI']);
  144. if(!$url_info)
  145. {
  146. Http::header('HTTP/1.1 400 Bad Request');
  147. return $connection->close('<h1>400 Bad Request</h1>');
  148. }
  149. $path = $url_info['path'];
  150. $path_info = pathinfo($path);
  151. $extension = isset($path_info['extension']) ? $path_info['extension'] : '' ;
  152. if($extension === '')
  153. {
  154. $path = ($len = strlen($path)) && $path[$len -1] === '/' ? $path.'index.php' : $path . '/index.php';
  155. $extension = 'php';
  156. }
  157. $root_dir = isset($this->serverRoot[$_SERVER['HTTP_HOST']]) ? $this->serverRoot[$_SERVER['HTTP_HOST']] : current($this->serverRoot);
  158. $file = "$root_dir/$path";
  159. // 对应的php文件不存在则直接使用根目录的index.php
  160. if($extension === 'php' && !is_file($file))
  161. {
  162. $file = "$root_dir/index.php";
  163. if(!is_file($file))
  164. {
  165. $file = "$root_dir/index.html";
  166. $extension = 'html';
  167. }
  168. }
  169. // 请求的文件存在
  170. if(is_file($file))
  171. {
  172. // 判断是否是站点目录里的文件
  173. if((!($request_realpath = realpath($file)) || !($root_dir_realpath = realpath($root_dir))) || 0 !== strpos($request_realpath, $root_dir_realpath))
  174. {
  175. Http::header('HTTP/1.1 400 Bad Request');
  176. return $connection->close('<h1>400 Bad Request</h1>');
  177. }
  178. $file = realpath($file);
  179. // 如果请求的是php文件
  180. if($extension === 'php')
  181. {
  182. $cwd = getcwd();
  183. chdir($root_dir);
  184. ini_set('display_errors', 'off');
  185. // 缓冲输出
  186. ob_start();
  187. // 载入php文件
  188. try
  189. {
  190. // $_SERVER变量
  191. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  192. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  193. include $file;
  194. }
  195. catch(\Exception $e)
  196. {
  197. // 如果不是exit
  198. if($e->getMessage() != 'jump_exit')
  199. {
  200. echo $e;
  201. }
  202. }
  203. $content = ob_get_clean();
  204. ini_set('display_errors', 'on');
  205. $connection->close($content);
  206. chdir($cwd);
  207. return ;
  208. }
  209. // 请求的是静态资源文件
  210. if(isset(self::$mimeTypeMap[$extension]))
  211. {
  212. Http::header('Content-Type: '. self::$mimeTypeMap[$extension]);
  213. }
  214. else
  215. {
  216. Http::header('Content-Type: '. self::$defaultMimeType);
  217. }
  218. // 获取文件信息
  219. $info = stat($file);
  220. $modified_time = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' GMT' : '';
  221. // 如果有$_SERVER['HTTP_IF_MODIFIED_SINCE']
  222. if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info)
  223. {
  224. // 文件没有更改则直接304
  225. if($modified_time === $_SERVER['HTTP_IF_MODIFIED_SINCE'])
  226. {
  227. // 304
  228. Http::header('HTTP/1.1 304 Not Modified');
  229. // 发送给客户端
  230. return $connection->close('');
  231. }
  232. }
  233. if($modified_time)
  234. {
  235. Http::header("Last-Modified: $modified_time");
  236. }
  237. // 发送给客户端
  238. return $connection->close(file_get_contents($file));
  239. }
  240. else
  241. {
  242. // 404
  243. Http::header("HTTP/1.1 404 Not Found");
  244. return $connection->close('<html><head><title>404 页面不存在</title></head><body><center><h3>404 Not Found</h3></center></body></html>');
  245. }
  246. }
  247. }