mihomo/listener/inbound/tproxy.go

92 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-12-04 13:37:14 +08:00
package inbound
import (
"fmt"
2023-11-03 21:01:45 +08:00
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/tproxy"
"github.com/metacubex/mihomo/log"
2022-12-04 13:37:14 +08:00
)
type TProxyOption struct {
BaseOption
2022-12-04 21:53:13 +08:00
UDP bool `inbound:"udp,omitempty"`
}
func (o TProxyOption) Equal(config C.InboundConfig) bool {
return optionToString(o) == optionToString(config)
2022-12-04 13:37:14 +08:00
}
type TProxy struct {
*Base
config *TProxyOption
lUDP *tproxy.UDPListener
lTCP *tproxy.Listener
udp bool
2022-12-04 13:37:14 +08:00
}
func NewTProxy(options *TProxyOption) (*TProxy, error) {
base, err := NewBase(&options.BaseOption)
if err != nil {
return nil, err
}
return &TProxy{
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 (t *TProxy) Config() C.InboundConfig {
return t.config
}
2022-12-04 21:53:13 +08:00
// Address implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (t *TProxy) Address() string {
return t.lTCP.Address()
}
2022-12-04 21:53:13 +08:00
// Listen implements constant.InboundListener
func (t *TProxy) Listen(tunnel C.Tunnel) error {
2022-12-04 13:37:14 +08:00
var err error
t.lTCP, err = tproxy.New(t.RawAddress(), tunnel, t.Additions()...)
2022-12-04 13:37:14 +08:00
if err != nil {
return err
}
if t.udp {
t.lUDP, err = tproxy.NewUDP(t.RawAddress(), tunnel, t.Additions()...)
2023-03-27 22:18:54 +08:00
if err != nil {
return err
2022-12-04 13:37:14 +08:00
}
}
log.Infoln("TProxy[%s] proxy listening at: %s", t.Name(), t.Address())
return nil
}
2022-12-04 21:53:13 +08:00
// Close implements constant.InboundListener
2022-12-04 13:37:14 +08:00
func (t *TProxy) Close() error {
var tcpErr error
var udpErr error
if t.lTCP != nil {
tcpErr = t.lTCP.Close()
}
if t.lUDP != nil {
udpErr = t.lUDP.Close()
}
if tcpErr != nil && udpErr != nil {
return fmt.Errorf("tcp close err: %s and udp close err: %s", tcpErr, udpErr)
}
if tcpErr != nil {
return tcpErr
}
if udpErr != nil {
return udpErr
}
return nil
}
2022-12-04 21:53:13 +08:00
var _ C.InboundListener = (*TProxy)(nil)