blackhole.go 1.2 KB

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