WebServer.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. require_once WORKERMAN_ROOT_DIR . 'man/Core/SocketWorker.php';
  3. require_once WORKERMAN_ROOT_DIR . 'applications/Common/Protocols/Http/Http.php';
  4. /**
  5. *
  6. * WebServer
  7. * HTTP协议
  8. *
  9. * @author walkor <worker-man@qq.com>
  10. */
  11. class WebServer extends Man\Core\SocketWorker
  12. {
  13. /**
  14. * 缓存最多多少静态文件
  15. * @var integer
  16. */
  17. const MAX_CACHE_FILE_COUNT = 100;
  18. /**
  19. * 大于这个值则文件不缓存
  20. * @var integer
  21. */
  22. const MAX_CACHE_FILE_SIZE = 300000;
  23. /**
  24. * 缓存静态文件内容
  25. * @var array
  26. */
  27. public static $fileCache = array();
  28. /**
  29. * 默认mime类型
  30. * @var string
  31. */
  32. protected static $defaultMimeType = 'text/html; charset=utf-8';
  33. /**
  34. * 服务器名到文件路径的转换
  35. * @var array ['workerman.net'=>'/home', 'www.workerman.net'=>'home/www']
  36. */
  37. protected static $serverRoot = array();
  38. /**
  39. * mime类型映射关系
  40. * @var array
  41. */
  42. protected static $mimeTypeMap = array();
  43. /**
  44. * 进程启动的时候一些初始化工作
  45. * @see Man\Core.SocketWorker::onStart()
  46. */
  47. public function onStart()
  48. {
  49. // 初始化HttpCache
  50. App\Common\Protocols\Http\HttpCache::init();
  51. // 初始化mimeMap
  52. $this->initMimeTypeMap();
  53. // 初始化ServerRoot
  54. $this->initServerRoot();
  55. }
  56. /**
  57. * 初始化mimeType
  58. * @return void
  59. */
  60. public function initMimeTypeMap()
  61. {
  62. $mime_file = \Man\Core\Lib\Config::get($this->workerName.'.include');
  63. if(!is_file($mime_file))
  64. {
  65. $this->notice("$mime_file mime.type file not fond");
  66. return;
  67. }
  68. $items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  69. if(!is_array($items))
  70. {
  71. $this->notice("get $mime_file mime.type content fail");
  72. return;
  73. }
  74. foreach($items as $content)
  75. {
  76. if(preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match))
  77. {
  78. $mime_type = $match[1];
  79. $extension_var = $match[2];
  80. $extension_array = explode(' ', substr($extension_var, 0, -1));
  81. foreach($extension_array as $extension)
  82. {
  83. self::$mimeTypeMap[$extension] = $mime_type;
  84. }
  85. }
  86. }
  87. }
  88. /**
  89. * 初始化ServerRoot
  90. * @return void
  91. */
  92. public function initServerRoot()
  93. {
  94. self::$serverRoot = \Man\Core\Lib\Config::get($this->workerName.'.root');
  95. }
  96. /**
  97. * 确定数据是否接收完整
  98. * @see Man\Core.SocketWorker::dealInput()
  99. */
  100. public function dealInput($recv_str)
  101. {
  102. return App\Common\Protocols\Http\http_input($recv_str);
  103. }
  104. /**
  105. * 数据接收完整后处理业务逻辑
  106. * @see Man\Core.SocketWorker::dealProcess()
  107. */
  108. public function dealProcess($recv_str)
  109. {
  110. // http请求处理开始。解析http协议,生成$_POST $_GET $_COOKIE
  111. App\Common\Protocols\Http\http_start($recv_str);
  112. // 请求的文件
  113. $url_info = parse_url($_SERVER['REQUEST_URI']);
  114. if(!$url_info)
  115. {
  116. App\Common\Protocols\Http\header('HTTP1.1/ 400 Bad Request');
  117. return $this->sendToClient(App\Common\Protocols\Http\http_end(''));
  118. }
  119. $path = $url_info['path'];
  120. $path_info = pathinfo($path);
  121. $extension = isset($path_info['extension']) ? $path_info['extension'] : '' ;
  122. if($extension == '')
  123. {
  124. $path = ($len = strlen($path)) && $path[$len -1] == '/' ? $path.'index.php' : $path . '/index.php';
  125. $extension = 'php';
  126. }
  127. // 命中缓存,直接返回
  128. if(isset(self::$fileCache[$path]) )
  129. {
  130. $file_content = self::$fileCache[$path];
  131. // 发送给客户端
  132. return $this->sendToClient(App\Common\Protocols\Http\http_end($file_content));
  133. }
  134. $root_dir = isset(self::$serverRoot[$_SERVER['HTTP_HOST']]) ? self::$serverRoot[$_SERVER['HTTP_HOST']] : current(self::$serverRoot);
  135. $file = "$root_dir/$path";
  136. // 请求的文件存在
  137. if(is_file($file))
  138. {
  139. // 如果请求的是php文件
  140. if($extension == 'php')
  141. {
  142. ini_set('display_errors', 'off');
  143. // 缓冲输出
  144. ob_start();
  145. // 载入php文件
  146. try
  147. {
  148. // $_SERVER变量
  149. $_SERVER['SCRIPT_NAME'] = $path;
  150. $_SERVER['REMOTE_ADDR'] = $this->getRemoteIp();
  151. $_SERVER['REMOTE_PORT'] = $this->getRemotePort();
  152. $_SERVER['SERVER_ADDR'] = $this->getLocalIp();
  153. $_SERVER['DOCUMENT_ROOT'] = $root_dir;
  154. $_SERVER['SCRIPT_FILENAME'] = $file;
  155. include $file;
  156. }
  157. catch(\Exception $e)
  158. {
  159. // 如果不是exit
  160. if($e->getMessage() != 'jump_exit')
  161. {
  162. echo $e;
  163. }
  164. }
  165. $content = ob_get_clean();
  166. ini_set('display_errors', 'on');
  167. $buffer = App\Common\Protocols\Http\http_end($content);
  168. $this->sendToClient($buffer);
  169. // 执行php每执行一次就退出(原因是有的业务使用了require_once类似的语句,不能重复加载业务逻辑)
  170. //return $this->stop();
  171. return ;
  172. }
  173. // 请求的是静态资源文件
  174. if(isset(self::$mimeTypeMap[$extension]))
  175. {
  176. App\Common\Protocols\Http\header('Content-Type: '. self::$mimeTypeMap[$extension]);
  177. }
  178. else
  179. {
  180. App\Common\Protocols\Http\header('Content-Type: '. self::$defaultMimeType);
  181. }
  182. // 获取文件信息
  183. $info = stat($file);
  184. $modified_time = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' GMT' : '';
  185. // 如果有$_SERVER['HTTP_IF_MODIFIED_SINCE']
  186. if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info)
  187. {
  188. // 文件没有更改则直接304
  189. if($modified_time === $_SERVER['HTTP_IF_MODIFIED_SINCE'])
  190. {
  191. // 304
  192. App\Common\Protocols\Http\header('HTTP/1.1 304 Not Modified');
  193. // 发送给客户端
  194. return $this->sendToClient(App\Common\Protocols\Http\http_end(''));
  195. }
  196. }
  197. if(!isset(self::$fileCache[$file]) )
  198. {
  199. $file_content = file_get_contents($file);
  200. // 缓存文件
  201. if($info['size'] < self::MAX_CACHE_FILE_SIZE && $file_content)
  202. {
  203. self::$fileCache[$file] = $file_content;
  204. // 缓存满了删除一个文件
  205. if(count(self::$fileCache) > self::MAX_CACHE_FILE_COUNT)
  206. {
  207. // 删除第一个缓存的文件
  208. reset(self::$fileCache);
  209. unset(self::$fileCache[key(self::$fileCache)]);
  210. }
  211. }
  212. }
  213. else
  214. {
  215. $file_content = self::$fileCache[$file];
  216. }
  217. if($modified_time)
  218. {
  219. App\Common\Protocols\Http\header("Last-Modified: $modified_time");
  220. }
  221. // 发送给客户端
  222. return $this->sendToClient(App\Common\Protocols\Http\http_end($file_content));
  223. }
  224. else
  225. {
  226. // 404
  227. App\Common\Protocols\Http\header("HTTP/1.1 404 Not Found");
  228. return $this->sendToClient(App\Common\Protocols\Http\http_end('<html><head><title>页面不存在</title></head><body><h3>WorkerMan提醒你,文件不存在</h3></body></html>'));
  229. }
  230. }
  231. }