mihomo/listener/inbound/base.go

102 lines
2.1 KiB
Go
Raw 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"
"github.com/Dreamacro/clash/adapter/inbound"
2022-12-04 13:37:14 +08:00
C "github.com/Dreamacro/clash/constant"
)
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
2022-12-04 15:15:23 +08:00
func (*Base) Listen(tcpIn chan<- C.ConnContext, udpIn chan<- C.PacketAdapter) 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"`
Port int `inbound:"port"`
SpecialRules string `inbound:"rule,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),
}
}
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)
}