http proxy

This commit is contained in:
Quentin McGaw
2023-08-23 09:30:51 +00:00
parent 8567522594
commit 5f355fabbe
4 changed files with 81 additions and 55 deletions

1
go.mod
View File

@@ -10,6 +10,7 @@ require (
github.com/klauspost/pgzip v1.2.6 github.com/klauspost/pgzip v1.2.6
github.com/pelletier/go-toml/v2 v2.2.2 github.com/pelletier/go-toml/v2 v2.2.2
github.com/qdm12/dns/v2 v2.0.0-rc6 github.com/qdm12/dns/v2 v2.0.0-rc6
github.com/qdm12/goservices v0.1.0
github.com/qdm12/gosettings v0.4.2 github.com/qdm12/gosettings v0.4.2
github.com/qdm12/goshutdown v0.3.0 github.com/qdm12/goshutdown v0.3.0
github.com/qdm12/gosplash v0.2.0 github.com/qdm12/gosplash v0.2.0

2
go.sum
View File

@@ -62,6 +62,8 @@ github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+Pymzi
github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM=
github.com/qdm12/dns/v2 v2.0.0-rc6 h1:h5KpuqZ3IMoSbz2a0OkHzIVc9/jk2vuIm9RoKJuaI78= github.com/qdm12/dns/v2 v2.0.0-rc6 h1:h5KpuqZ3IMoSbz2a0OkHzIVc9/jk2vuIm9RoKJuaI78=
github.com/qdm12/dns/v2 v2.0.0-rc6/go.mod h1:Oh34IJIG55BgHoACOf+cgZCgDiFuiJZ6r6gQW58FN+k= github.com/qdm12/dns/v2 v2.0.0-rc6/go.mod h1:Oh34IJIG55BgHoACOf+cgZCgDiFuiJZ6r6gQW58FN+k=
github.com/qdm12/goservices v0.1.0 h1:9sODefm/yuIGS7ynCkEnNlMTAYn9GzPhtcK4F69JWvc=
github.com/qdm12/goservices v0.1.0/go.mod h1:/JOFsAnHFiSjyoXxa5FlfX903h20K5u/3rLzCjYVMck=
github.com/qdm12/gosettings v0.4.2 h1:Gb39NScPr7OQV+oy0o1OD7A121udITDJuUGa7ljDF58= github.com/qdm12/gosettings v0.4.2 h1:Gb39NScPr7OQV+oy0o1OD7A121udITDJuUGa7ljDF58=
github.com/qdm12/gosettings v0.4.2/go.mod h1:CPrt2YC4UsURTrslmhxocVhMCW03lIrqdH2hzIf5prg= github.com/qdm12/gosettings v0.4.2/go.mod h1:CPrt2YC4UsURTrslmhxocVhMCW03lIrqdH2hzIf5prg=
github.com/qdm12/goshutdown v0.3.0 h1:pqBpJkdwlZlfTEx4QHtS8u8CXx6pG0fVo6S1N0MpSEM= github.com/qdm12/goshutdown v0.3.0 h1:pqBpJkdwlZlfTEx4QHtS8u8CXx6pG0fVo6S1N0MpSEM=

View File

@@ -18,15 +18,22 @@ func (l *Loop) Run(ctx context.Context, done chan<- struct{}) {
} }
for ctx.Err() == nil { for ctx.Err() == nil {
runCtx, runCancel := context.WithCancel(ctx)
settings := l.state.GetSettings() settings := l.state.GetSettings()
server := New(runCtx, settings.ListeningAddress, l.logger, server, err := New(settings.ListeningAddress, l.logger,
*settings.Stealth, *settings.Log, *settings.User, *settings.Stealth, *settings.Log, *settings.User,
*settings.Password, settings.ReadHeaderTimeout, settings.ReadTimeout) *settings.Password, settings.ReadHeaderTimeout, settings.ReadTimeout)
if err != nil {
l.statusManager.SetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
}
errorCh := make(chan error) errorCh, err := server.Start(ctx)
go server.Run(runCtx, errorCh) if err != nil {
l.statusManager.SetStatus(constants.Crashed)
l.logAndWait(ctx, err)
continue
}
// TODO stable timer, check Shadowsocks // TODO stable timer, check Shadowsocks
if l.userTrigger { if l.userTrigger {
@@ -41,31 +48,23 @@ func (l *Loop) Run(ctx context.Context, done chan<- struct{}) {
for stayHere { for stayHere {
select { select {
case <-ctx.Done(): case <-ctx.Done():
runCancel() _ = server.Stop()
<-errorCh
close(errorCh)
return return
case <-l.start: case <-l.start:
l.userTrigger = true l.userTrigger = true
l.logger.Info("starting") l.logger.Info("starting")
runCancel() _ = server.Stop()
<-errorCh
close(errorCh)
stayHere = false stayHere = false
case <-l.stop: case <-l.stop:
l.userTrigger = true l.userTrigger = true
l.logger.Info("stopping") l.logger.Info("stopping")
runCancel() _ = server.Stop()
<-errorCh
// Do not close errorCh or this for loop won't work
l.stopped <- struct{}{} l.stopped <- struct{}{}
case err := <-errorCh: case err := <-errorCh:
close(errorCh)
l.statusManager.SetStatus(constants.Crashed) l.statusManager.SetStatus(constants.Crashed)
l.logAndWait(ctx, err) l.logAndWait(ctx, err)
stayHere = false stayHere = false
} }
} }
runCancel() // repetition for linter only
} }
} }

View File

@@ -2,57 +2,81 @@ package httpproxy
import ( import (
"context" "context"
"net/http" "fmt"
"sync" "sync"
"time" "time"
"github.com/qdm12/goservices"
"github.com/qdm12/goservices/httpserver"
) )
type Server struct { type Server struct {
address string httpServer *httpserver.Server
handler http.Handler handlerCtx context.Context //nolint:containedctx
logger infoErrorer handlerCancel context.CancelFunc
internalWG *sync.WaitGroup handlerWg *sync.WaitGroup
readHeaderTimeout time.Duration
readTimeout time.Duration // Server settings
httpServerSettings httpserver.Settings
// Handler settings
logger Logger
stealth bool
verbose bool
username string
password string
} }
func New(ctx context.Context, address string, logger Logger, func ptrTo[T any](x T) *T { return &x }
func New(address string, logger Logger,
stealth, verbose bool, username, password string, stealth, verbose bool, username, password string,
readHeaderTimeout, readTimeout time.Duration, readHeaderTimeout, readTimeout time.Duration,
) *Server { ) (server *Server, err error) {
wg := &sync.WaitGroup{}
return &Server{ return &Server{
address: address, handlerWg: &sync.WaitGroup{},
handler: newHandler(ctx, wg, logger, stealth, verbose, username, password), httpServerSettings: httpserver.Settings{
logger: logger, // Handler is set when calling Start and reset when Stop is called
internalWG: wg, Handler: nil,
readHeaderTimeout: readHeaderTimeout, Name: ptrTo("proxy"),
readTimeout: readTimeout, Address: ptrTo(address),
} ReadTimeout: readTimeout,
ReadHeaderTimeout: readHeaderTimeout,
Logger: logger,
},
logger: logger,
stealth: stealth,
verbose: verbose,
username: username,
password: password,
}, nil
} }
func (s *Server) Run(ctx context.Context, errorCh chan<- error) { func (s *Server) Start(ctx context.Context) (
server := http.Server{ runError <-chan error, err error,
Addr: s.address, ) {
Handler: s.handler, if s.httpServer != nil {
ReadHeaderTimeout: s.readHeaderTimeout, return nil, fmt.Errorf("%w", goservices.ErrAlreadyStarted)
ReadTimeout: s.readTimeout,
} }
go func() {
<-ctx.Done() s.handlerCtx, s.handlerCancel = context.WithCancel(context.Background())
const shutdownGraceDuration = 100 * time.Millisecond s.httpServerSettings.Handler = newHandler(s.handlerCtx, s.handlerWg,
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownGraceDuration) s.logger, s.stealth, s.verbose, s.username, s.password)
defer cancel() s.httpServer, err = httpserver.New(s.httpServerSettings)
if err := server.Shutdown(shutdownCtx); err != nil { if err != nil {
s.logger.Error("failed shutting down: " + err.Error()) return nil, fmt.Errorf("creating http server: %w", err)
}
}()
s.logger.Info("listening on " + s.address)
err := server.ListenAndServe()
s.internalWG.Wait()
if err != nil && ctx.Err() == nil {
errorCh <- err
} else {
errorCh <- nil
} }
return s.httpServer.Start(ctx)
}
func (s *Server) Stop() (err error) {
if s.httpServer == nil {
return fmt.Errorf("%w", goservices.ErrAlreadyStopped)
}
s.handlerCancel()
err = s.httpServer.Stop()
s.handlerWg.Wait()
s.httpServer = nil // signal the server is down
return err
} }