From 5e606169f1c6d168c77637657572f2862cd2418f Mon Sep 17 00:00:00 2001 From: lucifer Date: Thu, 14 Oct 2021 12:10:19 +0800 Subject: [PATCH] gRPC: Parse X-Real-IP header, fix #766 (#769) --- transport/internet/grpc/encoding/hunkconn.go | 15 +++++++++++++++ transport/internet/grpc/encoding/multiconn.go | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/transport/internet/grpc/encoding/hunkconn.go b/transport/internet/grpc/encoding/hunkconn.go index a15a9577..44c06322 100644 --- a/transport/internet/grpc/encoding/hunkconn.go +++ b/transport/internet/grpc/encoding/hunkconn.go @@ -5,9 +5,11 @@ import ( "io" "net" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "github.com/xtls/xray-core/common/buf" + xnet "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/signal/done" ) @@ -49,6 +51,19 @@ func NewHunkConn(hc HunkConn, cancel context.CancelFunc) net.Conn { } } + md, ok := metadata.FromIncomingContext(hc.Context()) + if ok { + header := md.Get("x-real-ip") + if len(header) > 0 { + realip := xnet.ParseAddress(header[0]) + if realip.Family().IsIP() { + rAddr = &net.TCPAddr{ + IP: realip.IP(), + Port: 0, + } + } + } + } wrc := NewHunkReadWriter(hc, cancel) return cnc.NewConnection( cnc.ConnectionInput(wrc), diff --git a/transport/internet/grpc/encoding/multiconn.go b/transport/internet/grpc/encoding/multiconn.go index 31e8bb4b..13a7eb2c 100644 --- a/transport/internet/grpc/encoding/multiconn.go +++ b/transport/internet/grpc/encoding/multiconn.go @@ -5,9 +5,11 @@ import ( "io" "net" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "github.com/xtls/xray-core/common/buf" + xnet "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/signal/done" ) @@ -44,6 +46,19 @@ func NewMultiHunkConn(hc MultiHunkConn, cancel context.CancelFunc) net.Conn { } } + md, ok := metadata.FromIncomingContext(hc.Context()) + if ok { + header := md.Get("x-real-ip") + if len(header) > 0 { + realip := xnet.ParseAddress(header[0]) + if realip.Family().IsIP() { + rAddr = &net.TCPAddr{ + IP: realip.IP(), + Port: 0, + } + } + } + } wrc := NewMultiHunkReadWriter(hc, cancel) return cnc.NewConnection( cnc.ConnectionInputMulti(wrc),