github.com/xtls/xray-core@v1.8.12-0.20240518155711-3168d27b0bdb/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/xtls/xray-core/common/errors/errorgen 5 6 import ( 7 "context" 8 "time" 9 10 "github.com/xtls/xray-core/common" 11 "github.com/xtls/xray-core/common/session" 12 "github.com/xtls/xray-core/transport" 13 "github.com/xtls/xray-core/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 outbounds := session.OutboundsFromContext(ctx) 35 ob := outbounds[len(outbounds) - 1] 36 ob.Name = "blackhole" 37 38 nBytes := h.response.WriteTo(link.Writer) 39 if nBytes > 0 { 40 // Sleep a little here to make sure the response is sent to client. 41 time.Sleep(time.Second) 42 } 43 common.Interrupt(link.Writer) 44 return nil 45 } 46 47 func init() { 48 common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 49 return New(ctx, config.(*Config)) 50 })) 51 }