blackhole.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Package blackhole is an outbound handler that blocks all connections.
  2. package blackhole
  3. import (
  4. "context"
  5. "time"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/common/session"
  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. outbounds := session.OutboundsFromContext(ctx)
  28. ob := outbounds[len(outbounds)-1]
  29. ob.Name = "blackhole"
  30. nBytes := h.response.WriteTo(link.Writer)
  31. if nBytes > 0 {
  32. // Sleep a little here to make sure the response is sent to client.
  33. time.Sleep(time.Second)
  34. }
  35. common.Interrupt(link.Writer)
  36. return nil
  37. }
  38. func init() {
  39. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  40. return New(ctx, config.(*Config))
  41. }))
  42. }