mihomo/listener/inbound/base.go

104 lines
2.2 KiB
Go
Raw Permalink Normal View History

2022-12-04 13:37:14 +08:00
package inbound
import (
"encoding/json"
2022-12-04 13:37:14 +08:00
"net"
"net/netip"
"strconv"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/adapter/inbound"
C "github.com/metacubex/mihomo/constant"
2022-12-04 13:37:14 +08:00
)
type Base struct {
2022-12-04 22:08:20 +08:00
config *BaseOption
name string
specialRules string
listenAddr netip.Addr
port int
2022-12-04 13:37:14 +08:00
}
func NewBase(options *BaseOption) (*Base, error) {
if options.Listen == "" {
options.Listen = "0.0.0.0"
}
addr, err := netip.ParseAddr(options.Listen)
if err != nil {
return nil, err
}
return &Base{
2022-12-04 22:08:20 +08:00
name: options.Name(),
listenAddr: addr,
specialRules: options.SpecialRules,
2022-12-04 22:08:20 +08:00
port: options.Port,
config: options,
2022-12-04 13:37:14 +08:00
}, nil
}
2022-12-04 21:53:13 +08:00
// Config implements constant.InboundListener
func (b *Base) Config() C.InboundConfig {
return b.config
}
2022-12-04 21:53:13 +08:00
// Address implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (b *Base) Address() string {
return b.RawAddress()
}
2022-12-04 21:53:13 +08:00
// Close implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (*Base) Close() error {
return nil
}
2022-12-04 21:53:13 +08:00
// Name implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (b *Base) Name() string {
return b.name
}
2022-12-04 21:53:13 +08:00
// RawAddress implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (b *Base) RawAddress() string {
return net.JoinHostPort(b.listenAddr.String(), strconv.Itoa(int(b.port)))
}
2022-12-04 21:53:13 +08:00
// Listen implements constant.InboundListener
func (*Base) Listen(tunnel C.Tunnel) error {
2022-12-04 13:37:14 +08:00
return nil
}
func (b *Base) Additions() []inbound.Addition {
return b.config.Additions()
}
2022-12-04 21:53:13 +08:00
var _ C.InboundListener = (*Base)(nil)
2022-12-04 13:37:14 +08:00
type BaseOption struct {
NameStr string `inbound:"name"`
Listen string `inbound:"listen,omitempty"`
2022-12-05 17:43:50 +08:00
Port int `inbound:"port,omitempty"`
SpecialRules string `inbound:"rule,omitempty"`
SpecialProxy string `inbound:"proxy,omitempty"`
2022-12-04 13:37:14 +08:00
}
2022-12-04 21:53:13 +08:00
func (o BaseOption) Name() string {
return o.NameStr
}
func (o BaseOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
func (o BaseOption) Additions() []inbound.Addition {
return []inbound.Addition{
inbound.WithInName(o.NameStr),
inbound.WithSpecialRules(o.SpecialRules),
inbound.WithSpecialProxy(o.SpecialProxy),
}
}
2022-12-04 21:53:13 +08:00
var _ C.InboundConfig = (*BaseOption)(nil)
func optionToString(option any) string {
str, _ := json.Marshal(option)
return string(str)
}