WebServer.php 9.9 KB

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