mihomo/listener/inbound/socks.go

87 lines
1.8 KiB
Go
Raw Normal View History

2022-12-04 13:37:14 +08:00
package inbound
import (
"fmt"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/listener/socks"
"github.com/Dreamacro/clash/log"
)
type SocksOption struct {
BaseOption
2022-12-04 21:53:13 +08:00
UDP bool `inbound:"udp,omitempty"`
}
func (o SocksOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
2022-12-04 13:37:14 +08:00
}
type Socks struct {
*Base
config *SocksOption
udp bool
stl *socks.Listener
sul *socks.UDPListener
2022-12-04 13:37:14 +08:00
}
func NewSocks(options *SocksOption) (*Socks, error) {
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
return &Socks{
Base: base,
config: options,
2022-12-04 21:53:13 +08:00
udp: options.UDP,
2022-12-04 13:37:14 +08:00
}, nil
}
2022-12-04 21:53:13 +08:00
// Config implements constant.InboundListener
func (s *Socks) Config() C.InboundConfig {
return s.config
}
2022-12-04 21:53:13 +08:00
// Close implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (s *Socks) Close() error {
var err error
if s.stl != nil {
if tcpErr := s.stl.Close(); tcpErr != nil {
err = tcpErr
}
}
if s.udp && s.sul != nil {
if udpErr := s.sul.Close(); udpErr != nil {
if err == nil {
err = udpErr
} else {
return fmt.Errorf("close tcp err: %s, close udp err: %s", err.Error(), udpErr.Error())
}
}
}
return err
}
2022-12-04 21:53:13 +08:00
// Address implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (s *Socks) Address() string {
return s.stl.Address()
}
2022-12-04 21:53:13 +08:00
// Listen implements constant.InboundListener
2022-12-04 15:15:23 +08:00
func (s *Socks) Listen(tcpIn chan<- C.ConnContext, udpIn chan<- C.PacketAdapter) error {
2022-12-04 13:37:14 +08:00
var err error
2022-12-04 22:08:20 +08:00
if s.stl, err = socks.NewWithInfos(s.RawAddress(), s.name, s.specialRules, tcpIn); err != nil {
2022-12-04 13:37:14 +08:00
return err
}
if s.udp {
2022-12-04 22:08:20 +08:00
if s.sul, err = socks.NewUDPWithInfos(s.RawAddress(), s.name, s.specialRules, udpIn); err != nil {
2022-12-04 13:37:14 +08:00
return err
}
}
log.Infoln("SOCKS[%s] proxy listening at: %s", s.Name(), s.Address())
return nil
}
2022-12-04 21:53:13 +08:00
var _ C.InboundListener = (*Socks)(nil)