clash/listener/inbound/base.go

90 lines
1.9 KiB
Go
Raw Normal View History

2022-12-04 05:37:14 +00:00
package inbound
import (
"encoding/json"
2022-12-04 05:37:14 +00:00
"net"
"net/netip"
"strconv"
C "github.com/Dreamacro/clash/constant"
)
type Base struct {
config *BaseOption
2022-12-04 05:37:14 +00:00
name string
preferRulesName string
listenAddr netip.Addr
port int
}
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 13:53:13 +00:00
name: options.Name(),
2022-12-04 05:37:14 +00:00
listenAddr: addr,
preferRulesName: options.PreferRulesName,
port: options.Port,
config: options,
2022-12-04 05:37:14 +00:00
}, nil
}
2022-12-04 13:53:13 +00:00
// Config implements constant.InboundListener
func (b *Base) Config() C.InboundConfig {
return b.config
}
2022-12-04 13:53:13 +00:00
// Address implements constant.InboundListener
2022-12-04 05:37:14 +00:00
func (b *Base) Address() string {
return b.RawAddress()
}
2022-12-04 13:53:13 +00:00
// Close implements constant.InboundListener
2022-12-04 05:37:14 +00:00
func (*Base) Close() error {
return nil
}
2022-12-04 13:53:13 +00:00
// Name implements constant.InboundListener
2022-12-04 05:37:14 +00:00
func (b *Base) Name() string {
return b.name
}
2022-12-04 13:53:13 +00:00
// RawAddress implements constant.InboundListener
2022-12-04 05:37:14 +00:00
func (b *Base) RawAddress() string {
return net.JoinHostPort(b.listenAddr.String(), strconv.Itoa(int(b.port)))
}
2022-12-04 13:53:13 +00:00
// Listen implements constant.InboundListener
2022-12-04 07:15:23 +00:00
func (*Base) Listen(tcpIn chan<- C.ConnContext, udpIn chan<- C.PacketAdapter) error {
2022-12-04 05:37:14 +00:00
return nil
}
2022-12-04 13:53:13 +00:00
var _ C.InboundListener = (*Base)(nil)
2022-12-04 05:37:14 +00:00
type BaseOption struct {
2022-12-04 13:53:13 +00:00
NameStr string `inbound:"name"`
2022-12-04 05:37:14 +00:00
Listen string `inbound:"listen,omitempty"`
Port int `inbound:"port"`
PreferRulesName string `inbound:"rule,omitempty"`
}
2022-12-04 13:53:13 +00:00
func (o BaseOption) Name() string {
return o.NameStr
}
func (o BaseOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
}
var _ C.InboundConfig = (*BaseOption)(nil)
func optionToString(option any) string {
str, _ := json.Marshal(option)
return string(str)
}