http.go 1.8 KB

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