2020-05-12 11:29:53 +08:00
|
|
|
package mixed
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"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"
|
2021-07-18 16:09:09 +08:00
|
|
|
"github.com/Dreamacro/clash/transport/socks4"
|
2021-05-13 22:18:49 +08:00
|
|
|
"github.com/Dreamacro/clash/transport/socks5"
|
2020-05-12 11:29:53 +08:00
|
|
|
)
|
|
|
|
|
2021-06-13 17:23:10 +08:00
|
|
|
type Listener struct {
|
2021-06-13 23:05:22 +08:00
|
|
|
listener net.Listener
|
|
|
|
closed bool
|
|
|
|
cache *cache.Cache
|
2020-05-12 11:29:53 +08:00
|
|
|
}
|
|
|
|
|
2021-06-13 17:23:10 +08:00
|
|
|
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
|
2020-05-12 11:29:53 +08:00
|
|
|
l, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-07-19 14:07:51 +08:00
|
|
|
ml := &Listener{
|
|
|
|
listener: l,
|
|
|
|
cache: cache.New(30 * time.Second),
|
|
|
|
}
|
2020-05-12 11:29:53 +08:00
|
|
|
go func() {
|
|
|
|
for {
|
2021-06-13 23:05:22 +08:00
|
|
|
c, err := ml.listener.Accept()
|
2020-05-12 11:29:53 +08:00
|
|
|
if err != nil {
|
|
|
|
if ml.closed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2021-06-13 17:23:10 +08:00
|
|
|
go handleConn(c, in, ml.cache)
|
2020-05-12 11:29:53 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return ml, nil
|
|
|
|
}
|
|
|
|
|
2021-06-13 17:23:10 +08:00
|
|
|
func (l *Listener) Close() {
|
2020-05-12 11:29:53 +08:00
|
|
|
l.closed = true
|
2021-06-13 23:05:22 +08:00
|
|
|
l.listener.Close()
|
2020-05-12 11:29:53 +08:00
|
|
|
}
|
|
|
|
|
2021-06-13 17:23:10 +08:00
|
|
|
func (l *Listener) Address() string {
|
2021-07-19 14:07:51 +08:00
|
|
|
return l.listener.Addr().String()
|
2020-05-12 11:29:53 +08:00
|
|
|
}
|
|
|
|
|
2021-06-13 17:23:10 +08:00
|
|
|
func handleConn(conn net.Conn, in chan<- C.ConnContext, cache *cache.Cache) {
|
2021-06-15 17:13:40 +08:00
|
|
|
bufConn := N.NewBufferedConn(conn)
|
2020-05-12 11:29:53 +08:00
|
|
|
head, err := bufConn.Peek(1)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-07-18 16:09:09 +08:00
|
|
|
switch head[0] {
|
|
|
|
case socks4.Version:
|
|
|
|
socks.HandleSocks4(bufConn, in)
|
|
|
|
case socks5.Version:
|
|
|
|
socks.HandleSocks5(bufConn, in)
|
|
|
|
default:
|
|
|
|
http.HandleConn(bufConn, in, cache)
|
2020-05-12 11:29:53 +08:00
|
|
|
}
|
|
|
|
}
|