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