Clash.Meta/listener/listener.go

728 lines
14 KiB
Go
Raw Normal View History

2022-11-18 22:57:33 +08:00
package listener
2018-07-15 22:23:20 +08:00
import (
2018-11-21 13:47:46 +08:00
"fmt"
"net"
"strconv"
2022-11-18 22:57:33 +08:00
"strings"
"sync"
2018-07-15 22:23:20 +08:00
2023-11-03 21:01:45 +08:00
C "github.com/metacubex/mihomo/constant"
LC "github.com/metacubex/mihomo/listener/config"
"github.com/metacubex/mihomo/listener/http"
"github.com/metacubex/mihomo/listener/mixed"
"github.com/metacubex/mihomo/listener/redir"
embedSS "github.com/metacubex/mihomo/listener/shadowsocks"
"github.com/metacubex/mihomo/listener/sing_shadowsocks"
"github.com/metacubex/mihomo/listener/sing_tun"
"github.com/metacubex/mihomo/listener/sing_vmess"
"github.com/metacubex/mihomo/listener/socks"
"github.com/metacubex/mihomo/listener/tproxy"
"github.com/metacubex/mihomo/listener/tuic"
LT "github.com/metacubex/mihomo/listener/tunnel"
"github.com/metacubex/mihomo/log"
2022-11-18 22:57:33 +08:00
"github.com/samber/lo"
2018-07-15 22:23:20 +08:00
)
var (
allowLan = false
bindAddress = "*"
2018-11-21 13:47:46 +08:00
socksListener *socks.Listener
socksUDPListener *socks.UDPListener
httpListener *http.Listener
redirListener *redir.Listener
redirUDPListener *tproxy.UDPListener
tproxyListener *tproxy.Listener
tproxyUDPListener *tproxy.UDPListener
mixedListener *mixed.Listener
mixedUDPLister *socks.UDPListener
tunnelTCPListeners = map[string]*LT.Listener{}
tunnelUDPListeners = map[string]*LT.PacketConn{}
2022-12-04 21:53:13 +08:00
inboundListeners = map[string]C.InboundListener{}
tunLister *sing_tun.Listener
shadowSocksListener C.MultiAddrListener
vmessListener *sing_vmess.Listener
2022-11-28 17:09:25 +08:00
tuicListener *tuic.Listener
// lock for recreate function
2024-08-24 13:25:23 +08:00
socksMux sync.Mutex
httpMux sync.Mutex
redirMux sync.Mutex
tproxyMux sync.Mutex
mixedMux sync.Mutex
tunnelMux sync.Mutex
inboundMux sync.Mutex
tunMux sync.Mutex
ssMux sync.Mutex
vmessMux sync.Mutex
tuicMux sync.Mutex
2022-11-03 18:56:03 +08:00
LastTunConf LC.Tun
LastTuicConf LC.TuicServer
2018-07-15 22:23:20 +08:00
)
2018-11-21 13:47:46 +08:00
type Ports struct {
Port int `json:"port"`
SocksPort int `json:"socks-port"`
RedirPort int `json:"redir-port"`
TProxyPort int `json:"tproxy-port"`
MixedPort int `json:"mixed-port"`
ShadowSocksConfig string `json:"ss-config"`
VmessConfig string `json:"vmess-config"`
2018-11-21 13:47:46 +08:00
}
func GetTunConf() LC.Tun {
2022-11-03 18:56:03 +08:00
if tunLister == nil {
return LastTunConf
2022-05-03 19:13:37 +08:00
}
2022-11-03 18:56:03 +08:00
return tunLister.Config()
2022-05-03 19:13:37 +08:00
}
func GetTuicConf() LC.TuicServer {
if tuicListener == nil {
return LC.TuicServer{Enable: false}
}
return tuicListener.Config()
}
2018-11-21 13:47:46 +08:00
func AllowLan() bool {
return allowLan
}
func BindAddress() string {
return bindAddress
}
2018-11-21 13:47:46 +08:00
func SetAllowLan(al bool) {
allowLan = al
2018-07-15 22:23:20 +08:00
}
func SetBindAddress(host string) {
bindAddress = host
}
func ReCreateHTTP(port int, tunnel C.Tunnel) {
httpMux.Lock()
defer httpMux.Unlock()
var err error
defer func() {
if err != nil {
log.Errorln("Start HTTP server error: %s", err.Error())
}
}()
addr := genAddr(bindAddress, port, allowLan)
2018-11-21 13:47:46 +08:00
if httpListener != nil {
2021-08-01 00:35:37 +08:00
if httpListener.RawAddress() == addr {
return
2018-11-21 13:47:46 +08:00
}
httpListener.Close()
2018-11-21 13:47:46 +08:00
httpListener = nil
}
if portIsZero(addr) {
return
2018-07-15 22:23:20 +08:00
}
httpListener, err = http.New(addr, tunnel)
2018-07-15 22:23:20 +08:00
if err != nil {
2022-01-04 17:58:50 +08:00
log.Errorln("Start HTTP server error: %s", err.Error())
return
2018-07-15 22:23:20 +08:00
}
2021-06-13 17:23:10 +08:00
log.Infoln("HTTP proxy listening at: %s", httpListener.Address())
2018-07-15 22:23:20 +08:00
}
func ReCreateSocks(port int, tunnel C.Tunnel) {
socksMux.Lock()
defer socksMux.Unlock()
var err error
defer func() {
if err != nil {
log.Errorln("Start SOCKS server error: %s", err.Error())
}
}()
addr := genAddr(bindAddress, port, allowLan)
2018-11-21 13:47:46 +08:00
shouldTCPIgnore := false
shouldUDPIgnore := false
2018-11-21 13:47:46 +08:00
if socksListener != nil {
2021-08-01 00:35:37 +08:00
if socksListener.RawAddress() != addr {
socksListener.Close()
socksListener = nil
} else {
shouldTCPIgnore = true
}
}
if socksUDPListener != nil {
2021-08-01 00:35:37 +08:00
if socksUDPListener.RawAddress() != addr {
socksUDPListener.Close()
socksUDPListener = nil
} else {
shouldUDPIgnore = true
2018-11-21 13:47:46 +08:00
}
}
if shouldTCPIgnore && shouldUDPIgnore {
return
}
2018-11-21 13:47:46 +08:00
if portIsZero(addr) {
return
2018-07-15 22:23:20 +08:00
}
tcpListener, err := socks.New(addr, tunnel)
2018-07-15 22:23:20 +08:00
if err != nil {
return
2018-07-15 22:23:20 +08:00
}
udpListener, err := socks.NewUDP(addr, tunnel)
if err != nil {
tcpListener.Close()
return
}
socksListener = tcpListener
socksUDPListener = udpListener
log.Infoln("SOCKS proxy listening at: %s", socksListener.Address())
2018-07-15 22:23:20 +08:00
}
func ReCreateRedir(port int, tunnel C.Tunnel) {
redirMux.Lock()
defer redirMux.Unlock()
var err error
defer func() {
if err != nil {
log.Errorln("Start Redir server error: %s", err.Error())
}
}()
addr := genAddr(bindAddress, port, allowLan)
2018-11-21 13:47:46 +08:00
if redirListener != nil {
2021-08-01 00:35:37 +08:00
if redirListener.RawAddress() == addr {
return
2018-11-21 13:47:46 +08:00
}
redirListener.Close()
2018-11-21 13:47:46 +08:00
redirListener = nil
}
if redirUDPListener != nil {
2021-08-01 00:35:37 +08:00
if redirUDPListener.RawAddress() == addr {
return
}
redirUDPListener.Close()
redirUDPListener = nil
}
2018-11-21 13:47:46 +08:00
if portIsZero(addr) {
return
2018-08-12 04:00:34 +08:00
}
redirListener, err = redir.New(addr, tunnel)
2018-08-12 04:00:34 +08:00
if err != nil {
return
2018-08-12 04:00:34 +08:00
}
redirUDPListener, err = tproxy.NewUDP(addr, tunnel)
if err != nil {
log.Warnln("Failed to start Redir UDP Listener: %s", err)
}
2021-06-13 17:23:10 +08:00
log.Infoln("Redirect proxy listening at: %s", redirListener.Address())
2018-08-12 04:00:34 +08:00
}
func ReCreateShadowSocks(shadowSocksConfig string, tunnel C.Tunnel) {
ssMux.Lock()
defer ssMux.Unlock()
var err error
defer func() {
if err != nil {
log.Errorln("Start ShadowSocks server error: %s", err.Error())
}
}()
var ssConfig LC.ShadowsocksServer
if addr, cipher, password, err := embedSS.ParseSSURL(shadowSocksConfig); err == nil {
ssConfig = LC.ShadowsocksServer{
2022-12-05 16:29:50 +08:00
Enable: len(shadowSocksConfig) > 0,
Listen: addr,
Password: password,
Cipher: cipher,
Udp: true,
}
}
shouldIgnore := false
if shadowSocksListener != nil {
if shadowSocksListener.Config() != ssConfig.String() {
shadowSocksListener.Close()
shadowSocksListener = nil
} else {
shouldIgnore = true
}
}
if shouldIgnore {
return
}
if !ssConfig.Enable {
return
}
listener, err := sing_shadowsocks.New(ssConfig, tunnel)
if err != nil {
return
}
shadowSocksListener = listener
for _, addr := range shadowSocksListener.AddrList() {
log.Infoln("ShadowSocks proxy listening at: %s", addr.String())
}
return
}
func ReCreateVmess(vmessConfig string, tunnel C.Tunnel) {
vmessMux.Lock()
defer vmessMux.Unlock()
var err error
defer func() {
if err != nil {
log.Errorln("Start Vmess server error: %s", err.Error())
}
}()
var vsConfig LC.VmessServer
if addr, username, password, err := sing_vmess.ParseVmessURL(vmessConfig); err == nil {
vsConfig = LC.VmessServer{
2022-12-05 16:29:50 +08:00
Enable: len(vmessConfig) > 0,
Listen: addr,
Users: []LC.VmessUser{{Username: username, UUID: password, AlterID: 1}},
}
}
shouldIgnore := false
if vmessListener != nil {
if vmessListener.Config() != vsConfig.String() {
vmessListener.Close()
vmessListener = nil
} else {
shouldIgnore = true
}
}
if shouldIgnore {
return
}
if !vsConfig.Enable {
return
}
listener, err := sing_vmess.New(vsConfig, tunnel)
if err != nil {
return
}
vmessListener = listener
for _, addr := range vmessListener.AddrList() {
log.Infoln("Vmess proxy listening at: %s", addr.String())
}
return
}
func ReCreateTuic(config LC.TuicServer, tunnel C.Tunnel) {
2022-11-28 17:09:25 +08:00
tuicMux.Lock()
defer func() {
LastTuicConf = config
tuicMux.Unlock()
}()
2022-11-28 17:09:25 +08:00
shouldIgnore := false
var err error
defer func() {
if err != nil {
log.Errorln("Start Tuic server error: %s", err.Error())
}
}()
if tuicListener != nil {
if tuicListener.Config().String() != config.String() {
tuicListener.Close()
tuicListener = nil
} else {
shouldIgnore = true
}
}
if shouldIgnore {
return
}
if !config.Enable {
return
}
listener, err := tuic.New(config, tunnel)
2022-11-28 17:09:25 +08:00
if err != nil {
return
}
tuicListener = listener
2022-12-04 23:05:13 +08:00
for _, addr := range tuicListener.AddrList() {
log.Infoln("Tuic proxy listening at: %s", addr.String())
}
2022-11-28 17:09:25 +08:00
return
}
func ReCreateTProxy(port int, tunnel C.Tunnel) {
tproxyMux.Lock()
defer tproxyMux.Unlock()
var err error
defer func() {
if err != nil {
log.Errorln("Start TProxy server error: %s", err.Error())
}
}()
addr := genAddr(bindAddress, port, allowLan)
if tproxyListener != nil {
2021-08-01 00:35:37 +08:00
if tproxyListener.RawAddress() == addr {
return
}
tproxyListener.Close()
tproxyListener = nil
}
if tproxyUDPListener != nil {
2021-08-01 00:35:37 +08:00
if tproxyUDPListener.RawAddress() == addr {
return
}
tproxyUDPListener.Close()
tproxyUDPListener = nil
}
if portIsZero(addr) {
return
}
tproxyListener, err = tproxy.New(addr, tunnel)
if err != nil {
return
}
tproxyUDPListener, err = tproxy.NewUDP(addr, tunnel)
if err != nil {
log.Warnln("Failed to start TProxy UDP Listener: %s", err)
}
2021-06-13 17:23:10 +08:00
log.Infoln("TProxy server listening at: %s", tproxyListener.Address())
}
func ReCreateMixed(port int, tunnel C.Tunnel) {
mixedMux.Lock()
defer mixedMux.Unlock()
var err error
defer func() {
if err != nil {
log.Errorln("Start Mixed(http+socks) server error: %s", err.Error())
}
}()
addr := genAddr(bindAddress, port, allowLan)
shouldTCPIgnore := false
shouldUDPIgnore := false
if mixedListener != nil {
2021-08-01 00:35:37 +08:00
if mixedListener.RawAddress() != addr {
mixedListener.Close()
mixedListener = nil
} else {
shouldTCPIgnore = true
}
}
if mixedUDPLister != nil {
2021-08-01 00:35:37 +08:00
if mixedUDPLister.RawAddress() != addr {
mixedUDPLister.Close()
mixedUDPLister = nil
} else {
shouldUDPIgnore = true
}
}
if shouldTCPIgnore && shouldUDPIgnore {
return
}
if portIsZero(addr) {
return
}
mixedListener, err = mixed.New(addr, tunnel)
if err != nil {
return
}
mixedUDPLister, err = socks.NewUDP(addr, tunnel)
if err != nil {
mixedListener.Close()
return
}
log.Infoln("Mixed(http+socks) proxy listening at: %s", mixedListener.Address())
}
func ReCreateTun(tunConf LC.Tun, tunnel C.Tunnel) {
2024-08-24 13:25:23 +08:00
tunConf.Sort()
2021-11-17 16:03:47 +08:00
tunMux.Lock()
2022-11-02 23:58:51 +08:00
defer func() {
LastTunConf = tunConf
2022-11-02 23:58:51 +08:00
tunMux.Unlock()
}()
2021-11-17 16:03:47 +08:00
var err error
defer func() {
if err != nil {
2022-03-09 05:08:35 +08:00
log.Errorln("Start TUN listening error: %s", err.Error())
tunConf.Enable = false
}
}()
2024-08-24 13:25:23 +08:00
if tunConf.Equal(LastTunConf) {
if tunLister != nil {
tunLister.FlushDefaultInterface()
}
2022-05-03 19:13:37 +08:00
return
}
closeTunListener()
2021-11-17 16:03:47 +08:00
2022-03-09 05:08:35 +08:00
if !tunConf.Enable {
return
2021-11-17 16:03:47 +08:00
}
2022-05-03 19:13:37 +08:00
lister, err := sing_tun.New(tunConf, tunnel)
2022-12-08 11:29:39 +08:00
if err != nil {
return
}
tunLister = lister
2022-12-05 17:43:50 +08:00
log.Infoln("[TUN] Tun adapter listening at: %s", tunLister.Address())
2021-11-17 16:03:47 +08:00
}
func PatchTunnel(tunnels []LC.Tunnel, tunnel C.Tunnel) {
2022-11-18 22:57:33 +08:00
tunnelMux.Lock()
defer tunnelMux.Unlock()
type addrProxy struct {
network string
addr string
target string
proxy string
}
tcpOld := lo.Map(
lo.Keys(tunnelTCPListeners),
func(key string, _ int) addrProxy {
parts := strings.Split(key, "/")
return addrProxy{
network: "tcp",
addr: parts[0],
target: parts[1],
proxy: parts[2],
}
},
)
udpOld := lo.Map(
lo.Keys(tunnelUDPListeners),
func(key string, _ int) addrProxy {
parts := strings.Split(key, "/")
return addrProxy{
network: "udp",
addr: parts[0],
target: parts[1],
proxy: parts[2],
}
},
)
oldElm := lo.Union(tcpOld, udpOld)
newElm := lo.FlatMap(
tunnels,
2022-12-06 10:13:05 +08:00
func(tunnel LC.Tunnel, _ int) []addrProxy {
2022-11-18 22:57:33 +08:00
return lo.Map(
tunnel.Network,
func(network string, _ int) addrProxy {
return addrProxy{
network: network,
addr: tunnel.Address,
target: tunnel.Target,
proxy: tunnel.Proxy,
}
},
)
},
)
needClose, needCreate := lo.Difference(oldElm, newElm)
for _, elm := range needClose {
key := fmt.Sprintf("%s/%s/%s", elm.addr, elm.target, elm.proxy)
if elm.network == "tcp" {
tunnelTCPListeners[key].Close()
delete(tunnelTCPListeners, key)
} else {
tunnelUDPListeners[key].Close()
delete(tunnelUDPListeners, key)
}
}
for _, elm := range needCreate {
key := fmt.Sprintf("%s/%s/%s", elm.addr, elm.target, elm.proxy)
if elm.network == "tcp" {
l, err := LT.New(elm.addr, elm.target, elm.proxy, tunnel)
2022-11-18 22:57:33 +08:00
if err != nil {
2022-11-22 21:01:51 +08:00
log.Errorln("Start tunnel %s error: %s", elm.target, err.Error())
2022-11-18 22:57:33 +08:00
continue
}
tunnelTCPListeners[key] = l
log.Infoln("Tunnel(tcp/%s) proxy %s listening at: %s", elm.target, elm.proxy, tunnelTCPListeners[key].Address())
} else {
l, err := LT.NewUDP(elm.addr, elm.target, elm.proxy, tunnel)
2022-11-18 22:57:33 +08:00
if err != nil {
2022-11-22 21:01:51 +08:00
log.Errorln("Start tunnel %s error: %s", elm.target, err.Error())
2022-11-18 22:57:33 +08:00
continue
}
tunnelUDPListeners[key] = l
log.Infoln("Tunnel(udp/%s) proxy %s listening at: %s", elm.target, elm.proxy, tunnelUDPListeners[key].Address())
}
}
}
func PatchInboundListeners(newListenerMap map[string]C.InboundListener, tunnel C.Tunnel, dropOld bool) {
2022-12-04 21:53:13 +08:00
inboundMux.Lock()
defer inboundMux.Unlock()
for name, newListener := range newListenerMap {
if oldListener, ok := inboundListeners[name]; ok {
if !oldListener.Config().Equal(newListener.Config()) {
_ = oldListener.Close()
} else {
continue
}
}
if err := newListener.Listen(tunnel); err != nil {
2022-12-04 21:53:13 +08:00
log.Errorln("Listener %s listen err: %s", name, err.Error())
continue
}
inboundListeners[name] = newListener
}
if dropOld {
for name, oldListener := range inboundListeners {
if _, ok := newListenerMap[name]; !ok {
_ = oldListener.Close()
delete(inboundListeners, name)
}
}
}
}
2018-11-21 13:47:46 +08:00
// GetPorts return the ports of proxy servers
func GetPorts() *Ports {
ports := &Ports{}
if httpListener != nil {
_, portStr, _ := net.SplitHostPort(httpListener.Address())
2018-11-21 13:47:46 +08:00
port, _ := strconv.Atoi(portStr)
ports.Port = port
}
if socksListener != nil {
_, portStr, _ := net.SplitHostPort(socksListener.Address())
2018-11-21 13:47:46 +08:00
port, _ := strconv.Atoi(portStr)
ports.SocksPort = port
2018-07-15 22:23:20 +08:00
}
2018-11-21 13:47:46 +08:00
if redirListener != nil {
_, portStr, _ := net.SplitHostPort(redirListener.Address())
2018-11-21 13:47:46 +08:00
port, _ := strconv.Atoi(portStr)
ports.RedirPort = port
}
if tproxyListener != nil {
_, portStr, _ := net.SplitHostPort(tproxyListener.Address())
port, _ := strconv.Atoi(portStr)
ports.TProxyPort = port
}
if mixedListener != nil {
_, portStr, _ := net.SplitHostPort(mixedListener.Address())
port, _ := strconv.Atoi(portStr)
ports.MixedPort = port
}
if shadowSocksListener != nil {
ports.ShadowSocksConfig = shadowSocksListener.Config()
}
if vmessListener != nil {
ports.VmessConfig = vmessListener.Config()
}
2018-11-21 13:47:46 +08:00
return ports
}
2018-07-15 22:23:20 +08:00
2018-11-21 13:47:46 +08:00
func portIsZero(addr string) bool {
_, port, err := net.SplitHostPort(addr)
if port == "0" || port == "" || err != nil {
return true
}
return false
2018-07-15 22:23:20 +08:00
}
func genAddr(host string, port int, allowLan bool) string {
2018-11-21 13:47:46 +08:00
if allowLan {
if host == "*" {
return fmt.Sprintf(":%d", port)
}
2021-03-24 01:00:21 +08:00
return fmt.Sprintf("%s:%d", host, port)
2018-11-21 13:47:46 +08:00
}
2018-11-21 13:47:46 +08:00
return fmt.Sprintf("127.0.0.1:%d", port)
2018-07-15 22:23:20 +08:00
}
2021-11-17 16:03:47 +08:00
func closeTunListener() {
if tunLister != nil {
tunLister.Close()
tunLister = nil
2021-11-17 16:03:47 +08:00
}
}
2023-09-02 14:10:26 +08:00
func Cleanup() {
closeTunListener()
2021-11-17 16:03:47 +08:00
}