ServerService.php 14 KB

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