WebServer.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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\Protocols\Http;
  16. use Workerman\Protocols\HttpCache;
  17. /**
  18. * WebServer.
  19. */
  20. class WebServer extends Worker
  21. {
  22. /**
  23. * Mime.
  24. * @var string
  25. */
  26. protected static $defaultMimeType = 'text/html; charset=utf-8';
  27. /**
  28. * Virtual host to path mapping.
  29. * @var array ['workerman.net'=>'/home', 'www.workerman.net'=>'home/www']
  30. */
  31. protected $serverRoot = array();
  32. /**
  33. * Mime mapping.
  34. * @var array
  35. */
  36. protected static $mimeTypeMap = array();
  37. /**
  38. * Used to save user OnWorkerStart callback settings.
  39. * @var callback
  40. */
  41. protected $_onWorkerStart = null;
  42. /**
  43. * Add virtual host.
  44. * @param string $domain
  45. * @param string $root_path
  46. * @return void
  47. */
  48. public function addRoot($domain, $root_path)
  49. {
  50. $this->serverRoot[$domain] = $root_path;
  51. }
  52. /**
  53. * Construct.
  54. * @param string $socket_name
  55. * @param array $context_option
  56. */
  57. public function __construct($socket_name, $context_option = array())
  58. {
  59. list(, $address) = explode(':', $socket_name, 2);
  60. parent::__construct('http:'.$address, $context_option);
  61. $this->name = 'WebServer';
  62. }
  63. /**
  64. * Run webserver instance.
  65. * @see Workerman.Worker::run()
  66. */
  67. public function run()
  68. {
  69. $this->_onWorkerStart = $this->onWorkerStart;
  70. $this->onWorkerStart = array($this, 'onWorkerStart');
  71. $this->onMessage = array($this, 'onMessage');
  72. parent::run();
  73. }
  74. /**
  75. * Emit when process start.
  76. * @throws \Exception
  77. */
  78. public function onWorkerStart()
  79. {
  80. if(empty($this->serverRoot))
  81. {
  82. throw new \Exception('server root not set, please use WebServer::addRoot($domain, $root_path) to set server root path');
  83. }
  84. // Init HttpCache.
  85. HttpCache::init();
  86. // Init mimeMap.
  87. $this->initMimeTypeMap();
  88. // Try to emit onWorkerStart callback.
  89. if($this->_onWorkerStart)
  90. {
  91. try
  92. {
  93. call_user_func($this->_onWorkerStart, $this);
  94. }
  95. catch(\Exception $e)
  96. {
  97. echo $e;
  98. exit(250);
  99. }
  100. }
  101. }
  102. /**
  103. * Init mime map.
  104. * @return void
  105. */
  106. public function initMimeTypeMap()
  107. {
  108. $mime_file = Http::getMimeTypesFile();
  109. if(!is_file($mime_file))
  110. {
  111. $this->log("$mime_file mime.type file not fond");
  112. return;
  113. }
  114. $items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  115. if(!is_array($items))
  116. {
  117. $this->log("get $mime_file mime.type content fail");
  118. return;
  119. }
  120. foreach($items as $content)
  121. {
  122. if(preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match))
  123. {
  124. $mime_type = $match[1];
  125. $workerman_file_extension_var = $match[2];
  126. $workerman_file_extension_array = explode(' ', substr($workerman_file_extension_var, 0, -1));
  127. foreach($workerman_file_extension_array as $workerman_file_extension)
  128. {
  129. self::$mimeTypeMap[$workerman_file_extension] = $mime_type;
  130. }
  131. }
  132. }
  133. }
  134. /**
  135. * Emit when http message coming.
  136. * @param Connection\TcpConnection $connection
  137. * @return void
  138. */
  139. public function onMessage($connection)
  140. {
  141. // REQUEST_URI.
  142. $workerman_url_info = parse_url($_SERVER['REQUEST_URI']);
  143. if(!$workerman_url_info)
  144. {
  145. Http::header('HTTP/1.1 400 Bad Request');
  146. $connection->close('<h1>400 Bad Request</h1>');
  147. return;
  148. }
  149. $workerman_path = $workerman_url_info['path'];
  150. $workerman_path_info = pathinfo($workerman_path);
  151. $workerman_file_extension = isset($workerman_path_info['extension']) ? $workerman_path_info['extension'] : '' ;
  152. if($workerman_file_extension === '')
  153. {
  154. $workerman_path = ($len = strlen($workerman_path)) && $workerman_path[$len -1] === '/' ? $workerman_path.'index.php' : $workerman_path . '/index.php';
  155. $workerman_file_extension = 'php';
  156. }
  157. $workerman_root_dir = isset($this->serverRoot[$_SERVER['SERVER_NAME']]) ? $this->serverRoot[$_SERVER['SERVER_NAME']] : current($this->serverRoot);
  158. $workerman_file = "$workerman_root_dir/$workerman_path";
  159. if($workerman_file_extension === 'php' && !is_file($workerman_file))
  160. {
  161. $workerman_file = "$workerman_root_dir/index.php";
  162. if(!is_file($workerman_file))
  163. {
  164. $workerman_file = "$workerman_root_dir/index.html";
  165. $workerman_file_extension = 'html';
  166. }
  167. }
  168. // File exsits.
  169. if(is_file($workerman_file))
  170. {
  171. // Security check.
  172. if((!($workerman_request_realpath = realpath($workerman_file)) || !($workerman_root_dir_realpath = realpath($workerman_root_dir))) || 0 !== strpos($workerman_request_realpath, $workerman_root_dir_realpath))
  173. {
  174. Http::header('HTTP/1.1 400 Bad Request');
  175. $connection->close('<h1>400 Bad Request</h1>');
  176. return;
  177. }
  178. $workerman_file = realpath($workerman_file);
  179. // Request php file.
  180. if($workerman_file_extension === 'php')
  181. {
  182. $workerman_cwd = getcwd();
  183. chdir($workerman_root_dir);
  184. ini_set('display_errors', 'off');
  185. ob_start();
  186. // Try to include php file.
  187. try
  188. {
  189. // $_SERVER.
  190. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  191. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  192. include $workerman_file;
  193. }
  194. catch(\Exception $e)
  195. {
  196. // Jump_exit?
  197. if($e->getMessage() != 'jump_exit')
  198. {
  199. echo $e;
  200. }
  201. }
  202. $content = ob_get_clean();
  203. ini_set('display_errors', 'on');
  204. $connection->close($content);
  205. chdir($workerman_cwd);
  206. return;
  207. }
  208. // Static resource file request.
  209. if(isset(self::$mimeTypeMap[$workerman_file_extension]))
  210. {
  211. Http::header('Content-Type: '. self::$mimeTypeMap[$workerman_file_extension]);
  212. }
  213. else
  214. {
  215. Http::header('Content-Type: '. self::$defaultMimeType);
  216. }
  217. // Get file stat.
  218. $info = stat($workerman_file);
  219. $modified_time = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' GMT' : '';
  220. if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info)
  221. {
  222. // Http 304.
  223. if($modified_time === $_SERVER['HTTP_IF_MODIFIED_SINCE'])
  224. {
  225. // 304
  226. Http::header('HTTP/1.1 304 Not Modified');
  227. // Send nothing but http headers..
  228. $connection->close('');
  229. return;
  230. }
  231. }
  232. if($modified_time)
  233. {
  234. Http::header("Last-Modified: $modified_time");
  235. }
  236. // Send to client.
  237. $connection->close(file_get_contents($workerman_file));
  238. return;
  239. }
  240. else
  241. {
  242. // 404
  243. Http::header("HTTP/1.1 404 Not Found");
  244. $connection->close('<html><head><title>404 File not found</title></head><body><center><h3>404 Not Found</h3></center></body></html>');
  245. return;
  246. }
  247. }
  248. }