generate.dart 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import 'dart:io';
  2. import 'package:speed_safe/app/server/hysteria/server.dart';
  3. import 'package:speed_safe/app/server/shadowsocks/server.dart';
  4. import 'package:speed_safe/app/server/sing-box/config.dart';
  5. import 'package:speed_safe/app/server/trojan/server.dart';
  6. import 'package:speed_safe/app/server/xray/config.dart' as xray_config;
  7. import 'package:speed_safe/app/server/xray/server.dart';
  8. import 'package:speed_safe/app/server/server_base.dart';
  9. import 'package:speed_safe/app/util/system.dart';
  10. import 'package:path/path.dart' as p;
  11. class SingBoxGenerate {
  12. static const ipRegExp = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
  13. static Future<String> resolveDns(String dns) async {
  14. final dnsHost = Uri.parse(dns).host;
  15. if (!RegExp(ipRegExp).hasMatch(dnsHost) && dnsHost.isNotEmpty) {
  16. try {
  17. final dnsIp = (await InternetAddress.lookup(dnsHost)
  18. .timeout(const Duration(seconds: 2)))
  19. .first;
  20. return dns.replaceFirst(dnsHost, dnsIp.address);
  21. } on Exception catch (_) {
  22. throw Exception('Failed to resolve DNS server address: $dns');
  23. }
  24. }
  25. return dns;
  26. }
  27. static Future<Dns> dns(String remoteDns, String directDns,
  28. String serverAddress, bool ipv4Only) async {
  29. remoteDns = await resolveDns(remoteDns);
  30. directDns = await resolveDns(directDns);
  31. if (directDns.contains('+local://')) {
  32. directDns = directDns.replaceFirst('+local', '');
  33. }
  34. List<DnsRule> dnsRules = [
  35. DnsRule(
  36. domain: ['geosite:cn'],
  37. server: 'local',
  38. ),
  39. ];
  40. if (!RegExp(ipRegExp).hasMatch(serverAddress) &&
  41. serverAddress != '127.0.0.1') {
  42. dnsRules.add(
  43. DnsRule(
  44. domain: [serverAddress],
  45. server: 'local',
  46. ),
  47. );
  48. }
  49. return Dns(
  50. servers: [
  51. DnsServer(
  52. tag: 'remote',
  53. address: remoteDns,
  54. detour: 'proxy',
  55. strategy: ipv4Only ? 'ipv4_only' : null,
  56. ),
  57. DnsServer(
  58. tag: 'local',
  59. address: directDns,
  60. detour: 'direct',
  61. strategy: ipv4Only ? 'ipv4_only' : null,
  62. ),
  63. ],
  64. rules: dnsRules,
  65. );
  66. }
  67. static Route route(List<xray_config.XrayRule> rules, bool configureDns) {
  68. List<RouteRule> routeRules = [];
  69. if (configureDns) {
  70. routeRules.add(
  71. RouteRule(
  72. protocol: 'dns',
  73. outbound: 'dns-out',
  74. ),
  75. );
  76. }
  77. routeRules.addAll(convertRules(rules));
  78. return Route(
  79. geoip: Geoip(path: p.join(binPath, 'geoip.db')),
  80. geosite: Geosite(path: p.join(binPath, 'geosite.db')),
  81. rules: routeRules,
  82. autoDetectInterface: true,
  83. finalTag: 'proxy',
  84. );
  85. }
  86. static List<RouteRule> convertRules(List<xray_config.XrayRule> xrayRules) {
  87. List<RouteRule> result = [];
  88. result.add(
  89. RouteRule(
  90. processName: SystemUtil.getCoreFileNames(),
  91. outbound: 'direct',
  92. ),
  93. );
  94. for (var xrayRule in xrayRules) {
  95. if (xrayRule.enabled) {
  96. List<String>? geosite;
  97. List<String>? domain;
  98. List<String>? geoip;
  99. List<String>? ipCidr;
  100. List<int>? port;
  101. List<String>? portRange;
  102. if (xrayRule.domain != null) {
  103. for (var domainItem in xrayRule.domain!) {
  104. if (domainItem.startsWith('geosite:')) {
  105. geosite ??= [];
  106. geosite.add(domainItem.replaceFirst('geosite:', ''));
  107. } else {
  108. domain ??= [];
  109. domain.add(domainItem);
  110. }
  111. }
  112. }
  113. if (xrayRule.ip != null) {
  114. for (var ipItem in xrayRule.ip!) {
  115. if (ipItem.startsWith('geoip:')) {
  116. geoip ??= [];
  117. geoip.add(ipItem.replaceFirst('geoip:', ''));
  118. } else {
  119. ipCidr ??= [];
  120. ipCidr.add(ipItem);
  121. }
  122. }
  123. }
  124. if (xrayRule.port != null) {
  125. List<String> tempPort = xrayRule.port!.split(',');
  126. for (var portItem in tempPort) {
  127. if (portItem.contains('-')) {
  128. portRange ??= [];
  129. portRange.add(portItem.replaceAll('-', ':'));
  130. } else {
  131. port ??= [];
  132. port.add(int.parse(portItem));
  133. }
  134. }
  135. }
  136. result.add(RouteRule(
  137. geosite: geosite,
  138. domain: domain,
  139. geoip: geoip,
  140. ipCidr: ipCidr,
  141. port: port,
  142. portRange: portRange,
  143. outbound: xrayRule.outboundTag,
  144. ));
  145. }
  146. }
  147. return result;
  148. }
  149. static Inbound mixedInbound(
  150. String listen, int listenPort, List<User>? users) {
  151. return Inbound(
  152. type: 'mixed',
  153. listen: listen,
  154. listenPort: listenPort,
  155. users: users,
  156. );
  157. }
  158. static Inbound tunInbound(String? inet4Address, String? inet6Address, int mtu,
  159. String stack, bool autoRoute, bool strictRoute, bool sniff) {
  160. return Inbound(
  161. type: 'tun',
  162. inet4Address: inet4Address,
  163. inet6Address: inet6Address,
  164. mtu: mtu,
  165. autoRoute: autoRoute,
  166. strictRoute: strictRoute,
  167. stack: stack,
  168. sniff: sniff,
  169. );
  170. }
  171. static Outbound generateOutbound(ServerBase server) {
  172. late Outbound outbound;
  173. switch (server.runtimeType) {
  174. case XrayServer:
  175. outbound = xrayOutbound(server as XrayServer);
  176. break;
  177. case ShadowsocksServer:
  178. outbound = shadowsocksOutbound(server as ShadowsocksServer);
  179. break;
  180. case TrojanServer:
  181. outbound = trojanOutbound(server as TrojanServer);
  182. break;
  183. case HysteriaServer:
  184. outbound = hysteriaOutbound(server as HysteriaServer);
  185. break;
  186. default:
  187. throw Exception(
  188. 'Sing-Box does not support this server type: ${server.protocol}');
  189. }
  190. return outbound;
  191. }
  192. static Outbound xrayOutbound(XrayServer server) {
  193. if (server.protocol == 'socks') {
  194. return socksOutbound(server);
  195. } else if (server.protocol == 'vmess' || server.protocol == 'vless') {
  196. return vProtocolOutbound(server);
  197. } else {
  198. throw Exception(
  199. 'Sing-Box does not support this server type: ${server.protocol}');
  200. }
  201. }
  202. static Outbound socksOutbound(XrayServer server) {
  203. return Outbound(
  204. type: 'socks',
  205. tag: 'proxy',
  206. server: server.address,
  207. serverPort: server.port,
  208. version: '5',
  209. );
  210. }
  211. static Outbound vProtocolOutbound(XrayServer server) {
  212. final utls = UTls(
  213. enabled: server.fingerPrint != null && server.fingerPrint != 'none',
  214. fingerprint: server.fingerPrint,
  215. );
  216. final reality = Reality(
  217. enabled: server.tls == 'reality',
  218. publicKey: server.publicKey ?? '',
  219. shortId: server.shortId,
  220. );
  221. final tls = Tls(
  222. enabled: server.tls == 'tls',
  223. serverName: server.serverName ?? server.address,
  224. insecure: server.allowInsecure,
  225. utls: utls,
  226. reality: reality,
  227. );
  228. final transport = Transport(
  229. type: server.transport,
  230. host: server.transport == 'httpupgrade'
  231. ? (server.host ?? server.address)
  232. : null,
  233. path: server.transport == 'ws' || server.transport == 'httpupgrade'
  234. ? (server.path ?? '/')
  235. : null,
  236. serviceName:
  237. server.transport == 'grpc' ? (server.serviceName ?? '/') : null,
  238. );
  239. return Outbound(
  240. type: server.protocol,
  241. tag: 'proxy',
  242. server: server.address,
  243. serverPort: server.port,
  244. uuid: server.uuid,
  245. flow: server.flow,
  246. alterId: server.protocol == 'vmess' ? server.alterId : null,
  247. security: server.protocol == 'vmess' ? server.encryption : null,
  248. tls: tls,
  249. transport: server.tls == 'reality' ? null : transport,
  250. );
  251. }
  252. static Outbound shadowsocksOutbound(ShadowsocksServer server) {
  253. return Outbound(
  254. type: 'shadowsocks',
  255. tag: 'proxy',
  256. server: server.address,
  257. serverPort: server.port,
  258. method: server.encryption,
  259. password: server.password,
  260. plugin: server.plugin,
  261. pluginOpts: server.plugin,
  262. );
  263. }
  264. static Outbound trojanOutbound(TrojanServer server) {
  265. final tls = Tls(
  266. enabled: true,
  267. serverName: server.serverName ?? server.address,
  268. insecure: server.allowInsecure,
  269. );
  270. return Outbound(
  271. type: 'trojan',
  272. tag: 'proxy',
  273. server: server.address,
  274. serverPort: server.port,
  275. password: server.password,
  276. network: 'tcp',
  277. tls: tls,
  278. );
  279. }
  280. static Outbound hysteriaOutbound(HysteriaServer server) {
  281. final tls = Tls(
  282. enabled: true,
  283. serverName: server.serverName ?? server.address,
  284. insecure: server.insecure,
  285. alpn: server.alpn?.split(','),
  286. );
  287. return Outbound(
  288. type: 'hysteria',
  289. tag: 'proxy',
  290. server: server.address,
  291. serverPort: server.port,
  292. upMbps: server.upMbps,
  293. downMbps: server.downMbps,
  294. obfs: server.obfs,
  295. auth: server.authType == 'none'
  296. ? (server.authType == 'base64' ? server.authPayload : null)
  297. : null,
  298. authStr: server.authType == 'none'
  299. ? (server.authType == 'str' ? server.authPayload : null)
  300. : null,
  301. recvWindowConn: server.recvWindowConn,
  302. recvWindow: server.recvWindow,
  303. tls: tls,
  304. );
  305. }
  306. }