github.com/metacubex/mihomo@v1.18.5/listener/inbound/tproxy.go (about) 1 package inbound 2 3 import ( 4 "fmt" 5 6 C "github.com/metacubex/mihomo/constant" 7 "github.com/metacubex/mihomo/listener/tproxy" 8 "github.com/metacubex/mihomo/log" 9 ) 10 11 type TProxyOption struct { 12 BaseOption 13 UDP bool `inbound:"udp,omitempty"` 14 } 15 16 func (o TProxyOption) Equal(config C.InboundConfig) bool { 17 return optionToString(o) == optionToString(config) 18 } 19 20 type TProxy struct { 21 *Base 22 config *TProxyOption 23 lUDP *tproxy.UDPListener 24 lTCP *tproxy.Listener 25 udp bool 26 } 27 28 func NewTProxy(options *TProxyOption) (*TProxy, error) { 29 base, err := NewBase(&options.BaseOption) 30 if err != nil { 31 return nil, err 32 } 33 return &TProxy{ 34 Base: base, 35 config: options, 36 udp: options.UDP, 37 }, nil 38 39 } 40 41 // Config implements constant.InboundListener 42 func (t *TProxy) Config() C.InboundConfig { 43 return t.config 44 } 45 46 // Address implements constant.InboundListener 47 func (t *TProxy) Address() string { 48 return t.lTCP.Address() 49 } 50 51 // Listen implements constant.InboundListener 52 func (t *TProxy) Listen(tunnel C.Tunnel) error { 53 var err error 54 t.lTCP, err = tproxy.New(t.RawAddress(), tunnel, t.Additions()...) 55 if err != nil { 56 return err 57 } 58 if t.udp { 59 t.lUDP, err = tproxy.NewUDP(t.RawAddress(), tunnel, t.Additions()...) 60 if err != nil { 61 return err 62 } 63 } 64 log.Infoln("TProxy[%s] proxy listening at: %s", t.Name(), t.Address()) 65 return nil 66 } 67 68 // Close implements constant.InboundListener 69 func (t *TProxy) Close() error { 70 var tcpErr error 71 var udpErr error 72 if t.lTCP != nil { 73 tcpErr = t.lTCP.Close() 74 } 75 if t.lUDP != nil { 76 udpErr = t.lUDP.Close() 77 } 78 79 if tcpErr != nil && udpErr != nil { 80 return fmt.Errorf("tcp close err: %s and udp close err: %s", tcpErr, udpErr) 81 } 82 if tcpErr != nil { 83 return tcpErr 84 } 85 if udpErr != nil { 86 return udpErr 87 } 88 return nil 89 } 90 91 var _ C.InboundListener = (*TProxy)(nil)