mihomo/adapter/provider/provider.go

472 lines
11 KiB
Go
Raw Normal View History

2019-12-08 12:17:24 +08:00
package provider
import (
"encoding/json"
2019-12-08 12:17:24 +08:00
"errors"
"fmt"
2024-12-25 10:23:55 +08:00
"net/http"
2024-06-16 18:19:04 +08:00
"reflect"
2020-04-26 22:38:15 +08:00
"runtime"
"strings"
2019-12-08 12:17:24 +08:00
"time"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/adapter"
"github.com/metacubex/mihomo/common/convert"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/profile/cachefile"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/component/resource"
C "github.com/metacubex/mihomo/constant"
types "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/tunnel/statistic"
"github.com/dlclark/regexp2"
"gopkg.in/yaml.v3"
2019-12-08 12:17:24 +08:00
)
const (
ReservedName = "default"
)
type ProxySchema struct {
2022-03-16 12:10:13 +08:00
Proxies []map[string]any `yaml:"proxies"`
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
type providerForApi struct {
Name string `json:"name"`
Type string `json:"type"`
VehicleType string `json:"vehicleType"`
Proxies []C.Proxy `json:"proxies"`
TestUrl string `json:"testUrl"`
ExpectedStatus string `json:"expectedStatus"`
UpdatedAt time.Time `json:"updatedAt,omitempty"`
SubscriptionInfo *SubscriptionInfo `json:"subscriptionInfo,omitempty"`
2020-04-26 22:38:15 +08:00
}
2024-12-25 10:23:55 +08:00
type baseProvider struct {
name string
proxies []C.Proxy
healthCheck *HealthCheck
version uint32
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) Name() string {
return bp.name
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) Version() uint32 {
return bp.version
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) HealthCheck() {
bp.healthCheck.check()
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) Type() types.ProviderType {
return types.Proxy
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) Proxies() []C.Proxy {
return bp.proxies
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) Count() int {
return len(bp.proxies)
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) Touch() {
bp.healthCheck.touch()
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) HealthCheckURL() string {
return bp.healthCheck.url
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
bp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
2024-09-09 09:15:37 +08:00
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) setProxies(proxies []C.Proxy) {
bp.proxies = proxies
bp.healthCheck.setProxy(proxies)
if bp.healthCheck.auto() {
go bp.healthCheck.check()
}
}
2024-12-25 10:23:55 +08:00
func (bp *baseProvider) Close() error {
bp.healthCheck.close()
return nil
}
2024-12-25 10:23:55 +08:00
// ProxySetProvider for auto gc
type ProxySetProvider struct {
*proxySetProvider
}
2024-12-25 10:23:55 +08:00
type proxySetProvider struct {
baseProvider
*resource.Fetcher[[]C.Proxy]
subscriptionInfo *SubscriptionInfo
}
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
return json.Marshal(providerForApi{
Name: pp.Name(),
Type: pp.Type().String(),
VehicleType: pp.VehicleType().String(),
Proxies: pp.Proxies(),
TestUrl: pp.healthCheck.url,
ExpectedStatus: pp.healthCheck.expectedStatus.String(),
UpdatedAt: pp.UpdatedAt(),
SubscriptionInfo: pp.subscriptionInfo,
})
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (pp *proxySetProvider) Name() string {
return pp.Fetcher.Name()
}
2024-12-25 10:23:55 +08:00
func (pp *proxySetProvider) Update() error {
_, _, err := pp.Fetcher.Update()
return err
}
func (pp *proxySetProvider) Initial() error {
_, err := pp.Fetcher.Initial()
if err != nil {
return err
}
if subscriptionInfo := cachefile.Cache().GetSubscriptionInfo(pp.Name()); subscriptionInfo != "" {
pp.subscriptionInfo.Update(subscriptionInfo)
2022-11-05 02:24:08 +08:00
}
2024-12-25 10:23:55 +08:00
pp.closeAllConnections()
return nil
2022-11-05 02:24:08 +08:00
}
func (pp *proxySetProvider) closeAllConnections() {
statistic.DefaultManager.Range(func(c statistic.Tracker) bool {
for _, chain := range c.Chains() {
if chain == pp.Name() {
_ = c.Close()
break
}
}
return true
})
}
2024-08-27 11:04:42 +08:00
func (pp *proxySetProvider) Close() error {
2024-12-25 10:23:55 +08:00
_ = pp.baseProvider.Close()
2024-08-27 11:04:42 +08:00
return pp.Fetcher.Close()
2020-04-26 22:38:15 +08:00
}
2019-12-08 12:17:24 +08:00
2024-12-25 10:23:55 +08:00
func NewProxySetProvider(name string, interval time.Duration, parser resource.Parser[[]C.Proxy], vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
if hc.auto() {
go hc.process()
}
2024-12-25 10:23:55 +08:00
si := new(SubscriptionInfo)
2020-04-26 22:38:15 +08:00
pd := &proxySetProvider{
2024-12-25 10:23:55 +08:00
baseProvider: baseProvider{
name: name,
proxies: []C.Proxy{},
healthCheck: hc,
},
subscriptionInfo: si,
2019-12-08 12:17:24 +08:00
}
2020-04-26 22:38:15 +08:00
2024-12-25 10:23:55 +08:00
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, parser, proxiesOnUpdate(pd))
pd.Fetcher = fetcher
if httpVehicle, ok := vehicle.(*resource.HTTPVehicle); ok {
2024-12-25 10:23:55 +08:00
httpVehicle.SetInRead(func(resp *http.Response) {
if subscriptionInfo := resp.Header.Get("subscription-userinfo"); subscriptionInfo != "" {
cachefile.Cache().SetSubscriptionInfo(name, subscriptionInfo)
si.Update(subscriptionInfo)
}
})
}
2024-12-25 10:23:55 +08:00
wrapper := &ProxySetProvider{pd}
2024-08-27 11:04:42 +08:00
runtime.SetFinalizer(wrapper, (*ProxySetProvider).Close)
2021-11-21 17:44:03 +08:00
return wrapper, nil
2019-12-08 12:17:24 +08:00
}
2024-08-27 11:04:42 +08:00
func (pp *ProxySetProvider) Close() error {
runtime.SetFinalizer(pp, nil)
return pp.proxySetProvider.Close()
}
2024-12-25 10:23:55 +08:00
// InlineProvider for auto gc
type InlineProvider struct {
*inlineProvider
}
2024-12-25 10:23:55 +08:00
type inlineProvider struct {
baseProvider
updateAt time.Time
2020-04-26 22:38:15 +08:00
}
2024-12-25 10:23:55 +08:00
func (ip *inlineProvider) MarshalJSON() ([]byte, error) {
return json.Marshal(providerForApi{
Name: ip.Name(),
Type: ip.Type().String(),
VehicleType: ip.VehicleType().String(),
Proxies: ip.Proxies(),
TestUrl: ip.healthCheck.url,
ExpectedStatus: ip.healthCheck.expectedStatus.String(),
UpdatedAt: ip.updateAt,
})
}
2024-12-25 10:23:55 +08:00
func (ip *inlineProvider) VehicleType() types.VehicleType {
return types.Inline
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (ip *inlineProvider) Initial() error {
return nil
}
2024-12-25 10:23:55 +08:00
func (ip *inlineProvider) Update() error {
// make api update happy
ip.updateAt = time.Now()
2019-12-13 00:29:24 +08:00
return nil
}
2024-12-25 10:23:55 +08:00
func NewInlineProvider(name string, payload []map[string]any, parser resource.Parser[[]C.Proxy], hc *HealthCheck) (*InlineProvider, error) {
if hc.auto() {
go hc.process()
}
2019-12-08 12:17:24 +08:00
2024-12-25 10:23:55 +08:00
ps := ProxySchema{Proxies: payload}
buf, err := yaml.Marshal(ps)
if err != nil {
return nil, err
}
proxies, err := parser(buf)
if err != nil {
return nil, err
}
2019-12-08 12:17:24 +08:00
2024-12-25 10:23:55 +08:00
ip := &inlineProvider{
baseProvider: baseProvider{
name: name,
proxies: proxies,
healthCheck: hc,
},
updateAt: time.Now(),
}
wrapper := &InlineProvider{ip}
runtime.SetFinalizer(wrapper, (*InlineProvider).Close)
return wrapper, nil
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
func (ip *InlineProvider) Close() error {
runtime.SetFinalizer(ip, nil)
return ip.baseProvider.Close()
2019-12-08 12:17:24 +08:00
}
2024-12-25 10:23:55 +08:00
// CompatibleProvider for auto gc
type CompatibleProvider struct {
*compatibleProvider
2024-09-09 09:15:37 +08:00
}
2024-12-25 10:23:55 +08:00
type compatibleProvider struct {
baseProvider
}
2024-12-25 10:23:55 +08:00
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
return json.Marshal(providerForApi{
Name: cp.Name(),
Type: cp.Type().String(),
VehicleType: cp.VehicleType().String(),
Proxies: cp.Proxies(),
TestUrl: cp.healthCheck.url,
ExpectedStatus: cp.healthCheck.expectedStatus.String(),
})
}
2024-12-25 10:23:55 +08:00
func (cp *compatibleProvider) Update() error {
return nil
}
2024-12-25 10:23:55 +08:00
func (cp *compatibleProvider) Initial() error {
if cp.healthCheck.interval != 0 && cp.healthCheck.url != "" {
cp.HealthCheck()
}
2024-08-27 11:04:42 +08:00
return nil
2020-04-26 22:38:15 +08:00
}
2024-12-25 10:23:55 +08:00
func (cp *compatibleProvider) VehicleType() types.VehicleType {
return types.Compatible
}
2020-01-11 21:02:55 +08:00
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
2019-12-08 12:17:24 +08:00
if len(proxies) == 0 {
2021-07-06 00:33:13 +08:00
return nil, errors.New("provider need one proxy at least")
2019-12-08 12:17:24 +08:00
}
if hc.auto() {
go hc.process()
}
2020-04-26 22:38:15 +08:00
pd := &compatibleProvider{
2024-12-25 10:23:55 +08:00
baseProvider: baseProvider{
name: name,
proxies: proxies,
healthCheck: hc,
},
2020-04-26 22:38:15 +08:00
}
wrapper := &CompatibleProvider{pd}
2024-08-27 11:04:42 +08:00
runtime.SetFinalizer(wrapper, (*CompatibleProvider).Close)
2020-04-26 22:38:15 +08:00
return wrapper, nil
2019-12-08 12:17:24 +08:00
}
2024-08-27 11:04:42 +08:00
func (cp *CompatibleProvider) Close() error {
runtime.SetFinalizer(cp, nil)
return cp.compatibleProvider.Close()
}
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
return func(elm []C.Proxy) {
pd.setProxies(elm)
2022-07-20 08:53:54 +08:00
pd.version += 1
}
}
2024-12-25 10:23:55 +08:00
func NewProxiesParser(filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema) (resource.Parser[[]C.Proxy], error) {
excludeFilterReg, err := regexp2.Compile(excludeFilter, regexp2.None)
if err != nil {
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
}
var excludeTypeArray []string
if excludeType != "" {
excludeTypeArray = strings.Split(excludeType, "|")
}
var filterRegs []*regexp2.Regexp
for _, filter := range strings.Split(filter, "`") {
filterReg, err := regexp2.Compile(filter, regexp2.None)
if err != nil {
return nil, fmt.Errorf("invalid filter regex: %w", err)
}
filterRegs = append(filterRegs, filterReg)
}
return func(buf []byte) ([]C.Proxy, error) {
schema := &ProxySchema{}
if err := yaml.Unmarshal(buf, schema); err != nil {
proxies, err1 := convert.ConvertsV2Ray(buf)
if err1 != nil {
return nil, fmt.Errorf("%w, %w", err, err1)
}
schema.Proxies = proxies
}
if schema.Proxies == nil {
return nil, errors.New("file must have a `proxies` field")
}
proxies := []C.Proxy{}
proxiesSet := map[string]struct{}{}
for _, filterReg := range filterRegs {
for idx, mapping := range schema.Proxies {
if nil != excludeTypeArray && len(excludeTypeArray) > 0 {
mType, ok := mapping["type"]
if !ok {
continue
}
pType, ok := mType.(string)
if !ok {
continue
}
flag := false
for i := range excludeTypeArray {
if strings.EqualFold(pType, excludeTypeArray[i]) {
flag = true
break
}
}
if flag {
continue
}
}
mName, ok := mapping["name"]
if !ok {
continue
}
name, ok := mName.(string)
if !ok {
continue
}
if len(excludeFilter) > 0 {
if mat, _ := excludeFilterReg.MatchString(name); mat {
continue
}
}
if len(filter) > 0 {
if mat, _ := filterReg.MatchString(name); !mat {
continue
}
}
if _, ok := proxiesSet[name]; ok {
continue
}
if len(dialerProxy) > 0 {
mapping["dialer-proxy"] = dialerProxy
}
2024-06-16 18:19:04 +08:00
val := reflect.ValueOf(override)
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
if field.IsNil() {
continue
}
fieldName := strings.Split(val.Type().Field(i).Tag.Get("provider"), ",")[0]
switch fieldName {
case "additional-prefix":
name := mapping["name"].(string)
mapping["name"] = *field.Interface().(*string) + name
case "additional-suffix":
name := mapping["name"].(string)
mapping["name"] = name + *field.Interface().(*string)
case "proxy-name":
// Iterate through all naming replacement rules and perform the replacements.
for _, expr := range override.ProxyName {
name := mapping["name"].(string)
newName, err := expr.Pattern.Replace(name, expr.Target, 0, -1)
if err != nil {
return nil, fmt.Errorf("proxy name replace error: %w", err)
}
mapping["name"] = newName
}
2024-06-16 18:19:04 +08:00
default:
mapping[fieldName] = field.Elem().Interface()
}
2024-02-20 15:15:22 +08:00
}
proxy, err := adapter.ParseProxy(mapping)
if err != nil {
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
}
proxiesSet[name] = struct{}{}
proxies = append(proxies, proxy)
}
}
if len(proxies) == 0 {
if len(filter) > 0 {
return nil, errors.New("doesn't match any proxy, please check your filter")
}
return nil, errors.New("file doesn't have any proxy")
}
return proxies, nil
2024-12-25 10:23:55 +08:00
}, nil
}