github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/proxy/blackhole/blackhole.go (about) 1 // Package blackhole is an outbound handler that blocks all connections. 2 package blackhole 3 4 //go:generate go run github.com/xmplusdev/xmcore/common/errors/errorgen 5 6 import ( 7 "context" 8 "time" 9 10 "github.com/xmplusdev/xmcore/common" 11 "github.com/xmplusdev/xmcore/common/session" 12 "github.com/xmplusdev/xmcore/transport" 13 "github.com/xmplusdev/xmcore/transport/internet" 14 ) 15 16 // Handler is an outbound connection that silently swallow the entire payload. 17 type Handler struct { 18 response ResponseConfig 19 } 20 21 // New creates a new blackhole handler. 22 func New(ctx context.Context, config *Config) (*Handler, error) { 23 response, err := config.GetInternalResponse() 24 if err != nil { 25 return nil, err 26 } 27 return &Handler{ 28 response: response, 29 }, nil 30 } 31 32 // Process implements OutboundHandler.Dispatch(). 33 func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { 34 outbound := session.OutboundFromContext(ctx) 35 if outbound != nil { 36 outbound.Name = "blackhole" 37 } 38 39 nBytes := h.response.WriteTo(link.Writer) 40 if nBytes > 0 { 41 // Sleep a little here to make sure the response is sent to client. 42 time.Sleep(time.Second) 43 } 44 common.Interrupt(link.Writer) 45 return nil 46 } 47 48 func init() { 49 common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 50 return New(ctx, config.(*Config)) 51 })) 52 }