ServerService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 App\Utils\Helper;
  10. use App\Utils\URLSchemes;
  11. use Illuminate\Support\Facades\Cache;
  12. class ServerService
  13. {
  14. 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":"0.0.0.0","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}}}}';
  15. 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}}';
  16. public function getVmess(User $user, $all = false):array
  17. {
  18. $vmess = [];
  19. $model = Server::orderBy('sort', 'ASC');
  20. if (!$all) {
  21. $model->where('show', 1);
  22. }
  23. $vmesss = $model->get();
  24. foreach ($vmesss as $k => $v) {
  25. $vmesss[$k]['protocol_type'] = 'vmess';
  26. $groupId = json_decode($vmesss[$k]['group_id']);
  27. if (in_array($user->group_id, $groupId)) {
  28. $vmesss[$k]['link'] = URLSchemes::buildVmess($vmesss[$k], $user);
  29. if ($vmesss[$k]['parent_id']) {
  30. $vmesss[$k]['last_check_at'] = Cache::get(CacheKey::get('SERVER_V2RAY_LAST_CHECK_AT', $vmesss[$k]['parent_id']));
  31. } else {
  32. $vmesss[$k]['last_check_at'] = Cache::get(CacheKey::get('SERVER_V2RAY_LAST_CHECK_AT', $vmesss[$k]['id']));
  33. }
  34. array_push($vmess, $vmesss[$k]);
  35. }
  36. }
  37. return $vmess;
  38. }
  39. public function getTrojan(User $user, $all = false)
  40. {
  41. $trojan = [];
  42. $model = ServerTrojan::orderBy('sort', 'ASC');
  43. if (!$all) {
  44. $model->where('show', 1);
  45. }
  46. $trojans = $model->get();
  47. foreach ($trojans as $k => $v) {
  48. $trojans[$k]['protocol_type'] = 'trojan';
  49. $groupId = json_decode($trojans[$k]['group_id']);
  50. $trojans[$k]['link'] = URLSchemes::buildTrojan($trojans[$k], $user);
  51. if (in_array($user->group_id, $groupId)) {
  52. if ($trojans[$k]['parent_id']) {
  53. $trojans[$k]['last_check_at'] = Cache::get(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $trojans[$k]['parent_id']));
  54. } else {
  55. $trojans[$k]['last_check_at'] = Cache::get(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $trojans[$k]['id']));
  56. }
  57. array_push($trojan, $trojans[$k]);
  58. }
  59. }
  60. return $trojan;
  61. }
  62. public function getShadowsocks(User $user, $all = false)
  63. {
  64. $shadowsocks = [];
  65. $model = ServerShadowsocks::orderBy('sort', 'ASC');
  66. if (!$all) {
  67. $model->where('show', 1);
  68. }
  69. $shadowsockss = $model->get();
  70. foreach ($shadowsockss as $k => $v) {
  71. $shadowsockss[$k]['protocol_type'] = 'shadowsocks';
  72. $groupId = json_decode($shadowsockss[$k]['group_id']);
  73. $shadowsockss[$k]['link'] = URLSchemes::buildShadowsocks($shadowsockss[$k], $user);
  74. if (in_array($user->group_id, $groupId)) {
  75. if ($shadowsockss[$k]['parent_id']) {
  76. $shadowsockss[$k]['last_check_at'] = Cache::get(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $shadowsockss[$k]['parent_id']));
  77. } else {
  78. $shadowsockss[$k]['last_check_at'] = Cache::get(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $shadowsockss[$k]['id']));
  79. }
  80. array_push($shadowsocks, $shadowsockss[$k]);
  81. }
  82. }
  83. return $shadowsocks;
  84. }
  85. public function getAllServers(User $user, $all = false)
  86. {
  87. return [
  88. 'shadowsocks' => $this->getShadowsocks($user, $all),
  89. 'vmess' => $this->getVmess($user, $all),
  90. 'trojan' => $this->getTrojan($user, $all)
  91. ];
  92. }
  93. public function getAvailableUsers($groupId)
  94. {
  95. return User::whereIn('group_id', $groupId)
  96. ->whereRaw('u + d < transfer_enable')
  97. ->where(function ($query) {
  98. $query->where('expired_at', '>=', time())
  99. ->orWhere('expired_at', NULL);
  100. })
  101. ->where('banned', 0)
  102. ->select([
  103. 'id',
  104. 'email',
  105. 't',
  106. 'u',
  107. 'd',
  108. 'transfer_enable',
  109. 'uuid',
  110. 'v2ray_alter_id',
  111. 'v2ray_level'
  112. ])
  113. ->get();
  114. }
  115. public function getVmessConfig(int $nodeId, int $localPort)
  116. {
  117. $server = Server::find($nodeId);
  118. if (!$server) {
  119. abort(500, '节点不存在');
  120. }
  121. $json = json_decode(self::V2RAY_CONFIG);
  122. $json->log->loglevel = config('v2board.server_log_level', 'none');
  123. $json->inboundDetour[0]->port = (int)$localPort;
  124. $json->inbound->port = (int)$server->server_port;
  125. $json->inbound->streamSettings->network = $server->network;
  126. $this->setDns($server, $json);
  127. $this->setNetwork($server, $json);
  128. $this->setRule($server, $json);
  129. $this->setTls($server, $json);
  130. return $json;
  131. }
  132. public function getTrojanConfig(int $nodeId, int $localPort)
  133. {
  134. $server = ServerTrojan::find($nodeId);
  135. if (!$server) {
  136. abort(500, '节点不存在');
  137. }
  138. $json = json_decode(self::TROJAN_CONFIG);
  139. $json->local_port = $server->server_port;
  140. $json->ssl->sni = $server->server_name ? $server->server_name : $server->host;
  141. $json->ssl->cert = "/root/.cert/server.crt";
  142. $json->ssl->key = "/root/.cert/server.key";
  143. $json->api->api_port = $localPort;
  144. return $json;
  145. }
  146. private function setDns(Server $server, object $json)
  147. {
  148. if ($server->dnsSettings) {
  149. $dns = json_decode($server->dnsSettings);
  150. if (isset($dns->servers)) {
  151. array_push($dns->servers, '1.1.1.1');
  152. array_push($dns->servers, 'localhost');
  153. }
  154. $json->dns = $dns;
  155. $json->outbound->settings->domainStrategy = 'UseIP';
  156. }
  157. }
  158. private function setNetwork(Server $server, object $json)
  159. {
  160. if ($server->networkSettings) {
  161. switch ($server->network) {
  162. case 'tcp':
  163. $json->inbound->streamSettings->tcpSettings = json_decode($server->networkSettings);
  164. break;
  165. case 'kcp':
  166. $json->inbound->streamSettings->kcpSettings = json_decode($server->networkSettings);
  167. break;
  168. case 'ws':
  169. $json->inbound->streamSettings->wsSettings = json_decode($server->networkSettings);
  170. break;
  171. case 'http':
  172. $json->inbound->streamSettings->httpSettings = json_decode($server->networkSettings);
  173. break;
  174. case 'domainsocket':
  175. $json->inbound->streamSettings->dsSettings = json_decode($server->networkSettings);
  176. break;
  177. case 'quic':
  178. $json->inbound->streamSettings->quicSettings = json_decode($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 = json_decode($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 = json_decode($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;
  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. $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. }