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