outbound.go 2.1 KB

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