Skip to content

Commit

Permalink
[~] fix channel race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
Noooste committed Jan 12, 2024
1 parent 3ad1c60 commit 3f2131e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
18 changes: 8 additions & 10 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ func (c *Conn) Close() {

func (s *Session) getProxyConn(conn *Conn, host string) (err error) {
ctx, cancel := context.WithCancel(s.ctx)

s.ProxyDialer.ForceHTTP2 = s.H2Proxy
s.ProxyDialer.tr = s.HTTP2Transport
s.ProxyDialer.Dialer.Timeout = conn.TimeOut
Expand All @@ -225,21 +226,17 @@ func (s *Session) getProxyConn(conn *Conn, host string) (err error) {
connChan := make(chan net.Conn, 1)
errChan := make(chan error, 1)

defer close(connChan)
defer close(errChan)

go func() {
defer close(connChan)
defer close(errChan)

proxyConn, dialErr := s.ProxyDialer.DialContext(ctx, "tcp", host)
select {
case <-ctx.Done():
return
default:
if dialErr != nil {
errChan <- dialErr
connChan <- nil
}
errChan <- dialErr
connChan <- proxyConn
errChan <- nil
}
}()

Expand All @@ -249,10 +246,11 @@ func (s *Session) getProxyConn(conn *Conn, host string) (err error) {
return errors.New("proxy connection timeout")

case c := <-connChan:
if c == nil {
if err = <-errChan; err != nil {
cancel()
return <-errChan
return err
}

conn.Conn = c
conn.cancel = cancel
}
Expand Down
14 changes: 14 additions & 0 deletions tests/connection_proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,17 @@ func TestBadProxy(t *testing.T) {
}

}

func TestRace(t *testing.T) {
for i := 0; i < 100; i++ {
go func() {
session := azuretls.NewSession()
session.SetProxy("http://10.1.2.3")
session.SetTimeout(time.Second * 1)
for {
session.Get("https://api.ipify.org")
}
}()
}
time.Sleep(time.Second * 999)
}

0 comments on commit 3f2131e

Please sign in to comment.