github.com/sagernet/sing-box@v1.9.0-rc.20/outbound/http.go (about)

     1  package outbound
     2  
     3  import (
     4  	"context"
     5  	"net"
     6  	"os"
     7  
     8  	"github.com/sagernet/sing-box/adapter"
     9  	"github.com/sagernet/sing-box/common/dialer"
    10  	"github.com/sagernet/sing-box/common/tls"
    11  	C "github.com/sagernet/sing-box/constant"
    12  	"github.com/sagernet/sing-box/log"
    13  	"github.com/sagernet/sing-box/option"
    14  	"github.com/sagernet/sing/common"
    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  
    20  var _ adapter.Outbound = (*HTTP)(nil)
    21  
    22  type HTTP struct {
    23  	myOutboundAdapter
    24  	client *sHTTP.Client
    25  }
    26  
    27  func NewHTTP(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPOutboundOptions) (*HTTP, error) {
    28  	outboundDialer, err := dialer.New(router, options.DialerOptions)
    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 &HTTP{
    37  		myOutboundAdapter{
    38  			protocol:     C.TypeHTTP,
    39  			network:      []string{N.NetworkTCP},
    40  			router:       router,
    41  			logger:       logger,
    42  			tag:          tag,
    43  			dependencies: withDialerDependency(options.DialerOptions),
    44  		},
    45  		sHTTP.NewClient(sHTTP.Options{
    46  			Dialer:   detour,
    47  			Server:   options.ServerOptions.Build(),
    48  			Username: options.Username,
    49  			Password: options.Password,
    50  			Path:     options.Path,
    51  			Headers:  options.Headers.Build(),
    52  		}),
    53  	}, nil
    54  }
    55  
    56  func (h *HTTP) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
    57  	ctx, metadata := adapter.AppendContext(ctx)
    58  	metadata.Outbound = h.tag
    59  	metadata.Destination = destination
    60  	h.logger.InfoContext(ctx, "outbound connection to ", destination)
    61  	return h.client.DialContext(ctx, network, destination)
    62  }
    63  
    64  func (h *HTTP) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
    65  	return nil, os.ErrInvalid
    66  }
    67  
    68  func (h *HTTP) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
    69  	return NewConnection(ctx, h, conn, metadata)
    70  }
    71  
    72  func (h *HTTP) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
    73  	return os.ErrInvalid
    74  }