ServerService.php 14 KB

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