github.com/sagernet/sing-box@v1.2.7/inbound/mixed.go (about)

     1  package inbound
     2  
     3  import (
     4  	std_bufio "bufio"
     5  	"context"
     6  	"net"
     7  	"os"
     8  
     9  	"github.com/sagernet/sing-box/adapter"
    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/auth"
    14  	"github.com/sagernet/sing/common/buf"
    15  	"github.com/sagernet/sing/common/bufio"
    16  	N "github.com/sagernet/sing/common/network"
    17  	"github.com/sagernet/sing/common/rw"
    18  	"github.com/sagernet/sing/protocol/http"
    19  	"github.com/sagernet/sing/protocol/socks"
    20  	"github.com/sagernet/sing/protocol/socks/socks4"
    21  	"github.com/sagernet/sing/protocol/socks/socks5"
    22  )
    23  
    24  var (
    25  	_ adapter.Inbound           = (*Mixed)(nil)
    26  	_ adapter.InjectableInbound = (*Mixed)(nil)
    27  )
    28  
    29  type Mixed struct {
    30  	myInboundAdapter
    31  	authenticator auth.Authenticator
    32  }
    33  
    34  func NewMixed(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPMixedInboundOptions) *Mixed {
    35  	inbound := &Mixed{
    36  		myInboundAdapter{
    37  			protocol:       C.TypeMixed,
    38  			network:        []string{N.NetworkTCP},
    39  			ctx:            ctx,
    40  			router:         router,
    41  			logger:         logger,
    42  			tag:            tag,
    43  			listenOptions:  options.ListenOptions,
    44  			setSystemProxy: options.SetSystemProxy,
    45  		},
    46  		auth.NewAuthenticator(options.Users),
    47  	}
    48  	inbound.connHandler = inbound
    49  	return inbound
    50  }
    51  
    52  func (h *Mixed) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
    53  	headerType, err := rw.ReadByte(conn)
    54  	if err != nil {
    55  		return err
    56  	}
    57  	switch headerType {
    58  	case socks4.Version, socks5.Version:
    59  		return socks.HandleConnection0(ctx, conn, headerType, h.authenticator, h.upstreamUserHandler(metadata), adapter.UpstreamMetadata(metadata))
    60  	}
    61  	reader := std_bufio.NewReader(bufio.NewCachedReader(conn, buf.As([]byte{headerType})))
    62  	return http.HandleConnection(ctx, conn, reader, h.authenticator, h.upstreamUserHandler(metadata), adapter.UpstreamMetadata(metadata))
    63  }
    64  
    65  func (h *Mixed) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
    66  	return os.ErrInvalid
    67  }