clash/listener/mixed/mixed.go

67 lines
1.1 KiB
Go
Raw Normal View History

package mixed
import (
"net"
"time"
"github.com/Dreamacro/clash/common/cache"
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"
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 {
net.Listener
address string
closed bool
cache *cache.Cache
}
2021-06-13 09:23:10 +00:00
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
2021-06-13 09:23:10 +00:00
ml := &Listener{l, addr, false, cache.New(30 * time.Second)}
go func() {
for {
c, err := ml.Accept()
if err != nil {
if ml.closed {
break
}
continue
}
2021-06-13 09:23:10 +00:00
go handleConn(c, in, ml.cache)
}
}()
return ml, nil
}
2021-06-13 09:23:10 +00:00
func (l *Listener) Close() {
l.closed = true
l.Listener.Close()
}
2021-06-13 09:23:10 +00:00
func (l *Listener) Address() string {
return l.address
}
2021-06-13 09:23:10 +00:00
func handleConn(conn net.Conn, in chan<- C.ConnContext, cache *cache.Cache) {
bufConn := NewBufferedConn(conn)
head, err := bufConn.Peek(1)
if err != nil {
return
}
if head[0] == socks5.Version {
2021-06-13 09:23:10 +00:00
socks.HandleSocks(bufConn, in)
return
}
2021-06-13 09:23:10 +00:00
http.HandleConn(bufConn, in, cache)
}