2018-06-13 17:00:58 +00:00
|
|
|
package http
|
2018-06-10 14:50:03 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
2019-06-27 09:04:25 +00:00
|
|
|
"time"
|
2018-06-10 14:50:03 +00:00
|
|
|
|
2019-06-27 09:04:25 +00:00
|
|
|
"github.com/Dreamacro/clash/common/cache"
|
2021-06-13 09:23:10 +00:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2018-06-10 14:50:03 +00:00
|
|
|
)
|
|
|
|
|
2021-06-13 09:23:10 +00:00
|
|
|
type Listener struct {
|
2021-06-13 15:05:22 +00:00
|
|
|
listener net.Listener
|
|
|
|
address string
|
|
|
|
closed bool
|
2018-11-22 03:54:01 +00:00
|
|
|
}
|
|
|
|
|
2021-06-13 09:23:10 +00:00
|
|
|
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
|
2021-06-15 09:13:40 +00:00
|
|
|
return NewWithAuthenticate(addr, in, true)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWithAuthenticate(addr string, in chan<- C.ConnContext, authenticate bool) (*Listener, error) {
|
2018-07-15 14:23:20 +00:00
|
|
|
l, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
2018-11-22 03:54:01 +00:00
|
|
|
return nil, err
|
2018-07-15 14:23:20 +00:00
|
|
|
}
|
2021-06-15 09:13:40 +00:00
|
|
|
|
|
|
|
var c *cache.Cache
|
|
|
|
if authenticate {
|
|
|
|
c = cache.New(time.Second * 30)
|
|
|
|
}
|
|
|
|
|
|
|
|
hl := &Listener{
|
|
|
|
listener: l,
|
|
|
|
address: addr,
|
|
|
|
}
|
2018-07-15 14:23:20 +00:00
|
|
|
go func() {
|
2018-08-11 14:51:30 +00:00
|
|
|
for {
|
2021-06-15 09:13:40 +00:00
|
|
|
conn, err := hl.listener.Accept()
|
2018-08-11 14:51:30 +00:00
|
|
|
if err != nil {
|
2018-11-22 03:54:01 +00:00
|
|
|
if hl.closed {
|
2018-08-11 14:51:30 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2021-06-15 09:13:40 +00:00
|
|
|
go HandleConn(conn, in, c)
|
2018-08-11 14:51:30 +00:00
|
|
|
}
|
2018-07-15 14:23:20 +00:00
|
|
|
}()
|
|
|
|
|
2018-11-22 03:54:01 +00:00
|
|
|
return hl, nil
|
|
|
|
}
|
|
|
|
|
2021-06-13 09:23:10 +00:00
|
|
|
func (l *Listener) Close() {
|
2018-11-22 03:54:01 +00:00
|
|
|
l.closed = true
|
2021-06-13 15:05:22 +00:00
|
|
|
l.listener.Close()
|
2018-11-22 03:54:01 +00:00
|
|
|
}
|
2018-07-15 14:23:20 +00:00
|
|
|
|
2021-06-13 09:23:10 +00:00
|
|
|
func (l *Listener) Address() string {
|
2018-11-22 03:54:01 +00:00
|
|
|
return l.address
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|