Fix: goroutine leak while closing proxy (#43)

* Fix: goroutine leak while closing proxy

* Chore: improve proxy architecture

* Fix: stack overflow
This commit is contained in:
beyondkmp
2018-11-22 11:54:01 +08:00
committed by Dreamacro
parent 05bf4d44ab
commit 970643b144
4 changed files with 79 additions and 74 deletions

View File

@ -13,21 +13,25 @@ var (
tun = tunnel.Instance()
)
func NewRedirProxy(addr string) (chan<- struct{}, <-chan struct{}, error) {
type redirListener struct {
net.Listener
address string
closed bool
}
func NewRedirProxy(addr string) (*redirListener, error) {
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, nil, err
return nil, err
}
done := make(chan struct{})
closed := make(chan struct{})
rl := &redirListener{l, addr, false}
go func() {
log.Infof("Redir proxy listening at: %s", addr)
for {
c, err := l.Accept()
if err != nil {
if _, open := <-done; !open {
if rl.closed {
break
}
continue
@ -36,13 +40,16 @@ func NewRedirProxy(addr string) (chan<- struct{}, <-chan struct{}, error) {
}
}()
go func() {
<-done
l.Close()
closed <- struct{}{}
}()
return rl, nil
}
return done, closed, nil
func (l *redirListener) Close() {
l.closed = true
l.Listener.Close()
}
func (l *redirListener) Address() string {
return l.address
}
func handleRedir(conn net.Conn) {