blackhole.go 1.3 KB

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