mihomo/hub/executor/executor.go

354 lines
8.2 KiB
Go
Raw Normal View History

2018-11-21 13:47:46 +08:00
package executor
import (
"fmt"
2022-02-05 00:51:06 +08:00
2021-12-04 17:41:13 +08:00
"net"
"os"
2021-12-04 17:41:13 +08:00
"runtime"
"strconv"
2020-06-18 18:11:02 +08:00
"sync"
2022-01-21 22:38:02 +08:00
"github.com/Dreamacro/clash/listener/tproxy"
2021-06-10 14:05:56 +08:00
"github.com/Dreamacro/clash/adapter"
"github.com/Dreamacro/clash/adapter/outboundgroup"
"github.com/Dreamacro/clash/component/auth"
"github.com/Dreamacro/clash/component/dialer"
2022-02-05 00:51:06 +08:00
G "github.com/Dreamacro/clash/component/geodata"
"github.com/Dreamacro/clash/component/iface"
"github.com/Dreamacro/clash/component/profile"
"github.com/Dreamacro/clash/component/profile/cachefile"
"github.com/Dreamacro/clash/component/resolver"
"github.com/Dreamacro/clash/component/trie"
2018-11-21 13:47:46 +08:00
"github.com/Dreamacro/clash/config"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
2018-12-05 21:13:29 +08:00
"github.com/Dreamacro/clash/dns"
2021-06-13 17:23:10 +08:00
P "github.com/Dreamacro/clash/listener"
authStore "github.com/Dreamacro/clash/listener/auth"
2018-11-21 13:47:46 +08:00
"github.com/Dreamacro/clash/log"
"github.com/Dreamacro/clash/tunnel"
2018-11-21 13:47:46 +08:00
)
2021-10-10 23:44:09 +08:00
var mux sync.Mutex
2020-06-18 18:11:02 +08:00
func readConfig(path string) ([]byte, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
2021-10-09 20:35:06 +08:00
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if len(data) == 0 {
2020-08-25 22:19:59 +08:00
return nil, fmt.Errorf("configuration file %s is empty", path)
}
return data, err
}
2018-11-21 13:47:46 +08:00
// Parse config with default config path
func Parse() (*config.Config, error) {
return ParseWithPath(C.Path.Config())
}
// ParseWithPath parse config with custom config path
func ParseWithPath(path string) (*config.Config, error) {
buf, err := readConfig(path)
if err != nil {
return nil, err
}
return ParseWithBytes(buf)
}
// ParseWithBytes config with buffer
func ParseWithBytes(buf []byte) (*config.Config, error) {
return config.Parse(buf)
2018-11-21 13:47:46 +08:00
}
// ApplyConfig dispatch configure to all parts
2018-11-30 17:42:40 +08:00
func ApplyConfig(cfg *config.Config, force bool) {
2020-06-18 18:11:02 +08:00
mux.Lock()
defer mux.Unlock()
2022-03-18 00:24:38 +08:00
log.SetLevel(log.INFO)
2022-03-05 18:04:04 +08:00
updateUsers(cfg.Users)
2019-09-11 17:00:55 +08:00
updateHosts(cfg.Hosts)
updateGeneral(cfg.General, force)
updateProxies(cfg.Proxies, cfg.Providers)
updateRules(cfg.Rules, cfg.RuleProviders)
updateIPTables(cfg.DNS, cfg.General, cfg.Tun)
updateDNS(cfg.DNS, cfg.Tun)
updateTun(cfg.Tun)
updateExperimental(cfg)
loadProvider(cfg.RuleProviders, cfg.Providers)
2022-01-21 22:38:02 +08:00
updateProfile(cfg)
2022-03-05 18:04:04 +08:00
log.SetLevel(cfg.General.LogLevel)
2018-11-21 13:47:46 +08:00
}
func GetGeneral() *config.General {
ports := P.GetPorts()
2019-06-27 20:45:12 +08:00
authenticator := []string{}
if auth := authStore.Authenticator(); auth != nil {
authenticator = auth.Users()
}
general := &config.General{
2020-06-18 18:11:02 +08:00
Inbound: config.Inbound{
Port: ports.Port,
SocksPort: ports.SocksPort,
RedirPort: ports.RedirPort,
TProxyPort: ports.TProxyPort,
2020-06-18 18:11:02 +08:00
MixedPort: ports.MixedPort,
Authentication: authenticator,
AllowLan: P.AllowLan(),
BindAddress: P.BindAddress(),
},
2022-02-05 00:51:06 +08:00
Mode: tunnel.Mode(),
LogLevel: log.Level(),
IPv6: !resolver.DisableIPv6,
GeodataLoader: G.LoaderName(),
2018-11-21 13:47:46 +08:00
}
2019-06-27 20:45:12 +08:00
return general
2018-11-21 13:47:46 +08:00
}
func updateExperimental(c *config.Config) {}
2022-03-09 05:08:35 +08:00
func updateDNS(c *config.DNS, t *config.Tun) {
cfg := dns.Config{
2018-12-05 21:13:29 +08:00
Main: c.NameServer,
Fallback: c.Fallback,
IPv6: c.IPv6,
EnhancedMode: c.EnhancedMode,
2019-05-03 00:05:14 +08:00
Pool: c.FakeIPRange,
Hosts: c.Hosts,
2019-09-15 13:36:45 +08:00
FallbackFilter: dns.FallbackFilter{
2021-08-25 15:15:13 +08:00
GeoIP: c.FallbackFilter.GeoIP,
GeoIPCode: c.FallbackFilter.GeoIPCode,
IPCIDR: c.FallbackFilter.IPCIDR,
Domain: c.FallbackFilter.Domain,
2021-11-17 16:03:47 +08:00
GeoSite: c.FallbackFilter.GeoSite,
2019-09-15 13:36:45 +08:00
},
Default: c.DefaultNameserver,
Policy: c.NameServerPolicy,
}
r := dns.NewResolver(cfg)
2021-11-17 16:03:47 +08:00
mr := dns.NewMainResolver(r)
m := dns.NewEnhancer(cfg)
// reuse cache of old host mapper
if old := resolver.DefaultHostMapper; old != nil {
m.PatchFrom(old.(*dns.ResolverEnhancer))
}
resolver.DefaultResolver = r
2021-11-17 16:03:47 +08:00
resolver.MainResolver = mr
resolver.DefaultHostMapper = m
2022-03-09 05:08:35 +08:00
if t.Enable {
2021-11-17 16:03:47 +08:00
resolver.DefaultLocalServer = dns.NewLocalServer(r, m)
}
if c.Enable {
dns.ReCreateServer(c.Listen, r, m)
2022-03-09 05:08:35 +08:00
} else {
if !t.Enable {
resolver.DefaultResolver = nil
resolver.MainResolver = nil
resolver.DefaultHostMapper = nil
resolver.DefaultLocalServer = nil
}
dns.ReCreateServer("", nil, nil)
2022-01-04 17:58:50 +08:00
}
2018-12-05 21:13:29 +08:00
}
func updateHosts(tree *trie.DomainTrie) {
resolver.DefaultHosts = tree
2019-09-11 17:00:55 +08:00
}
2019-12-08 12:17:24 +08:00
func updateProxies(proxies map[string]C.Proxy, providers map[string]provider.ProxyProvider) {
tunnel.UpdateProxies(proxies, providers)
2018-11-21 13:47:46 +08:00
}
2021-12-02 22:56:17 +08:00
func updateRules(rules []C.Rule, ruleProviders map[string]*provider.RuleProvider) {
tunnel.UpdateRules(rules, ruleProviders)
2018-11-21 13:47:46 +08:00
}
func loadProvider(ruleProviders map[string]*provider.RuleProvider, proxyProviders map[string]provider.ProxyProvider) {
load := func(pv provider.Provider) {
if pv.VehicleType() == provider.Compatible {
log.Infoln("Start initial compatible provider %s", pv.Name())
} else {
log.Infoln("Start initial provider %s", (pv).Name())
}
if err := (pv).Initial(); err != nil {
switch pv.Type() {
case provider.Proxy:
{
log.Warnln("initial proxy provider %s error: %v", (pv).Name(), err)
}
case provider.Rule:
{
log.Warnln("initial rule provider %s error: %v", (pv).Name(), err)
}
}
}
}
for _, proxyProvider := range proxyProviders {
load(proxyProvider)
}
for _, ruleProvider := range ruleProviders {
load(*ruleProvider)
}
}
func updateTun(tun *config.Tun) {
P.ReCreateTun(tun, tunnel.TCPIn(), tunnel.UDPIn())
2022-03-09 05:08:35 +08:00
}
func updateGeneral(general *config.General, force bool) {
tunnel.SetMode(general.Mode)
2020-06-18 18:11:02 +08:00
resolver.DisableIPv6 = !general.IPv6
adapter.UnifiedDelay.Store(general.UnifiedDelay)
dialer.DefaultInterface.Store(general.Interface)
2022-03-09 05:08:35 +08:00
if dialer.DefaultInterface.Load() != "" {
log.Infoln("Use interface name: %s", general.Interface)
}
2022-03-09 05:08:35 +08:00
if general.RoutingMark > 0 || (general.RoutingMark == 0 && general.TProxyPort == 0) {
2022-03-03 05:02:17 +08:00
dialer.DefaultRoutingMark.Store(int32(general.RoutingMark))
2022-03-09 05:08:35 +08:00
if general.RoutingMark > 0 {
log.Infoln("Use routing mark: %#x", general.RoutingMark)
}
2022-03-03 05:02:17 +08:00
}
2021-11-17 16:03:47 +08:00
iface.FlushCache()
2020-06-18 18:11:02 +08:00
if !force {
return
}
2018-12-03 23:41:40 +08:00
2022-03-15 02:20:19 +08:00
geodataLoader := general.GeodataLoader
G.SetLoader(geodataLoader)
2018-11-21 13:47:46 +08:00
allowLan := general.AllowLan
P.SetAllowLan(allowLan)
bindAddress := general.BindAddress
P.SetBindAddress(bindAddress)
2021-06-13 17:23:10 +08:00
tcpIn := tunnel.TCPIn()
udpIn := tunnel.UDPIn()
P.ReCreateHTTP(general.Port, tcpIn)
P.ReCreateSocks(general.SocksPort, tcpIn, udpIn)
P.ReCreateRedir(general.RedirPort, tcpIn, udpIn)
P.ReCreateTProxy(general.TProxyPort, tcpIn, udpIn)
P.ReCreateMixed(general.MixedPort, tcpIn, udpIn)
2018-11-21 13:47:46 +08:00
}
func updateUsers(users []auth.AuthUser) {
authenticator := auth.NewAuthenticator(users)
authStore.SetAuthenticator(authenticator)
if authenticator != nil {
log.Infoln("Authentication of local server updated")
}
}
func updateProfile(cfg *config.Config) {
profileCfg := cfg.Profile
profile.StoreSelected.Store(profileCfg.StoreSelected)
if profileCfg.StoreSelected {
patchSelectGroup(cfg.Proxies)
}
}
func patchSelectGroup(proxies map[string]C.Proxy) {
mapping := cachefile.Cache().SelectedMap()
if mapping == nil {
return
}
for name, proxy := range proxies {
2021-06-10 14:05:56 +08:00
outbound, ok := proxy.(*adapter.Proxy)
if !ok {
continue
}
selector, ok := outbound.ProxyAdapter.(*outboundgroup.Selector)
if !ok {
continue
}
selected, exist := mapping[name]
if !exist {
continue
}
selector.Set(selected)
}
}
2021-11-17 16:03:47 +08:00
func updateIPTables(dns *config.DNS, general *config.General, tun *config.Tun) {
2022-03-09 05:08:35 +08:00
tproxy.CleanUpTProxyLinuxIPTables()
if runtime.GOOS != "linux" || general.TProxyPort == 0 {
2022-03-09 05:08:35 +08:00
return
}
var err error
defer func() {
if err != nil {
log.Errorln("Setting iptables failed: %s", err.Error())
os.Exit(2)
}
}()
if !dns.Enable || dns.Listen == "" {
err = fmt.Errorf("DNS server must be enable")
return
}
if tun.Enable {
2022-03-09 05:08:35 +08:00
err = fmt.Errorf("TUN device must be disabe")
2021-12-04 17:41:13 +08:00
return
}
_, dnsPortStr, err := net.SplitHostPort(dns.Listen)
if dnsPortStr == "0" || dnsPortStr == "" || err != nil {
return
}
dnsPort, err := strconv.Atoi(dnsPortStr)
if err != nil {
return
}
2022-03-05 18:04:04 +08:00
if dialer.DefaultRoutingMark.Load() == 0 {
dialer.DefaultRoutingMark.Store(2158)
2021-12-04 17:41:13 +08:00
}
if general.AutoIptables {
err = tproxy.SetTProxyLinuxIPTables(general.Interface, general.TProxyPort, dnsPort)
}
2021-12-04 17:41:13 +08:00
}
2021-11-17 16:03:47 +08:00
2022-03-05 18:04:04 +08:00
func Cleanup() {
P.Cleanup()
2022-02-06 01:59:35 +08:00
if runtime.GOOS == "linux" {
2021-12-04 17:41:13 +08:00
tproxy.CleanUpTProxyLinuxIPTables()
}
2021-11-17 16:03:47 +08:00
}