mihomo/listener/mixed/mixed.go

90 lines
1.9 KiB
Go
Raw Permalink Normal View History

package mixed
import (
"net"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/adapter/inbound"
2023-12-02 17:07:36 +08:00
"github.com/metacubex/mihomo/common/lru"
2023-11-03 21:01:45 +08:00
N "github.com/metacubex/mihomo/common/net"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/listener/http"
"github.com/metacubex/mihomo/listener/socks"
"github.com/metacubex/mihomo/transport/socks4"
"github.com/metacubex/mihomo/transport/socks5"
)
2021-06-13 17:23:10 +08:00
type Listener struct {
listener net.Listener
addr string
2023-12-02 17:07:36 +08:00
cache *lru.LruCache[string, bool]
closed bool
2021-08-01 00:35:37 +08:00
}
// RawAddress implements C.Listener
func (l *Listener) RawAddress() string {
return l.addr
}
// Address implements C.Listener
func (l *Listener) Address() string {
return l.listener.Addr().String()
}
// Close implements C.Listener
func (l *Listener) Close() error {
l.closed = true
return l.listener.Close()
}
func New(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-MIXED"),
inbound.WithSpecialRules(""),
}
}
2022-11-16 10:43:16 +08:00
l, err := inbound.Listen("tcp", addr)
if err != nil {
return nil, err
}
ml := &Listener{
listener: l,
addr: addr,
2023-12-02 17:07:36 +08:00
cache: lru.New[string, bool](lru.WithAge[string, bool](30)),
}
go func() {
for {
c, err := ml.listener.Accept()
if err != nil {
if ml.closed {
break
}
continue
}
go handleConn(c, tunnel, ml.cache, additions...)
}
}()
return ml, nil
}
2023-12-02 17:07:36 +08:00
func handleConn(conn net.Conn, tunnel C.Tunnel, cache *lru.LruCache[string, bool], additions ...inbound.Addition) {
N.TCPKeepAlive(conn)
2021-06-15 17:13:40 +08:00
bufConn := N.NewBufferedConn(conn)
head, err := bufConn.Peek(1)
if err != nil {
return
}
switch head[0] {
case socks4.Version:
socks.HandleSocks4(bufConn, tunnel, additions...)
case socks5.Version:
socks.HandleSocks5(bufConn, tunnel, additions...)
default:
http.HandleConn(bufConn, tunnel, cache, additions...)
}
}