clash/listener/mixed/mixed.go

92 lines
2 KiB
Go
Raw Normal View History

package mixed
import (
2022-11-16 02:43:16 +00:00
"github.com/Dreamacro/clash/adapter/inbound"
"net"
"github.com/Dreamacro/clash/common/cache"
2021-06-15 09:13:40 +00:00
N "github.com/Dreamacro/clash/common/net"
2021-06-13 09:23:10 +00: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 14:18:49 +00:00
"github.com/Dreamacro/clash/transport/socks5"
)
2021-06-13 09:23:10 +00:00
type Listener struct {
2022-12-04 14:08:20 +00:00
listener net.Listener
addr string
name string
specialRules string
cache *cache.LruCache[string, bool]
closed bool
2021-07-31 16:35:37 +00: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-11-16 02:43:16 +00:00
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
2022-12-04 05:37:14 +00:00
return NewWithInfos(addr, "DEFAULT-MIXED", "", in)
}
2022-12-04 14:08:20 +00:00
func NewWithInfos(addr, name, specialRules string, in chan<- C.ConnContext) (*Listener, error) {
2022-11-16 02:43:16 +00:00
l, err := inbound.Listen("tcp", addr)
if err != nil {
return nil, err
}
ml := &Listener{
2022-12-04 14:08:20 +00:00
listener: l,
addr: addr,
name: name,
specialRules: specialRules,
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
}
2022-12-04 14:08:20 +00:00
go handleConn(ml.name, ml.specialRules, c, in, ml.cache)
}
}()
return ml, nil
}
2022-12-04 14:08:20 +00:00
func handleConn(name, specialRules string, conn net.Conn, in chan<- C.ConnContext, cache *cache.LruCache[string, bool]) {
conn.(*net.TCPConn).SetKeepAlive(true)
2021-06-15 09:13:40 +00:00
bufConn := N.NewBufferedConn(conn)
head, err := bufConn.Peek(1)
if err != nil {
return
}
switch head[0] {
case socks4.Version:
2022-12-04 14:08:20 +00:00
socks.HandleSocks4(name, specialRules, bufConn, in)
case socks5.Version:
2022-12-04 14:08:20 +00:00
socks.HandleSocks5(name, specialRules, bufConn, in)
default:
2022-12-04 14:08:20 +00:00
http.HandleConn(name, specialRules, bufConn, in, cache)
}
}