http.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package outbound
  2. import (
  3. "context"
  4. "net"
  5. "os"
  6. "github.com/sagernet/sing-box/adapter"
  7. "github.com/sagernet/sing-box/common/dialer"
  8. "github.com/sagernet/sing-box/common/tls"
  9. C "github.com/sagernet/sing-box/constant"
  10. "github.com/sagernet/sing-box/log"
  11. "github.com/sagernet/sing-box/option"
  12. "github.com/sagernet/sing/common"
  13. M "github.com/sagernet/sing/common/metadata"
  14. N "github.com/sagernet/sing/common/network"
  15. "github.com/sagernet/sing/protocol/http"
  16. )
  17. var _ adapter.Outbound = (*HTTP)(nil)
  18. type HTTP struct {
  19. myOutboundAdapter
  20. client *http.Client
  21. }
  22. func NewHTTP(router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPOutboundOptions) (*HTTP, error) {
  23. detour, err := tls.NewDialerFromOptions(router, dialer.New(router, options.DialerOptions), options.Server, common.PtrValueOrDefault(options.TLS))
  24. if err != nil {
  25. return nil, err
  26. }
  27. return &HTTP{
  28. myOutboundAdapter{
  29. protocol: C.TypeHTTP,
  30. network: []string{N.NetworkTCP},
  31. router: router,
  32. logger: logger,
  33. tag: tag,
  34. },
  35. http.NewClient(detour, options.ServerOptions.Build(), options.Username, options.Password),
  36. }, nil
  37. }
  38. func (h *HTTP) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  39. ctx, metadata := adapter.AppendContext(ctx)
  40. metadata.Outbound = h.tag
  41. metadata.Destination = destination
  42. h.logger.InfoContext(ctx, "outbound connection to ", destination)
  43. return h.client.DialContext(ctx, network, destination)
  44. }
  45. func (h *HTTP) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  46. return nil, os.ErrInvalid
  47. }
  48. func (h *HTTP) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  49. return NewConnection(ctx, h, conn, metadata)
  50. }
  51. func (h *HTTP) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  52. return os.ErrInvalid
  53. }