clash/listener/http/server.go

76 lines
1.5 KiB
Go
Raw Normal View History

2018-06-13 17:00:58 +00:00
package http
2018-06-10 14:50:03 +00:00
import (
"net"
2022-11-16 02:43:16 +00:00
"github.com/Dreamacro/clash/adapter/inbound"
"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 {
2022-12-04 14:08:20 +00:00
listener net.Listener
addr string
closed bool
name string
specialRules string
}
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) {
return NewWithAuthenticate(addr, "DEFAULT-HTTP", "", in, true)
2021-06-15 09:13:40 +00:00
}
2022-12-04 14:08:20 +00:00
func NewWithInfos(addr, name, specialRules string, in chan<- C.ConnContext) (*Listener, error) {
return NewWithAuthenticate(addr, name, specialRules, in, true)
2022-12-04 05:37:14 +00:00
}
2022-12-04 14:08:20 +00:00
func NewWithAuthenticate(addr, name, specialRules string, in chan<- C.ConnContext, authenticate bool) (*Listener, error) {
2022-11-16 02:43:16 +00:00
l, err := inbound.Listen("tcp", addr)
2022-07-22 07:16:09 +00:00
2018-07-15 14:23:20 +00:00
if err != nil {
return nil, err
2018-07-15 14:23:20 +00:00
}
2021-06-15 09:13:40 +00:00
var c *cache.LruCache[string, bool]
2021-06-15 09:13:40 +00:00
if authenticate {
c = cache.New[string, bool](cache.WithAge[string, bool](30))
2021-06-15 09:13:40 +00:00
}
hl := &Listener{
2022-12-04 14:08:20 +00:00
listener: l,
name: name,
specialRules: specialRules,
addr: addr,
2021-06-15 09:13:40 +00:00
}
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 {
if hl.closed {
2018-08-11 14:51:30 +00:00
break
}
continue
}
2022-12-04 14:08:20 +00:00
go HandleConn(hl.name, hl.specialRules, conn, in, c)
2018-08-11 14:51:30 +00:00
}
2018-07-15 14:23:20 +00:00
}()
return hl, nil
}