2020-11-25 13:01:53 +02:00
|
|
|
package trojan
|
|
|
|
|
|
|
|
import (
|
2024-07-04 22:59:18 +03:00
|
|
|
"bufio"
|
2020-11-25 13:01:53 +02:00
|
|
|
"context"
|
2024-07-04 22:59:18 +03:00
|
|
|
"golang.org/x/net/http2"
|
|
|
|
"golang.org/x/net/http2/hpack"
|
2020-11-25 13:01:53 +02:00
|
|
|
"io"
|
|
|
|
"strconv"
|
2021-01-18 09:41:00 +02:00
|
|
|
"strings"
|
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 {
|
|
|
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return nil, errors.New("failed to get trojan user").Base(err).AtError()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := validator.Add(u); err != nil {
|
2024-06-29 21:32:57 +03:00
|
|
|
return nil, errors.New("failed to add user").Base(err).AtError()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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().
|
2021-09-20 15:11:21 +03:00
|
|
|
func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error {
|
2020-11-25 13:01:53 +02:00
|
|
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("unable to set read deadline").Base(err).AtWarning()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to read first request").Base(err)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
2024-06-29 21:32:57 +03:00
|
|
|
errors.LogInfo(ctx, "firstLen = ", firstLen)
|
2020-11-25 13:01:53 +02:00
|
|
|
|
|
|
|
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
|
2024-06-29 21:32:57 +03:00
|
|
|
err = errors.New("not trojan protocol")
|
2020-11-25 13:01:53 +02:00
|
|
|
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
|
2024-06-29 21:32:57 +03:00
|
|
|
err = errors.New("not a valid user")
|
2020-11-25 13:01:53 +02:00
|
|
|
log.Record(&log.AccessMessage{
|
|
|
|
From: conn.RemoteAddr(),
|
|
|
|
To: "",
|
|
|
|
Status: log.AccessRejected,
|
|
|
|
Reason: err,
|
|
|
|
})
|
|
|
|
|
|
|
|
shouldFallback = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if isfb && shouldFallback {
|
2024-06-29 21:32:57 +03:00
|
|
|
return s.fallback(ctx, err, sessionPolicy, conn, iConn, napfb, first, firstLen, bufferedReader)
|
2020-11-25 13:01:53 +02:00
|
|
|
} else if shouldFallback {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("invalid protocol or invalid user")
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
clientReader := &ConnReader{Reader: bufferedReader}
|
|
|
|
if err := clientReader.ParseHeader(); err != nil {
|
|
|
|
log.Record(&log.AccessMessage{
|
|
|
|
From: conn.RemoteAddr(),
|
|
|
|
To: "",
|
|
|
|
Status: log.AccessRejected,
|
|
|
|
Reason: err,
|
|
|
|
})
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to create request from: ", conn.RemoteAddr()).Base(err)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
destination := clientReader.Target
|
|
|
|
if err := conn.SetReadDeadline(time.Time{}); err != nil {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("unable to set read deadline").Base(err).AtWarning()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
inbound := session.InboundFromContext(ctx)
|
2023-04-06 13:21:35 +03:00
|
|
|
inbound.Name = "trojan"
|
2024-05-14 04:52:24 +03:00
|
|
|
inbound.CanSpliceCopy = 3
|
2020-11-25 13:01:53 +02:00
|
|
|
inbound.User = user
|
|
|
|
sessionPolicy = s.policyManager.ForLevel(user.Level)
|
|
|
|
|
|
|
|
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,
|
|
|
|
})
|
|
|
|
|
2024-06-29 21:32:57 +03:00
|
|
|
errors.LogInfo(ctx, "received request for ", destination)
|
2023-07-06 18:18:05 +03:00
|
|
|
return s.handleConnection(ctx, sessionPolicy, destination, clientReader, buf.NewWriter(conn), dispatcher)
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
errors.LogWarningInner(ctx, err, "failed to write response")
|
2021-01-11 11:30:57 +02:00
|
|
|
}
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("unexpected EOF").Base(err)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
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,
|
|
|
|
})
|
|
|
|
}
|
2024-06-29 21:32:57 +03:00
|
|
|
errors.LogInfo(ctx, "tunnelling request to ", destination)
|
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-07-06 18:18:05 +03:00
|
|
|
clientWriter buf.Writer, dispatcher routing.Dispatcher,
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to dispatch request to ", destination).Base(err)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to transfer request").Base(err)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
responseDone := func() error {
|
|
|
|
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
|
|
|
|
|
|
|
|
if err := buf.Copy(link.Reader, clientWriter, buf.UpdateActivity(timer)); err != nil {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to write response").Base(err)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
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))
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("connection ends").Base(err)
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-06-29 21:32:57 +03:00
|
|
|
func (s *Server) fallback(ctx context.Context, 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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
errors.LogWarningInner(ctx, err, "unable to set back read deadline")
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
2024-06-29 21:32:57 +03:00
|
|
|
errors.LogInfoInner(ctx, err, "fallback starts")
|
2020-11-25 13:01:53 +02:00
|
|
|
|
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
|
2024-07-04 22:59:18 +03:00
|
|
|
errors.LogInfo(ctx, "realName = "+name)
|
|
|
|
errors.LogInfo(ctx, "realAlpn = "+alpn)
|
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
|
2024-07-04 22:59:18 +03:00
|
|
|
errors.LogInfo(ctx, "realName = "+name)
|
|
|
|
errors.LogInfo(ctx, "realAlpn = "+alpn)
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New(`failed to find the default "name" config`).AtWarning()
|
2021-01-18 09:41:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if apfb[alpn] == nil {
|
|
|
|
alpn = ""
|
|
|
|
}
|
2020-11-25 13:01:53 +02:00
|
|
|
pfb := apfb[alpn]
|
|
|
|
if pfb == nil {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New(`failed to find the default "alpn" config`).AtWarning()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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])
|
2024-07-04 22:59:18 +03:00
|
|
|
errors.LogInfo(ctx, "realPath = "+path)
|
2020-11-25 13:01:53 +02:00
|
|
|
if pfb[path] == nil {
|
|
|
|
path = ""
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2024-07-04 22:59:18 +03:00
|
|
|
} else if firstLen >= 18 && first.Byte(4) == '*' { // process h2c
|
|
|
|
h2path := extractPathFromH2Request(connection)
|
|
|
|
if h2path != "" {
|
|
|
|
path = h2path
|
|
|
|
}
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
fb := pfb[path]
|
|
|
|
if fb == nil {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New(`failed to find the default "path" config`).AtWarning()
|
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)
|
|
|
|
|
|
|
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to dial to " + fb.Dest).Base(err).AtWarning()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to fallback request payload").Base(err).AtInfo()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
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 {
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("failed to deliver response payload").Base(err).AtInfo()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
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))
|
2024-06-29 21:32:57 +03:00
|
|
|
return errors.New("fallback ends").Base(err).AtInfo()
|
2020-11-25 13:01:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2024-07-04 22:59:18 +03:00
|
|
|
|
|
|
|
// Get path form http2
|
|
|
|
func extractPathFromH2Request(conn stat.Connection) string {
|
|
|
|
reader := bufio.NewReader(conn)
|
|
|
|
framer := http2.NewFramer(conn, reader)
|
|
|
|
|
|
|
|
for {
|
|
|
|
frame, err := framer.ReadFrame()
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// find headers frame
|
|
|
|
if f, ok := frame.(*http2.HeadersFrame); ok {
|
|
|
|
decoder := hpack.NewDecoder(4096, func(hf hpack.HeaderField) {})
|
|
|
|
headerBlock := f.HeaderBlockFragment()
|
|
|
|
|
|
|
|
hf, err := decoder.DecodeFull(headerBlock)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
path := func(headers []hpack.HeaderField) string {
|
|
|
|
for _, header := range headers {
|
|
|
|
if header.Name == ":path" {
|
|
|
|
return header.Value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
return path(hf)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|