mihomo/listener/mixed/mixed.go

89 lines
1.8 KiB
Go
Raw Normal View History

package mixed
import (
2022-07-22 15:16:09 +08:00
"context"
2022-11-14 12:11:54 +08:00
"github.com/database64128/tfo-go/v2"
"net"
"github.com/Dreamacro/clash/common/cache"
2021-06-15 17:13:40 +08:00
N "github.com/Dreamacro/clash/common/net"
2021-06-13 17:23:10 +08:00
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/listener/http"
"github.com/Dreamacro/clash/listener/socks"
"github.com/Dreamacro/clash/transport/socks4"
2021-05-13 22:18:49 +08:00
"github.com/Dreamacro/clash/transport/socks5"
)
2021-06-13 17:23:10 +08:00
type Listener struct {
listener net.Listener
2021-08-01 00:35:37 +08:00
addr string
cache *cache.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()
}
2022-07-22 15:16:09 +08:00
func New(addr string, inboundTfo bool, in chan<- C.ConnContext) (*Listener, error) {
lc := tfo.ListenConfig{
DisableTFO: !inboundTfo,
}
l, err := lc.Listen(context.Background(), "tcp", addr)
if err != nil {
return nil, err
}
ml := &Listener{
listener: l,
2021-08-01 00:35:37 +08:00
addr: addr,
cache: cache.New[string, bool](cache.WithAge[string, bool](30)),
}
go func() {
for {
c, err := ml.listener.Accept()
if err != nil {
if ml.closed {
break
}
continue
}
2021-06-13 17:23:10 +08:00
go handleConn(c, in, ml.cache)
}
}()
return ml, nil
}
func handleConn(conn net.Conn, in chan<- C.ConnContext, cache *cache.LruCache[string, bool]) {
conn.(*net.TCPConn).SetKeepAlive(true)
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, in)
case socks5.Version:
socks.HandleSocks5(bufConn, in)
default:
http.HandleConn(bufConn, in, cache)
}
}