@@ -2,8 +2,8 @@ package proxy
22
33import (
44 "bufio"
5- "context"
65 "crypto/tls"
6+ "errors"
77 "fmt"
88 "io"
99 "log/slog"
@@ -12,6 +12,7 @@ import (
1212 "net/url"
1313 "strings"
1414 "sync"
15+ "sync/atomic"
1516
1617 "github.com/coder/boundary/audit"
1718 "github.com/coder/boundary/rules"
@@ -24,6 +25,7 @@ type Server struct {
2425 logger * slog.Logger
2526 tlsConfig * tls.Config
2627 httpPort int
28+ started atomic.Bool
2729
2830 listener net.Listener
2931}
@@ -49,7 +51,12 @@ func NewProxyServer(config Config) *Server {
4951}
5052
5153// Start starts the HTTP proxy server with TLS termination capability
52- func (p * Server ) Start (ctx context.Context ) error {
54+ func (p * Server ) Start () error {
55+ if p .isStarted () {
56+ return nil
57+ }
58+ p .started .Store (true )
59+
5360 // Start HTTP server with custom listener for TLS detection
5461 go func () {
5562 p .logger .Info ("Starting HTTP proxy with TLS termination" , "port" , p .httpPort )
@@ -62,46 +69,49 @@ func (p *Server) Start(ctx context.Context) error {
6269
6370 for {
6471 conn , err := p .listener .Accept ()
72+ if err != nil && errors .Is (err , net .ErrClosed ) && p .isStopped () {
73+ return
74+ }
6575 if err != nil {
66- select {
67- case <- ctx .Done ():
68- err = p .listener .Close ()
69- if err != nil {
70- p .logger .Error ("Failed to close listener" , "error" , err )
71- }
72- return
73- default :
74- p .logger .Error ("Failed to accept connection" , "error" , err )
75- continue
76- }
76+ p .logger .Error ("Failed to accept connection" , "error" , err )
77+ continue
7778 }
7879
7980 // Handle connection with TLS detection
8081 go p .handleConnectionWithTLSDetection (conn )
8182 }
8283 }()
8384
84- // Wait for context cancellation
85- <- ctx .Done ()
86- return p .Stop ()
85+ return nil
8786}
8887
8988// Stops proxy server
9089func (p * Server ) Stop () error {
91- if p .listener == nil {
90+ if p .isStopped () {
9291 return nil
9392 }
93+ p .started .Store (false )
94+
95+ if p .listener == nil {
96+ return errors .New ("listener is nil; server was not started" )
97+ }
9498
9599 err := p .listener .Close ()
96100 if err != nil {
97101 p .logger .Error ("Failed to close listener" , "error" , err )
98102 }
99103
100- fmt .Printf ("STOP is finished\n " )
101-
102104 return nil
103105}
104106
107+ func (p * Server ) isStarted () bool {
108+ return p .started .Load ()
109+ }
110+
111+ func (p * Server ) isStopped () bool {
112+ return ! p .started .Load ()
113+ }
114+
105115// handleHTTP handles regular HTTP requests and CONNECT tunneling
106116func (p * Server ) handleHTTP (w http.ResponseWriter , r * http.Request ) {
107117 p .logger .Debug ("handleHTTP called" , "method" , r .Method , "url" , r .URL .String (), "host" , r .Host )
0 commit comments