Skip to content

Commit

Permalink
Add ua selector
Browse files Browse the repository at this point in the history
Support modify test url

Optimize android proxy

Fix the error that async proxy provider could not selected the proxy
  • Loading branch information
chen08209 committed Jul 4, 2024
1 parent 6dcb466 commit 5c3a0c5
Show file tree
Hide file tree
Showing 43 changed files with 1,247 additions and 301 deletions.
2 changes: 1 addition & 1 deletion core/Clash.Meta
56 changes: 46 additions & 10 deletions core/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import "C"
import (
"github.com/metacubex/mihomo/adapter"
"github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/adapter/outboundgroup"
ap "github.com/metacubex/mihomo/adapter/provider"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/resolver"
Expand Down Expand Up @@ -59,11 +60,17 @@ type ruleProviderSchema struct {
Interval int `provider:"interval,omitempty"`
}

type ConfigExtendedParams struct {
IsPatch bool `json:"is-patch"`
IsCompatible bool `json:"is-compatible"`
SelectedMap map[string]string `json:"selected-map"`
TestURL *string `json:"test-url"`
}

type GenerateConfigParams struct {
ProfilePath *string `json:"profile-path"`
Config *config.RawConfig `json:"config" `
IsPatch *bool `json:"is-patch"`
IsCompatible *bool `json:"is-compatible"`
ProfilePath *string `json:"profile-path"`
Config config.RawConfig `json:"config" `
Params ConfigExtendedParams `json:"params"`
}

type ChangeProxyParams struct {
Expand Down Expand Up @@ -170,9 +177,9 @@ func getRawConfigWithPath(path *string) *config.RawConfig {
}
}

func decorationConfig(profilePath *string, cfg config.RawConfig, compatible bool) *config.RawConfig {
func decorationConfig(profilePath *string, cfg config.RawConfig) *config.RawConfig {
prof := getRawConfigWithPath(profilePath)
overwriteConfig(prof, cfg, compatible)
overwriteConfig(prof, cfg)
return prof
}

Expand Down Expand Up @@ -322,7 +329,7 @@ func generateProxyGroupAndRule(proxyGroup *[]map[string]any, rule *[]string) {
*rule = computedRule
}

func overwriteConfig(targetConfig *config.RawConfig, patchConfig config.RawConfig, compatible bool) {
func overwriteConfig(targetConfig *config.RawConfig, patchConfig config.RawConfig) {
targetConfig.ExternalController = patchConfig.ExternalController
targetConfig.ExternalUI = ""
targetConfig.Interface = ""
Expand Down Expand Up @@ -352,7 +359,7 @@ func overwriteConfig(targetConfig *config.RawConfig, patchConfig config.RawConfi
//} else if runtime.GOOS == "windows" {
// targetConfig.DNS.NameServer = append(targetConfig.DNS.NameServer, dns.SystemDNSPlaceholder)
//}
if compatible == false {
if configParams.IsCompatible == false {
targetConfig.ProxyProvider = make(map[string]map[string]any)
targetConfig.RuleProvider = make(map[string]map[string]any)
generateProxyGroupAndRule(&targetConfig.ProxyGroup, &targetConfig.Rule)
Expand Down Expand Up @@ -388,15 +395,44 @@ func patchConfig(general *config.General) {
resolver.DisableIPv6 = !general.IPv6
}

func applyConfig(isPatch bool) {
func patchSelectGroup() {
mapping := configParams.SelectedMap
if mapping == nil {
return
}
for name, proxy := range tunnel.ProxiesWithProviders() {
outbound, ok := proxy.(*adapter.Proxy)
if !ok {
continue
}

selector, ok := outbound.ProxyAdapter.(outboundgroup.SelectAble)
if !ok {
continue
}

selected, exist := mapping[name]
if !exist {
continue
}

selector.ForceSet(selected)
}
}

func applyConfig() {
cfg, err := config.ParseRawConfig(currentConfig)
if err != nil {
cfg, _ = config.ParseRawConfig(config.DefaultRawConfig())
}
if isPatch {
if configParams.TestURL != nil {
constant.DefaultTestURL = *configParams.TestURL
}
if configParams.IsPatch {
patchConfig(cfg.General)
} else {
runtime.GC()
hub.UltraApplyConfig(cfg, true)
patchSelectGroup()
}
}
1 change: 1 addition & 0 deletions core/dart-bridge/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const (
Process MessageType = "process"
Request MessageType = "request"
Run MessageType = "run"
Loaded MessageType = "loaded"
)

type Message struct {
Expand Down
21 changes: 13 additions & 8 deletions core/hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import (

var currentConfig = config.DefaultRawConfig()

var configParams = ConfigExtendedParams{}

var isInit = false

//export initClash
Expand Down Expand Up @@ -92,17 +94,14 @@ func updateConfig(s *C.char, port C.longlong) {
go func() {
var params = &GenerateConfigParams{}
err := json.Unmarshal([]byte(paramsString), params)
configParams = params.Params
if err != nil {
bridge.SendToPort(i, err.Error())
return
}
prof := decorationConfig(params.ProfilePath, *params.Config, *params.IsCompatible)
prof := decorationConfig(params.ProfilePath, params.Config)
currentConfig = prof
if *params.IsPatch {
applyConfig(true)
} else {
applyConfig(false)
}
applyConfig()
bridge.SendToPort(i, "")
}()
}
Expand Down Expand Up @@ -161,8 +160,8 @@ func changeProxy(s *C.char) {
groupName := *params.GroupName
proxyName := *params.ProxyName
proxies := tunnel.ProxiesWithProviders()
group := proxies[groupName]
if group == nil {
group, ok := proxies[groupName]
if !ok {
return
}
adapterProxy := group.(*adapter.Proxy)
Expand Down Expand Up @@ -441,4 +440,10 @@ func init() {
Data: c,
})
}
executor.DefaultProxyProviderLoadedHook = func(providerName string) {
bridge.SendMessage(bridge.Message{
Type: bridge.Loaded,
Data: providerName,
})
}
}
49 changes: 29 additions & 20 deletions core/tun.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/metacubex/mihomo/log"
"golang.org/x/sync/semaphore"
"sync"
"sync/atomic"
"syscall"
"time"
)
Expand All @@ -22,11 +23,11 @@ type FdMap struct {
m sync.Map
}

func (cm *FdMap) Store(key int) {
func (cm *FdMap) Store(key int64) {
cm.m.Store(key, struct{}{})
}

func (cm *FdMap) Load(key int) bool {
func (cm *FdMap) Load(key int64) bool {
_, ok := cm.m.Load(key)
return ok
}
Expand Down Expand Up @@ -80,36 +81,44 @@ var errBlocked = errors.New("blocked")

//export setFdMap
func setFdMap(fd C.long) {
fdInt := int(fd)
fdInt := int64(fd)
go func() {
fdMap.Store(fdInt)
}()
}

var fdCounter int64 = 0

func init() {
dialer.DefaultSocketHook = func(network, address string, conn syscall.RawConn) error {
if platform.ShouldBlockConnection() {
return errBlocked
}
return conn.Control(func(fd uintptr) {
fdInt := int(fd)
//timeout := time.After(100 * time.Millisecond)
if tun != nil {
tun.MarkSocket(fdInt)
time.Sleep(100 * time.Millisecond)
if tun == nil {
return
}

fdInt := int64(fd)
timeout := time.After(100 * time.Millisecond)
id := atomic.AddInt64(&fdCounter, 1)
tun.MarkSocket(t.Fd{
Id: id,
Value: fdInt,
})

for {
select {
case <-timeout:
return
default:
exists := fdMap.Load(id)
if exists {
return
}
time.Sleep(10 * time.Millisecond)
}
}
//for {
// select {
// case <-timeout:
// return
// default:
// exists := fdMap.Load(fdInt)
// if exists {
// return
// }
// time.Sleep(20 * time.Millisecond)
// }
//}
})
}
}
10 changes: 7 additions & 3 deletions core/tun/tun.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"io"
"net"
"os"
"strconv"
"time"
)

Expand Down Expand Up @@ -187,7 +186,12 @@ func Start(fd int, gateway, portal, dns string) (io.Closer, error) {
return stack, nil
}

func (t *Tun) MarkSocket(fd int) {
type Fd struct {
Id int64 `json:"id"`
Value int64 `json:"value"`
}

func (t *Tun) MarkSocket(fd Fd) {
_ = t.Limit.Acquire(context.Background(), 1)
defer t.Limit.Release(1)

Expand All @@ -197,7 +201,7 @@ func (t *Tun) MarkSocket(fd int) {

message := &bridge.Message{
Type: bridge.Tun,
Data: strconv.Itoa(fd),
Data: fd,
}

bridge.SendMessage(*message)
Expand Down
5 changes: 2 additions & 3 deletions lib/clash/core.dart
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,11 @@ class ClashCore {
return completer.future;
}

bool changeProxy(ChangeProxyParams changeProxyParams) {
changeProxy(ChangeProxyParams changeProxyParams) {
final params = json.encode(changeProxyParams);
final paramsChar = params.toNativeUtf8().cast<Char>();
final isInit = clashFFI.changeProxy(paramsChar) == 1;
clashFFI.changeProxy(paramsChar);
malloc.free(paramsChar);
return isInit;
}

Future<Delay> getDelay(String proxyName) {
Expand Down
6 changes: 3 additions & 3 deletions lib/clash/generated/clash_ffi.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5248,7 +5248,7 @@ class ClashFFI {
late final _getProxies =
_getProxiesPtr.asFunction<ffi.Pointer<ffi.Char> Function()>();

int changeProxy(
void changeProxy(
ffi.Pointer<ffi.Char> s,
) {
return _changeProxy(
Expand All @@ -5257,10 +5257,10 @@ class ClashFFI {
}

late final _changeProxyPtr =
_lookup<ffi.NativeFunction<GoUint8 Function(ffi.Pointer<ffi.Char>)>>(
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Char>)>>(
'changeProxy');
late final _changeProxy =
_changeProxyPtr.asFunction<int Function(ffi.Pointer<ffi.Char>)>();
_changeProxyPtr.asFunction<void Function(ffi.Pointer<ffi.Char>)>();

ffi.Pointer<ffi.Char> getTraffic() {
return _getTraffic();
Expand Down
9 changes: 7 additions & 2 deletions lib/clash/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import 'core.dart';
abstract mixin class ClashMessageListener {
void onLog(Log log) {}

void onTun(String fd) {}
void onTun(Fd fd) {}

void onDelay(Delay delay) {}

Expand All @@ -21,6 +21,8 @@ abstract mixin class ClashMessageListener {
void onNow(Now now) {}

void onRun(String runTime) {}

void onLoaded(String groupName) {}
}

class ClashMessage {
Expand All @@ -39,7 +41,7 @@ class ClashMessage {
listener.onLog(Log.fromJson(m.data));
break;
case MessageType.tun:
listener.onTun(m.data);
listener.onTun(Fd.fromJson(m.data));
break;
case MessageType.delay:
listener.onDelay(Delay.fromJson(m.data));
Expand All @@ -56,6 +58,9 @@ class ClashMessage {
case MessageType.run:
listener.onRun(m.data);
break;
case MessageType.loaded:
listener.onLoaded(m.data);
break;
}
}
});
Expand Down
3 changes: 2 additions & 1 deletion lib/common/common.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ export 'string.dart';
export 'app_localizations.dart';
export 'function.dart';
export 'package.dart';
export 'measure.dart';
export 'measure.dart';
export 'service.dart';
1 change: 1 addition & 0 deletions lib/common/constant.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const maxMobileWidth = 600;
const maxLaptopWidth = 840;
const geodataLoaderMemconservative = "memconservative";
const geodataLoaderStandard = "standard";
const defaultTestUrl = "https://www.gstatic.com/generate_204";
final filter = ImageFilter.blur(
sigmaX: 5,
sigmaY: 5,
Expand Down
Loading

0 comments on commit 5c3a0c5

Please sign in to comment.