2020-11-25 13:01:53 +02:00
|
|
|
package trojan
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"io"
|
|
|
|
"strconv"
|
2021-01-18 09:41:00 +02:00
|
|
|
"strings"
|
2023-07-20 02:16:29 +03:00
|
|
|
"sync"
|
2020-11-25 13:01:53 +02:00
|
|
|
"time"
|
|
|
|
|
2020-12-04 03:36:16 +02:00
|
|
|
"github.com/xtls/xray-core/common"
|
|
|
|
"github.com/xtls/xray-core/common/buf"
|
|
|
|
"github.com/xtls/xray-core/common/errors"
|
|
|
|
"github.com/xtls/xray-core/common/log"
|
|
|
|
"github.com/xtls/xray-core/common/net"
|
|
|
|
"github.com/xtls/xray-core/common/protocol"
|
|
|
|
udp_proto "github.com/xtls/xray-core/common/protocol/udp"
|
|
|
|
"github.com/xtls/xray-core/common/retry"
|
|
|
|
"github.com/xtls/xray-core/common/session"
|
|
|
|
"github.com/xtls/xray-core/common/signal"
|
|
|
|
"github.com/xtls/xray-core/common/task"
|
2021-09-24 08:21:03 +03:00
|
|
|
"github.com/xtls/xray-core/core"
|
2020-12-04 03:36:16 +02:00
|
|
|
"github.com/xtls/xray-core/features/policy"
|
|
|
|
"github.com/xtls/xray-core/features/routing"
|
2023-02-15 18:07:12 +02:00
|
|
|
"github.com/xtls/xray-core/transport/internet/reality"
|
2021-12-15 02:28:47 +02:00
|
|
|
"github.com/xtls/xray-core/transport/internet/stat"
|
2021-09-24 08:21:03 +03:00
|
|
|
"github.com/xtls/xray-core/transport/internet/tls"
|
2020-12-04 03:36:16 +02:00
|
|
|
"github.com/xtls/xray-core/transport/internet/udp"
|
2020-11-25 13:01:53 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
|
|
|
|
return NewServer(ctx, config.(*ServerConfig))
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Server is an inbound connection handler that handles messages in trojan protocol.
|
|
|
|
type Server struct {
|
2023-07-20 02:16:29 +03:00
|
|
|
sync.Mutex
|
|
|
|
|
2020-11-25 13:01:53 +02:00
|
|
|
policyManager policy.Manager
|
|
|
|
validator *Validator
|
2021-01-18 09:41:00 +02:00
|
|
|
fallbacks map[string]map[string]map[string]*Fallback // or nil
|
2021-01-10 09:50:21 +02:00
|
|
|
cone bool
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewServer creates a new trojan inbound handler.
|
|
|
|
func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
|
|
|
|
validator := new(Validator)
|
|
|
|
for _, user := range config.Users {
|
|
|
|
u, err := user.ToMemoryUser()
|
|
|
|
if err != nil {
|
|
|
|
return nil, newError("failed to get trojan user").Base(err).AtError()
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := validator.Add(u); err != nil {
|
|
|
|
return nil, newError("failed to add user").Base(err).AtError()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
v := core.MustFromContext(ctx)
|
|
|
|
server := &Server{
|
|
|
|
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
|
|
|
validator: validator,
|
2021-01-10 09:50:21 +02:00
|
|
|
cone: ctx.Value("cone").(bool),
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if config.Fallbacks != nil {
|
2021-01-18 09:41:00 +02:00
|
|
|
server.fallbacks = make(map[string]map[string]map[string]*Fallback)
|
2020-11-25 13:01:53 +02:00
|
|
|
for _, fb := range config.Fallbacks {
|
2021-01-18 09:41:00 +02:00
|
|
|
if server.fallbacks[fb.Name] == nil {
|
|
|
|
server.fallbacks[fb.Name] = make(map[string]map[string]*Fallback)
|
|
|
|
}
|
|
|
|
if server.fallbacks[fb.Name][fb.Alpn] == nil {
|
|
|
|
server.fallbacks[fb.Name][fb.Alpn] = make(map[string]*Fallback)
|
|
|
|
}
|
|
|
|
server.fallbacks[fb.Name][fb.Alpn][fb.Path] = fb
|
|
|
|
}
|
|
|
|
if server.fallbacks[""] != nil {
|
|
|
|
for name, apfb := range server.fallbacks {
|
|
|
|
if name != "" {
|
|
|
|
for alpn := range server.fallbacks[""] {
|
|
|
|
if apfb[alpn] == nil {
|
|
|
|
apfb[alpn] = make(map[string]*Fallback)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, apfb := range server.fallbacks {
|
|
|
|
if apfb[""] != nil {
|
|
|
|
for alpn, pfb := range apfb {
|
|
|
|
if alpn != "" { // && alpn != "h2" {
|
|
|
|
for path, fb := range apfb[""] {
|
|
|
|
if pfb[path] == nil {
|
|
|
|
pfb[path] = fb
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if server.fallbacks[""] != nil {
|
2021-01-18 09:41:00 +02:00
|
|
|
for name, apfb := range server.fallbacks {
|
|
|
|
if name != "" {
|
|
|
|
for alpn, pfb := range server.fallbacks[""] {
|
|
|
|
for path, fb := range pfb {
|
|
|
|
if apfb[alpn][path] == nil {
|
|
|
|
apfb[alpn][path] = fb
|
|
|
|
}
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return server, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddUser implements proxy.UserManager.AddUser().
|
|
|
|
func (s *Server) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
|
|
|
|
return s.validator.Add(u)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveUser implements proxy.UserManager.RemoveUser().
|
|
|
|
func (s *Server) RemoveUser(ctx context.Context, e string) error {
|
|
|
|
return s.validator.Del(e)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Network implements proxy.Inbound.Network().
|
|
|
|
func (s *Server) Network() []net.Network {
|
|
|
|
return []net.Network{net.Network_TCP, net.Network_UNIX}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Process implements proxy.Inbound.Process().
|
2023-07-01 00:28:36 +03:00
|
|
|
func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher, usrIpRstrct *map[session.ID]*stat.UserIpRestriction, connIp *stat.UserIpRestriction) error {
|
2020-11-25 13:01:53 +02:00
|
|
|
sid := session.ExportIDToError(ctx)
|
|
|
|
|
|
|
|
iConn := conn
|
2021-09-20 15:11:21 +03:00
|
|
|
statConn, ok := iConn.(*stat.CounterConnection)
|
2020-11-25 13:01:53 +02:00
|
|
|
if ok {
|
|
|
|
iConn = statConn.Connection
|
|
|
|
}
|
|
|
|
|
|
|
|
sessionPolicy := s.policyManager.ForLevel(0)
|
|
|
|
if err := conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
|
|
|
|
return newError("unable to set read deadline").Base(err).AtWarning()
|
|
|
|
}
|
|
|
|
|
2023-01-17 05:18:58 +02:00
|
|
|
first := buf.FromBytes(make([]byte, buf.Size))
|
|
|
|
first.Clear()
|
2020-11-25 13:01:53 +02:00
|
|
|
firstLen, err := first.ReadFrom(conn)
|
|
|
|
if err != nil {
|
|
|
|
return newError("failed to read first request").Base(err)
|
|
|
|
}
|
|
|
|
newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid)
|
|
|
|
|
|
|
|
bufferedReader := &buf.BufferedReader{
|
|
|
|
Reader: buf.NewReader(conn),
|
|
|
|
Buffer: buf.MultiBuffer{first},
|
|
|
|
}
|
|
|
|
|
|
|
|
var user *protocol.MemoryUser
|
|
|
|
|
2021-01-18 09:41:00 +02:00
|
|
|
napfb := s.fallbacks
|
|
|
|
isfb := napfb != nil
|
2020-11-25 13:01:53 +02:00
|
|
|
|
|
|
|
shouldFallback := false
|
|
|
|
if firstLen < 58 || first.Byte(56) != '\r' {
|
|
|
|
// invalid protocol
|
|
|
|
err = newError("not trojan protocol")
|
|
|
|
log.Record(&log.AccessMessage{
|
|
|
|
From: conn.RemoteAddr(),
|
|
|
|
To: "",
|
|
|
|
Status: log.AccessRejected,
|
|
|
|
Reason: err,
|
|
|
|
})
|
|
|
|
|
|
|
|
shouldFallback = true
|
|
|
|
} else {
|
|
|
|
user = s.validator.Get(hexString(first.BytesTo(56)))
|
|
|
|
if user == nil {
|
|
|
|
// invalid user, let's fallback
|
|
|
|
err = newError("not a valid user")
|
|
|
|
log.Record(&log.AccessMessage{
|
|
|
|
From: conn.RemoteAddr(),
|
|
|
|
To: "",
|
|
|
|
Status: log.AccessRejected,
|
|
|
|
Reason: err,
|
|
|
|
})
|
|
|
|
|
|
|
|
shouldFallback = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if isfb && shouldFallback {
|
2021-01-18 09:41:00 +02:00
|
|
|
return s.fallback(ctx, sid, err, sessionPolicy, conn, iConn, napfb, first, firstLen, bufferedReader)
|
2020-11-25 13:01:53 +02:00
|
|
|
} else if shouldFallback {
|
|
|
|
return newError("invalid protocol or invalid user")
|
|
|
|
}
|
|
|
|
|
|
|
|
clientReader := &ConnReader{Reader: bufferedReader}
|
|
|
|
if err := clientReader.ParseHeader(); err != nil {
|
|
|
|
log.Record(&log.AccessMessage{
|
|
|
|
From: conn.RemoteAddr(),
|
|
|
|
To: "",
|
|
|
|
Status: log.AccessRejected,
|
|
|
|
Reason: err,
|
|
|
|
})
|
|
|
|
return newError("failed to create request from: ", conn.RemoteAddr()).Base(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
destination := clientReader.Target
|
|
|
|
if err := conn.SetReadDeadline(time.Time{}); err != nil {
|
|
|
|
return newError("unable to set read deadline").Base(err).AtWarning()
|
|
|
|
}
|
|
|
|
|
|
|
|
inbound := session.InboundFromContext(ctx)
|
|
|
|
if inbound == nil {
|
|
|
|
panic("no inbound metadata")
|
|
|
|
}
|
2023-04-06 13:21:35 +03:00
|
|
|
inbound.Name = "trojan"
|
2020-11-25 13:01:53 +02:00
|
|
|
inbound.User = user
|
|
|
|
sessionPolicy = s.policyManager.ForLevel(user.Level)
|
|
|
|
|
2023-07-01 00:28:36 +03:00
|
|
|
if (user.IpLimit > 0) {
|
|
|
|
addr := conn.RemoteAddr().(*net.TCPAddr)
|
|
|
|
|
|
|
|
uniqueIps := make(map[string]bool)
|
2023-07-20 02:16:29 +03:00
|
|
|
|
|
|
|
s.Lock()
|
2023-07-01 00:28:36 +03:00
|
|
|
// Iterate through the connections and find unique used IP addresses withing last 30 seconds.
|
|
|
|
for _, conn := range *usrIpRstrct {
|
|
|
|
if conn.User == user.Email && !conn.IpAddress.Equal(addr.IP) && ((time.Now().Unix() - conn.Time) < 30) {
|
|
|
|
uniqueIps[conn.IpAddress.String()] = true
|
|
|
|
}
|
|
|
|
}
|
2023-07-20 02:16:29 +03:00
|
|
|
s.Unlock()
|
2023-07-01 00:28:36 +03:00
|
|
|
|
|
|
|
if (len(uniqueIps) >= int(user.IpLimit)) {
|
|
|
|
return newError("User ", user, " has exceeded their allowed IPs.").AtWarning()
|
|
|
|
}
|
|
|
|
|
|
|
|
connIp.IpAddress = addr.IP
|
|
|
|
connIp.User = user.Email
|
|
|
|
connIp.Time = time.Now().Unix()
|
|
|
|
}
|
|
|
|
|
2020-11-25 13:01:53 +02:00
|
|
|
if destination.Network == net.Network_UDP { // handle udp request
|
|
|
|
return s.handleUDPPayload(ctx, &PacketReader{Reader: clientReader}, &PacketWriter{Writer: conn}, dispatcher)
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
|
|
|
|
From: conn.RemoteAddr(),
|
|
|
|
To: destination,
|
|
|
|
Status: log.AccessAccepted,
|
|
|
|
Reason: "",
|
|
|
|
Email: user.Email,
|
|
|
|
})
|
|
|
|
|
|
|
|
newError("received request for ", destination).WriteToLog(sid)
|
2023-03-04 12:39:26 +02:00
|
|
|
return s.handleConnection(ctx, sessionPolicy, destination, clientReader, buf.NewWriter(conn), dispatcher, iConn, statConn)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleUDPPayload(ctx context.Context, clientReader *PacketReader, clientWriter *PacketWriter, dispatcher routing.Dispatcher) error {
|
|
|
|
udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
|
2021-01-08 05:55:25 +02:00
|
|
|
udpPayload := packet.Payload
|
2021-01-08 08:00:51 +02:00
|
|
|
if udpPayload.UDP == nil {
|
|
|
|
udpPayload.UDP = &packet.Source
|
|
|
|
}
|
2021-01-11 11:30:57 +02:00
|
|
|
|
|
|
|
if err := clientWriter.WriteMultiBuffer(buf.MultiBuffer{udpPayload}); err != nil {
|
|
|
|
newError("failed to write response").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx))
|
|
|
|
}
|
2020-11-25 13:01:53 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
inbound := session.InboundFromContext(ctx)
|
|
|
|
user := inbound.User
|
|
|
|
|
2020-12-30 10:10:26 +02:00
|
|
|
var dest *net.Destination
|
2020-12-23 15:06:21 +02:00
|
|
|
|
2020-11-25 13:01:53 +02:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil
|
|
|
|
default:
|
2021-01-08 05:55:25 +02:00
|
|
|
mb, err := clientReader.ReadMultiBuffer()
|
2020-11-25 13:01:53 +02:00
|
|
|
if err != nil {
|
|
|
|
if errors.Cause(err) != io.EOF {
|
|
|
|
return newError("unexpected EOF").Base(err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-01-08 05:55:25 +02:00
|
|
|
mb2, b := buf.SplitFirst(mb)
|
2021-01-08 08:00:51 +02:00
|
|
|
if b == nil {
|
|
|
|
continue
|
|
|
|
}
|
2021-01-08 05:55:25 +02:00
|
|
|
destination := *b.UDP
|
2021-01-08 08:00:51 +02:00
|
|
|
|
|
|
|
currentPacketCtx := ctx
|
|
|
|
if inbound.Source.IsValid() {
|
|
|
|
currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
|
|
|
|
From: inbound.Source,
|
|
|
|
To: destination,
|
|
|
|
Status: log.AccessAccepted,
|
|
|
|
Reason: "",
|
|
|
|
Email: user.Email,
|
|
|
|
})
|
|
|
|
}
|
2021-01-08 05:55:25 +02:00
|
|
|
newError("tunnelling request to ", destination).WriteToLog(session.ExportIDToError(ctx))
|
2020-11-25 13:01:53 +02:00
|
|
|
|
2021-01-10 09:50:21 +02:00
|
|
|
if !s.cone || dest == nil {
|
2021-01-08 05:55:25 +02:00
|
|
|
dest = &destination
|
2020-12-23 15:06:21 +02:00
|
|
|
}
|
|
|
|
|
2021-01-08 08:00:51 +02:00
|
|
|
udpServer.Dispatch(currentPacketCtx, *dest, b) // first packet
|
2021-01-08 05:55:25 +02:00
|
|
|
for _, payload := range mb2 {
|
2021-01-08 08:00:51 +02:00
|
|
|
udpServer.Dispatch(currentPacketCtx, *dest, payload)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Session,
|
|
|
|
destination net.Destination,
|
|
|
|
clientReader buf.Reader,
|
2023-03-04 12:39:26 +02:00
|
|
|
clientWriter buf.Writer, dispatcher routing.Dispatcher, iConn stat.Connection, statConn *stat.CounterConnection,
|
2022-05-18 10:29:01 +03:00
|
|
|
) error {
|
2020-11-25 13:01:53 +02:00
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
|
|
|
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
|
|
|
|
|
|
|
|
link, err := dispatcher.Dispatch(ctx, destination)
|
|
|
|
if err != nil {
|
|
|
|
return newError("failed to dispatch request to ", destination).Base(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
requestDone := func() error {
|
|
|
|
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
2023-03-04 12:39:26 +02:00
|
|
|
if buf.Copy(clientReader, link.Writer, buf.UpdateActivity(timer)) != nil {
|
2020-11-25 13:01:53 +02:00
|
|
|
return newError("failed to transfer request").Base(err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
responseDone := func() error {
|
|
|
|
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
|
|
|
|
|
|
|
if err := buf.Copy(link.Reader, clientWriter, buf.UpdateActivity(timer)); err != nil {
|
|
|
|
return newError("failed to write response").Base(err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-19 19:57:14 +03:00
|
|
|
requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
|
2020-11-25 13:01:53 +02:00
|
|
|
if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
|
|
|
|
common.Must(common.Interrupt(link.Reader))
|
|
|
|
common.Must(common.Interrupt(link.Writer))
|
|
|
|
return newError("connection ends").Base(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-09-20 15:11:21 +03:00
|
|
|
func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err error, sessionPolicy policy.Session, connection stat.Connection, iConn stat.Connection, napfb map[string]map[string]map[string]*Fallback, first *buf.Buffer, firstLen int64, reader buf.Reader) error {
|
2020-11-25 13:01:53 +02:00
|
|
|
if err := connection.SetReadDeadline(time.Time{}); err != nil {
|
|
|
|
newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid)
|
|
|
|
}
|
|
|
|
newError("fallback starts").Base(err).AtInfo().WriteToLog(sid)
|
|
|
|
|
2021-01-18 09:41:00 +02:00
|
|
|
name := ""
|
2020-11-25 13:01:53 +02:00
|
|
|
alpn := ""
|
2021-01-18 09:41:00 +02:00
|
|
|
if tlsConn, ok := iConn.(*tls.Conn); ok {
|
|
|
|
cs := tlsConn.ConnectionState()
|
|
|
|
name = cs.ServerName
|
|
|
|
alpn = cs.NegotiatedProtocol
|
|
|
|
newError("realName = " + name).AtInfo().WriteToLog(sid)
|
|
|
|
newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
|
2023-02-15 18:07:12 +02:00
|
|
|
} else if realityConn, ok := iConn.(*reality.Conn); ok {
|
|
|
|
cs := realityConn.ConnectionState()
|
|
|
|
name = cs.ServerName
|
|
|
|
alpn = cs.NegotiatedProtocol
|
|
|
|
newError("realName = " + name).AtInfo().WriteToLog(sid)
|
|
|
|
newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid)
|
2021-01-18 09:41:00 +02:00
|
|
|
}
|
2021-01-22 01:37:55 +02:00
|
|
|
name = strings.ToLower(name)
|
|
|
|
alpn = strings.ToLower(alpn)
|
2021-01-18 09:41:00 +02:00
|
|
|
|
|
|
|
if len(napfb) > 1 || napfb[""] == nil {
|
|
|
|
if name != "" && napfb[name] == nil {
|
|
|
|
match := ""
|
|
|
|
for n := range napfb {
|
|
|
|
if n != "" && strings.Contains(name, n) && len(n) > len(match) {
|
|
|
|
match = n
|
|
|
|
}
|
|
|
|
}
|
|
|
|
name = match
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
2021-01-18 09:41:00 +02:00
|
|
|
|
|
|
|
if napfb[name] == nil {
|
|
|
|
name = ""
|
|
|
|
}
|
|
|
|
apfb := napfb[name]
|
|
|
|
if apfb == nil {
|
|
|
|
return newError(`failed to find the default "name" config`).AtWarning()
|
|
|
|
}
|
|
|
|
|
|
|
|
if apfb[alpn] == nil {
|
|
|
|
alpn = ""
|
|
|
|
}
|
2020-11-25 13:01:53 +02:00
|
|
|
pfb := apfb[alpn]
|
|
|
|
if pfb == nil {
|
|
|
|
return newError(`failed to find the default "alpn" config`).AtWarning()
|
|
|
|
}
|
|
|
|
|
|
|
|
path := ""
|
|
|
|
if len(pfb) > 1 || pfb[""] == nil {
|
|
|
|
if firstLen >= 18 && first.Byte(4) != '*' { // not h2c
|
|
|
|
firstBytes := first.Bytes()
|
|
|
|
for i := 4; i <= 8; i++ { // 5 -> 9
|
|
|
|
if firstBytes[i] == '/' && firstBytes[i-1] == ' ' {
|
|
|
|
search := len(firstBytes)
|
|
|
|
if search > 64 {
|
|
|
|
search = 64 // up to about 60
|
|
|
|
}
|
|
|
|
for j := i + 1; j < search; j++ {
|
|
|
|
k := firstBytes[j]
|
|
|
|
if k == '\r' || k == '\n' { // avoid logging \r or \n
|
|
|
|
break
|
|
|
|
}
|
2021-03-12 13:50:59 +02:00
|
|
|
if k == '?' || k == ' ' {
|
2020-11-25 13:01:53 +02:00
|
|
|
path = string(firstBytes[i:j])
|
|
|
|
newError("realPath = " + path).AtInfo().WriteToLog(sid)
|
|
|
|
if pfb[path] == nil {
|
|
|
|
path = ""
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fb := pfb[path]
|
|
|
|
if fb == nil {
|
|
|
|
return newError(`failed to find the default "path" config`).AtWarning()
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
|
|
|
|
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
|
|
|
|
|
|
|
|
var conn net.Conn
|
|
|
|
if err := retry.ExponentialBackoff(5, 100).On(func() error {
|
|
|
|
var dialer net.Dialer
|
|
|
|
conn, err = dialer.DialContext(ctx, fb.Type, fb.Dest)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}); err != nil {
|
|
|
|
return newError("failed to dial to " + fb.Dest).Base(err).AtWarning()
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
serverReader := buf.NewReader(conn)
|
|
|
|
serverWriter := buf.NewWriter(conn)
|
|
|
|
|
|
|
|
postRequest := func() error {
|
|
|
|
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
|
|
|
|
if fb.Xver != 0 {
|
2021-01-23 23:06:15 +02:00
|
|
|
ipType := 4
|
|
|
|
remoteAddr, remotePort, err := net.SplitHostPort(connection.RemoteAddr().String())
|
|
|
|
if err != nil {
|
|
|
|
ipType = 0
|
|
|
|
}
|
|
|
|
localAddr, localPort, err := net.SplitHostPort(connection.LocalAddr().String())
|
|
|
|
if err != nil {
|
|
|
|
ipType = 0
|
|
|
|
}
|
|
|
|
if ipType == 4 {
|
2021-01-22 05:26:57 +02:00
|
|
|
for i := 0; i < len(remoteAddr); i++ {
|
|
|
|
if remoteAddr[i] == ':' {
|
|
|
|
ipType = 6
|
|
|
|
break
|
|
|
|
}
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
pro := buf.New()
|
|
|
|
defer pro.Release()
|
|
|
|
switch fb.Xver {
|
|
|
|
case 1:
|
2021-01-22 05:26:57 +02:00
|
|
|
if ipType == 0 {
|
|
|
|
common.Must2(pro.Write([]byte("PROXY UNKNOWN\r\n")))
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if ipType == 4 {
|
2020-11-25 13:01:53 +02:00
|
|
|
common.Must2(pro.Write([]byte("PROXY TCP4 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n")))
|
|
|
|
} else {
|
|
|
|
common.Must2(pro.Write([]byte("PROXY TCP6 " + remoteAddr + " " + localAddr + " " + remotePort + " " + localPort + "\r\n")))
|
|
|
|
}
|
|
|
|
case 2:
|
2021-01-22 05:26:57 +02:00
|
|
|
common.Must2(pro.Write([]byte("\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A"))) // signature
|
|
|
|
if ipType == 0 {
|
|
|
|
common.Must2(pro.Write([]byte("\x20\x00\x00\x00"))) // v2 + LOCAL + UNSPEC + UNSPEC + 0 bytes
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if ipType == 4 {
|
|
|
|
common.Must2(pro.Write([]byte("\x21\x11\x00\x0C"))) // v2 + PROXY + AF_INET + STREAM + 12 bytes
|
2020-11-25 13:01:53 +02:00
|
|
|
common.Must2(pro.Write(net.ParseIP(remoteAddr).To4()))
|
|
|
|
common.Must2(pro.Write(net.ParseIP(localAddr).To4()))
|
|
|
|
} else {
|
2021-01-22 05:26:57 +02:00
|
|
|
common.Must2(pro.Write([]byte("\x21\x21\x00\x24"))) // v2 + PROXY + AF_INET6 + STREAM + 36 bytes
|
2020-11-25 13:01:53 +02:00
|
|
|
common.Must2(pro.Write(net.ParseIP(remoteAddr).To16()))
|
|
|
|
common.Must2(pro.Write(net.ParseIP(localAddr).To16()))
|
|
|
|
}
|
|
|
|
p1, _ := strconv.ParseUint(remotePort, 10, 16)
|
|
|
|
p2, _ := strconv.ParseUint(localPort, 10, 16)
|
|
|
|
common.Must2(pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)}))
|
|
|
|
}
|
|
|
|
if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil {
|
|
|
|
return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
|
|
|
|
return newError("failed to fallback request payload").Base(err).AtInfo()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
writer := buf.NewWriter(connection)
|
|
|
|
|
|
|
|
getResponse := func() error {
|
|
|
|
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
|
|
|
if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil {
|
|
|
|
return newError("failed to deliver response payload").Base(err).AtInfo()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil {
|
|
|
|
common.Must(common.Interrupt(serverReader))
|
|
|
|
common.Must(common.Interrupt(serverWriter))
|
|
|
|
return newError("fallback ends").Base(err).AtInfo()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|