WebServer.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. <?php
  2. namespace Workerman;
  3. use \Workerman\Worker;
  4. use \Workerman\Protocols\Http;
  5. use \Workerman\Protocols\HttpCache;
  6. /**
  7. *
  8. * WebServer
  9. * HTTP协议
  10. *
  11. * @author walkor <walkor@workerman.net>
  12. */
  13. class WebServer extends Worker
  14. {
  15. /**
  16. * 默认mime类型
  17. * @var string
  18. */
  19. protected static $defaultMimeType = 'text/html; charset=utf-8';
  20. /**
  21. * 服务器名到文件路径的转换
  22. * @var array ['workerman.net'=>'/home', 'www.workerman.net'=>'home/www']
  23. */
  24. protected $serverRoot = array();
  25. /**
  26. * mime类型映射关系
  27. * @var array
  28. */
  29. protected static $mimeTypeMap = array();
  30. /**
  31. * add server root
  32. */
  33. public function addRoot($domain, $root_path)
  34. {
  35. $this->serverRoot[$domain] = $root_path;
  36. }
  37. /**
  38. *
  39. * @param string $socket_name
  40. * @param array $context_option
  41. */
  42. public function __construct($socket_name, $context_option = array())
  43. {
  44. $this->onWorkerStart = array($this, 'onWorkerStart');
  45. $this->onMessage = array($this, 'onMessage');
  46. $this->name = 'WebServer';
  47. list($scheme, $address) = explode(':', $socket_name, 2);
  48. parent::__construct('http:'.$address, $context_option);
  49. }
  50. /**
  51. * 进程启动的时候一些初始化工作
  52. */
  53. public function onWorkerStart()
  54. {
  55. if(empty($this->serverRoot))
  56. {
  57. throw new \Exception('server root not set, please use WebServer::addRoot($domain, $root_path) to set server root path');
  58. }
  59. // 初始化HttpCache
  60. HttpCache::init();
  61. // 初始化mimeMap
  62. $this->initMimeTypeMap();
  63. }
  64. /**
  65. * 初始化mimeType
  66. * @return void
  67. */
  68. public function initMimeTypeMap()
  69. {
  70. $mime_file = Http::getMimeTypesFile();
  71. if(!is_file($mime_file))
  72. {
  73. $this->notice("$mime_file mime.type file not fond");
  74. return;
  75. }
  76. $items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  77. if(!is_array($items))
  78. {
  79. $this->log("get $mime_file mime.type content fail");
  80. return;
  81. }
  82. foreach($items as $content)
  83. {
  84. if(preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match))
  85. {
  86. $mime_type = $match[1];
  87. $extension_var = $match[2];
  88. $extension_array = explode(' ', substr($extension_var, 0, -1));
  89. foreach($extension_array as $extension)
  90. {
  91. self::$mimeTypeMap[$extension] = $mime_type;
  92. }
  93. }
  94. }
  95. }
  96. /**
  97. * 数据接收完整后处理业务逻辑
  98. */
  99. public function onMessage($connection, $data)
  100. {
  101. // 请求的文件
  102. $url_info = parse_url($_SERVER['REQUEST_URI']);
  103. if(!$url_info)
  104. {
  105. Http::header('HTTP/1.1 400 Bad Request');
  106. return $connection->close('<h1>400 Bad Request</h1>');
  107. }
  108. $path = $url_info['path'];
  109. $path_info = pathinfo($path);
  110. $extension = isset($path_info['extension']) ? $path_info['extension'] : '' ;
  111. if($extension == '')
  112. {
  113. $path = ($len = strlen($path)) && $path[$len -1] == '/' ? $path.'index.php' : $path . '/index.php';
  114. $extension = 'php';
  115. }
  116. $root_dir = isset($this->serverRoot[$_SERVER['HTTP_HOST']]) ? $this->serverRoot[$_SERVER['HTTP_HOST']] : current($this->serverRoot);
  117. $file = "$root_dir/$path";
  118. // 对应的php文件不存在则直接使用根目录的index.php
  119. if($extension == 'php' && !is_file($file))
  120. {
  121. $file = "$root_dir/index.php";
  122. }
  123. // 请求的文件存在
  124. if(is_file($file))
  125. {
  126. // 判断是否是站点目录里的文件
  127. if((!($request_realpath = realpath($file)) || !($root_dir_realpath = realpath($root_dir))) || 0 !== strpos($request_realpath, $root_dir_realpath))
  128. {
  129. Http::header('HTTP/1.1 400 Bad Request');
  130. return $connection->close('<h1>400 Bad Request</h1>');
  131. }
  132. $file = realpath($file);
  133. // 如果请求的是php文件
  134. if($extension == 'php')
  135. {
  136. $cwd = getcwd();
  137. chdir($root_dir);
  138. ini_set('display_errors', 'off');
  139. // 缓冲输出
  140. ob_start();
  141. // 载入php文件
  142. try
  143. {
  144. // $_SERVER变量
  145. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  146. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  147. include $file;
  148. }
  149. catch(\Exception $e)
  150. {
  151. // 如果不是exit
  152. if($e->getMessage() != 'jump_exit')
  153. {
  154. echo $e;
  155. }
  156. }
  157. $content = ob_get_clean();
  158. ini_set('display_errors', 'on');
  159. $connection->close($content);
  160. chdir($cwd);
  161. return ;
  162. }
  163. // 请求的是静态资源文件
  164. if(isset(self::$mimeTypeMap[$extension]))
  165. {
  166. Http::header('Content-Type: '. self::$mimeTypeMap[$extension]);
  167. }
  168. else
  169. {
  170. Http::header('Content-Type: '. self::$defaultMimeType);
  171. }
  172. // 获取文件信息
  173. $info = stat($file);
  174. $modified_time = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' GMT' : '';
  175. // 如果有$_SERVER['HTTP_IF_MODIFIED_SINCE']
  176. if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info)
  177. {
  178. // 文件没有更改则直接304
  179. if($modified_time === $_SERVER['HTTP_IF_MODIFIED_SINCE'])
  180. {
  181. // 304
  182. Http::header('HTTP/1.1 304 Not Modified');
  183. // 发送给客户端
  184. return $connection->close('');
  185. }
  186. }
  187. if($modified_time)
  188. {
  189. Http::header("Last-Modified: $modified_time");
  190. }
  191. // 发送给客户端
  192. return $connection->close(file_get_contents($file));
  193. }
  194. else
  195. {
  196. // 404
  197. Http::header("HTTP/1.1 404 Not Found");
  198. return $connection->close('<html><head><title>404 页面不存在</title></head><body><center><h3>404 Not Found</h3></center></body></html>');
  199. }
  200. }
  201. }