WebServer.php 9.5 KB

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