ServerService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <?php
  2. namespace App\Services;
  3. use App\Models\ServerLog;
  4. use App\Models\ServerShadowsocks;
  5. use App\Models\User;
  6. use App\Models\Server;
  7. use App\Models\ServerTrojan;
  8. use App\Utils\CacheKey;
  9. use Illuminate\Support\Facades\Cache;
  10. class ServerService
  11. {
  12. CONST V2RAY_CONFIG = '{"api":{"services":["HandlerService","StatsService"],"tag":"api"},"dns":{},"stats":{},"inbound":{"port":443,"protocol":"vmess","settings":{"clients":[]},"sniffing":{"enabled":true,"destOverride":["http","tls"]},"streamSettings":{"network":"tcp"},"tag":"proxy"},"inboundDetour":[{"listen":"127.0.0.1","port":23333,"protocol":"dokodemo-door","settings":{"address":"0.0.0.0"},"tag":"api"}],"log":{"loglevel":"debug","access":"access.log","error":"error.log"},"outbound":{"protocol":"freedom","settings":{}},"outboundDetour":[{"protocol":"blackhole","settings":{},"tag":"block"}],"routing":{"rules":[{"inboundTag":"api","outboundTag":"api","type":"field"}]},"policy":{"levels":{"0":{"handshake":4,"connIdle":300,"uplinkOnly":5,"downlinkOnly":30,"statsUserUplink":true,"statsUserDownlink":true}}}}';
  13. CONST TROJAN_CONFIG = '{"run_type":"server","local_addr":"0.0.0.0","local_port":443,"remote_addr":"www.taobao.com","remote_port":80,"password":[],"ssl":{"cert":"server.crt","key":"server.key","sni":"domain.com"},"api":{"enabled":true,"api_addr":"127.0.0.1","api_port":10000}}';
  14. public function getV2ray(User $user, $all = false):array
  15. {
  16. $servers = [];
  17. $model = Server::orderBy('sort', 'ASC');
  18. if (!$all) {
  19. $model->where('show', 1);
  20. }
  21. $v2ray = $model->get();
  22. for ($i = 0; $i < count($v2ray); $i++) {
  23. $v2ray[$i]['type'] = 'v2ray';
  24. $groupId = json_decode($v2ray[$i]['group_id']);
  25. if (in_array($user->group_id, $groupId)) {
  26. if ($v2ray[$i]['parent_id']) {
  27. $v2ray[$i]['last_check_at'] = Cache::get(CacheKey::get('SERVER_V2RAY_LAST_CHECK_AT', $v2ray[$i]['parent_id']));
  28. } else {
  29. $v2ray[$i]['last_check_at'] = Cache::get(CacheKey::get('SERVER_V2RAY_LAST_CHECK_AT', $v2ray[$i]['id']));
  30. }
  31. array_push($servers, $v2ray[$i]->toArray());
  32. }
  33. }
  34. return $servers;
  35. }
  36. public function getTrojan(User $user, $all = false):array
  37. {
  38. $servers = [];
  39. $model = ServerTrojan::orderBy('sort', 'ASC');
  40. if (!$all) {
  41. $model->where('show', 1);
  42. }
  43. $trojan = $model->get();
  44. for ($i = 0; $i < count($trojan); $i++) {
  45. $trojan[$i]['type'] = 'trojan';
  46. $groupId = json_decode($trojan[$i]['group_id']);
  47. if (in_array($user->group_id, $groupId)) {
  48. if ($trojan[$i]['parent_id']) {
  49. $trojan[$i]['last_check_at'] = Cache::get(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $trojan[$i]['parent_id']));
  50. } else {
  51. $trojan[$i]['last_check_at'] = Cache::get(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $trojan[$i]['id']));
  52. }
  53. array_push($servers, $trojan[$i]->toArray());
  54. }
  55. }
  56. return $servers;
  57. }
  58. public function getShadowsocks(User $user, $all = false)
  59. {
  60. $servers = [];
  61. $model = ServerShadowsocks::orderBy('sort', 'ASC');
  62. if (!$all) {
  63. $model->where('show', 1);
  64. }
  65. $shadowsocks = $model->get();
  66. for ($i = 0; $i < count($shadowsocks); $i++) {
  67. $shadowsocks[$i]['type'] = 'shadowsocks';
  68. $groupId = json_decode($shadowsocks[$i]['group_id']);
  69. if (in_array($user->group_id, $groupId)) {
  70. if ($shadowsocks[$i]['parent_id']) {
  71. $shadowsocks[$i]['last_check_at'] = Cache::get(CacheKey::get('SERVER_SHADOWSOCKS_LAST_CHECK_AT', $shadowsocks[$i]['parent_id']));
  72. } else {
  73. $shadowsocks[$i]['last_check_at'] = Cache::get(CacheKey::get('SERVER_SHADOWSOCKS_LAST_CHECK_AT', $shadowsocks[$i]['id']));
  74. }
  75. array_push($servers, $shadowsocks[$i]->toArray());
  76. }
  77. }
  78. return $servers;
  79. }
  80. public function getAvailableServers(User $user, $all = false)
  81. {
  82. $servers = array_merge(
  83. $this->getShadowsocks($user, $all),
  84. $this->getV2ray($user, $all),
  85. $this->getTrojan($user, $all)
  86. );
  87. $tmp = array_column($servers, 'sort');
  88. array_multisort($tmp, SORT_ASC, $servers);
  89. return $servers;
  90. }
  91. public function getAvailableUsers($groupId)
  92. {
  93. return User::whereIn('group_id', $groupId)
  94. ->whereRaw('u + d < transfer_enable')
  95. ->where(function ($query) {
  96. $query->where('expired_at', '>=', time())
  97. ->orWhere('expired_at', NULL);
  98. })
  99. ->where('banned', 0)
  100. ->select([
  101. 'id',
  102. 'email',
  103. 't',
  104. 'u',
  105. 'd',
  106. 'transfer_enable',
  107. 'uuid'
  108. ])
  109. ->get();
  110. }
  111. public function getV2RayConfig(int $nodeId, int $localPort)
  112. {
  113. $server = Server::find($nodeId);
  114. if (!$server) {
  115. abort(500, '节点不存在');
  116. }
  117. $json = json_decode(self::V2RAY_CONFIG);
  118. $json->log->loglevel = (int)config('v2board.server_log_enable') ? 'debug' : 'none';
  119. $json->inboundDetour[0]->port = (int)$localPort;
  120. $json->inbound->port = (int)$server->server_port;
  121. $json->inbound->streamSettings->network = $server->network;
  122. $this->setDns($server, $json);
  123. $this->setNetwork($server, $json);
  124. $this->setRule($server, $json);
  125. $this->setTls($server, $json);
  126. return $json;
  127. }
  128. public function getTrojanConfig(int $nodeId, int $localPort)
  129. {
  130. $server = ServerTrojan::find($nodeId);
  131. if (!$server) {
  132. abort(500, '节点不存在');
  133. }
  134. $json = json_decode(self::TROJAN_CONFIG);
  135. $json->local_port = $server->server_port;
  136. $json->ssl->sni = $server->server_name ? $server->server_name : $server->host;
  137. $json->ssl->cert = "/root/.cert/server.crt";
  138. $json->ssl->key = "/root/.cert/server.key";
  139. $json->api->api_port = $localPort;
  140. return $json;
  141. }
  142. private function setDns(Server $server, object $json)
  143. {
  144. if ($server->dnsSettings) {
  145. $dns = json_decode($server->dnsSettings);
  146. if (isset($dns->servers)) {
  147. array_push($dns->servers, '1.1.1.1');
  148. array_push($dns->servers, 'localhost');
  149. }
  150. $json->dns = $dns;
  151. $json->outbound->settings->domainStrategy = 'UseIP';
  152. }
  153. }
  154. private function setNetwork(Server $server, object $json)
  155. {
  156. if ($server->networkSettings) {
  157. switch ($server->network) {
  158. case 'tcp':
  159. $json->inbound->streamSettings->tcpSettings = json_decode($server->networkSettings);
  160. break;
  161. case 'kcp':
  162. $json->inbound->streamSettings->kcpSettings = json_decode($server->networkSettings);
  163. break;
  164. case 'ws':
  165. $json->inbound->streamSettings->wsSettings = json_decode($server->networkSettings);
  166. break;
  167. case 'http':
  168. $json->inbound->streamSettings->httpSettings = json_decode($server->networkSettings);
  169. break;
  170. case 'domainsocket':
  171. $json->inbound->streamSettings->dsSettings = json_decode($server->networkSettings);
  172. break;
  173. case 'quic':
  174. $json->inbound->streamSettings->quicSettings = json_decode($server->networkSettings);
  175. break;
  176. case 'grpc':
  177. $json->inbound->streamSettings->grpcSettings = json_decode($server->networkSettings);
  178. break;
  179. }
  180. }
  181. }
  182. private function setRule(Server $server, object $json)
  183. {
  184. $domainRules = array_filter(explode(PHP_EOL, config('v2board.server_v2ray_domain')));
  185. $protocolRules = array_filter(explode(PHP_EOL, config('v2board.server_v2ray_protocol')));
  186. if ($server->ruleSettings) {
  187. $ruleSettings = json_decode($server->ruleSettings);
  188. // domain
  189. if (isset($ruleSettings->domain)) {
  190. $ruleSettings->domain = array_filter($ruleSettings->domain);
  191. if (!empty($ruleSettings->domain)) {
  192. $domainRules = array_merge($domainRules, $ruleSettings->domain);
  193. }
  194. }
  195. // protocol
  196. if (isset($ruleSettings->protocol)) {
  197. $ruleSettings->protocol = array_filter($ruleSettings->protocol);
  198. if (!empty($ruleSettings->protocol)) {
  199. $protocolRules = array_merge($protocolRules, $ruleSettings->protocol);
  200. }
  201. }
  202. }
  203. if (!empty($domainRules)) {
  204. $domainObj = new \StdClass();
  205. $domainObj->type = 'field';
  206. $domainObj->domain = $domainRules;
  207. $domainObj->outboundTag = 'block';
  208. array_push($json->routing->rules, $domainObj);
  209. }
  210. if (!empty($protocolRules)) {
  211. $protocolObj = new \StdClass();
  212. $protocolObj->type = 'field';
  213. $protocolObj->protocol = $protocolRules;
  214. $protocolObj->outboundTag = 'block';
  215. array_push($json->routing->rules, $protocolObj);
  216. }
  217. if (empty($domainRules) && empty($protocolRules)) {
  218. $json->inbound->sniffing->enabled = false;
  219. }
  220. }
  221. private function setTls(Server $server, object $json)
  222. {
  223. if ((int)$server->tls) {
  224. $tlsSettings = json_decode($server->tlsSettings);
  225. $json->inbound->streamSettings->security = 'tls';
  226. $tls = (object)[
  227. 'certificateFile' => '/root/.cert/server.crt',
  228. 'keyFile' => '/root/.cert/server.key'
  229. ];
  230. $json->inbound->streamSettings->tlsSettings = new \StdClass();
  231. if (isset($tlsSettings->serverName)) {
  232. $json->inbound->streamSettings->tlsSettings->serverName = (string)$tlsSettings->serverName;
  233. }
  234. if (isset($tlsSettings->allowInsecure)) {
  235. $json->inbound->streamSettings->tlsSettings->allowInsecure = (int)$tlsSettings->allowInsecure ? true : false;
  236. }
  237. $json->inbound->streamSettings->tlsSettings->certificates[0] = $tls;
  238. }
  239. }
  240. public function log(int $userId, int $serverId, int $u, int $d, float $rate, string $method)
  241. {
  242. if (($u + $d) <= 10240) return;
  243. $timestamp = strtotime(date('Y-m-d H:0'));
  244. $serverLog = ServerLog::where('log_at', '>=', $timestamp)
  245. ->where('log_at', '<', $timestamp + 3600)
  246. ->where('server_id', $serverId)
  247. ->where('user_id', $userId)
  248. ->where('rate', $rate)
  249. ->where('method', $method)
  250. ->lockForUpdate()
  251. ->first();
  252. if ($serverLog) {
  253. $serverLog->u = $serverLog->u + $u;
  254. $serverLog->d = $serverLog->d + $d;
  255. $serverLog->save();
  256. } else {
  257. $serverLog = new ServerLog();
  258. $serverLog->user_id = $userId;
  259. $serverLog->server_id = $serverId;
  260. $serverLog->u = $u;
  261. $serverLog->d = $d;
  262. $serverLog->rate = $rate;
  263. $serverLog->log_at = $timestamp;
  264. $serverLog->method = $method;
  265. $serverLog->save();
  266. }
  267. }
  268. public function getShadowsocksServers()
  269. {
  270. $server = ServerShadowsocks::orderBy('sort', 'ASC')->get();
  271. for ($i = 0; $i < count($server); $i++) {
  272. $server[$i]['type'] = 'shadowsocks';
  273. if (!empty($server[$i]['tags'])) {
  274. $server[$i]['tags'] = json_decode($server[$i]['tags']);
  275. }
  276. $server[$i]['group_id'] = json_decode($server[$i]['group_id']);
  277. }
  278. return $server->toArray();
  279. }
  280. public function getV2rayServers()
  281. {
  282. $server = Server::orderBy('sort', 'ASC')->get();
  283. for ($i = 0; $i < count($server); $i++) {
  284. $server[$i]['type'] = 'v2ray';
  285. if (!empty($server[$i]['tags'])) {
  286. $server[$i]['tags'] = json_decode($server[$i]['tags']);
  287. }
  288. if (!empty($server[$i]['dnsSettings'])) {
  289. $server[$i]['dnsSettings'] = json_decode($server[$i]['dnsSettings']);
  290. }
  291. if (!empty($server[$i]['tlsSettings'])) {
  292. $server[$i]['tlsSettings'] = json_decode($server[$i]['tlsSettings']);
  293. }
  294. if (!empty($server[$i]['ruleSettings'])) {
  295. $server[$i]['ruleSettings'] = json_decode($server[$i]['ruleSettings']);
  296. }
  297. $server[$i]['group_id'] = json_decode($server[$i]['group_id']);
  298. }
  299. return $server->toArray();
  300. }
  301. public function getTrojanServers()
  302. {
  303. $server = ServerTrojan::orderBy('sort', 'ASC')->get();
  304. for ($i = 0; $i < count($server); $i++) {
  305. $server[$i]['type'] = 'trojan';
  306. if (!empty($server[$i]['tags'])) {
  307. $server[$i]['tags'] = json_decode($server[$i]['tags']);
  308. }
  309. $server[$i]['group_id'] = json_decode($server[$i]['group_id']);
  310. }
  311. return $server->toArray();
  312. }
  313. public function mergeData(&$servers)
  314. {
  315. foreach ($servers as $k => $v) {
  316. $serverType = strtoupper($servers[$k]['type']);
  317. $servers[$k]['online'] = Cache::get(CacheKey::get("SERVER_{$serverType}_ONLINE_USER", $servers[$k]['parent_id'] ? $servers[$k]['parent_id'] : $servers[$k]['id']));
  318. if ($servers[$k]['parent_id']) {
  319. $servers[$k]['last_check_at'] = Cache::get(CacheKey::get("SERVER_{$serverType}_LAST_CHECK_AT", $servers[$k]['parent_id']));
  320. $servers[$k]['last_push_at'] = Cache::get(CacheKey::get("SERVER_{$serverType}_LAST_PUSH_AT", $servers[$k]['parent_id']));
  321. } else {
  322. $servers[$k]['last_check_at'] = Cache::get(CacheKey::get("SERVER_{$serverType}_LAST_CHECK_AT", $servers[$k]['id']));
  323. $servers[$k]['last_push_at'] = Cache::get(CacheKey::get("SERVER_{$serverType}_LAST_PUSH_AT", $servers[$k]['id']));
  324. }
  325. if ((time() - 300) >= $servers[$k]['last_check_at']) {
  326. $servers[$k]['available_status'] = 0;
  327. } else if ((time() - 300) >= $servers[$k]['last_push_at']) {
  328. $servers[$k]['available_status'] = 1;
  329. } else {
  330. $servers[$k]['available_status'] = 2;
  331. }
  332. }
  333. }
  334. public function getAllServers()
  335. {
  336. $servers = array_merge(
  337. $this->getShadowsocksServers(),
  338. $this->getV2rayServers(),
  339. $this->getTrojanServers()
  340. );
  341. $this->mergeData($servers);
  342. $tmp = array_column($servers, 'sort');
  343. array_multisort($tmp, SORT_ASC, $servers);
  344. return $servers;
  345. }
  346. }