Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion proxy/socks/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package socks

import (
"bufio"
"context"
"io"
"time"
Expand All @@ -19,6 +20,7 @@ import (
"github.com/xtls/xray-core/features"
"github.com/xtls/xray-core/features/policy"
"github.com/xtls/xray-core/features/routing"
"github.com/xtls/xray-core/proxy/http"
"github.com/xtls/xray-core/transport/internet/stat"
"github.com/xtls/xray-core/transport/internet/udp"
)
Expand All @@ -29,6 +31,7 @@ type Server struct {
policyManager policy.Manager
cone bool
udpFilter *UDPFilter
httpServer *http.Server
}

// NewServer creates a new Server object.
Expand All @@ -42,6 +45,12 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
if config.AuthType == AuthType_PASSWORD {
s.udpFilter = new(UDPFilter) // We only use this when auth is enabled
}
// Create http config and server
httpConfig := &http.ServerConfig{}
if config.AuthType == AuthType_PASSWORD {
httpConfig.Accounts = config.Accounts
}
s.httpServer, _ = http.NewServer(ctx, httpConfig)
return s, nil
}

Expand Down Expand Up @@ -75,9 +84,23 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con
Level: s.config.UserLevel,
}

var newConn readConn
if network == net.Network_TCP {
reader := bufio.NewReader(conn)
newConn = conBuff{
Connection: conn,
reader: reader,
}
firstbyte, _ := reader.Peek(1)
if firstbyte[0] != 5 && firstbyte[0] != 4 { // Check if socks5/4
errors.LogDebug(ctx, "Not socks request, try to parse as HTTP request")
return s.httpServer.Process(ctx, network, newConn.(stat.Connection), dispatcher)
}
}

switch network {
case net.Network_TCP:
return s.processTCP(ctx, conn, dispatcher)
return s.processTCP(ctx, newConn.(stat.Connection), dispatcher)
case net.Network_UDP:
return s.handleUDPPayload(ctx, conn, dispatcher)
default:
Expand Down Expand Up @@ -285,6 +308,20 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
}
}

// Used for read bytes from connection without consuming data
type readConn interface {
Read(p []byte) (n int, err error)
}

type conBuff struct {
stat.Connection
reader *bufio.Reader
}

func (c conBuff) Read(p []byte) (n int, err error) {
return c.reader.Read(p)
}

func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewServer(ctx, config.(*ServerConfig))
Expand Down