mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-12 00:28:37 +08:00
Compare commits
1 Commits
be0a30ddf0
...
02c4a3bbb8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02c4a3bbb8 |
2
.github/workflows/gin.yml
vendored
2
.github/workflows/gin.yml
vendored
@ -65,7 +65,7 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- uses: actions/cache@v5
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
${{ matrix.go-build }}
|
||||
|
||||
30
context.go
30
context.go
@ -978,32 +978,18 @@ func (c *Context) ClientIP() string {
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
trusted bool
|
||||
remoteIP net.IP
|
||||
)
|
||||
// If gin is listening a unix socket, always trust it.
|
||||
localAddr, ok := c.Request.Context().Value(http.LocalAddrContextKey).(net.Addr)
|
||||
if ok && strings.HasPrefix(localAddr.Network(), "unix") {
|
||||
trusted = true
|
||||
}
|
||||
|
||||
// Fallback
|
||||
if !trusted {
|
||||
// It also checks if the remoteIP is a trusted proxy or not.
|
||||
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
|
||||
// defined by Engine.SetTrustedProxies()
|
||||
remoteIP = net.ParseIP(c.RemoteIP())
|
||||
if remoteIP == nil {
|
||||
return ""
|
||||
}
|
||||
trusted = c.engine.isTrustedProxy(remoteIP)
|
||||
// It also checks if the remoteIP is a trusted proxy or not.
|
||||
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
|
||||
// defined by Engine.SetTrustedProxies()
|
||||
remoteIP := net.ParseIP(c.RemoteIP())
|
||||
if remoteIP == nil {
|
||||
return ""
|
||||
}
|
||||
trusted := c.engine.isTrustedProxy(remoteIP)
|
||||
|
||||
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
|
||||
for _, headerName := range c.engine.RemoteIPHeaders {
|
||||
headerValue := strings.Join(c.Request.Header.Values(headerName), ",")
|
||||
ip, valid := c.engine.validateHeader(headerValue)
|
||||
ip, valid := c.engine.validateHeader(c.requestHeader(headerName))
|
||||
if valid {
|
||||
return ip
|
||||
}
|
||||
|
||||
@ -1488,37 +1488,6 @@ func TestContextRenderNoContentIndentedJSON(t *testing.T) {
|
||||
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
func TestContextClientIPWithMultipleHeaders(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
|
||||
|
||||
// Multiple X-Forwarded-For headers
|
||||
c.Request.Header.Add("X-Forwarded-For", "1.2.3.4, "+localhostIP)
|
||||
c.Request.Header.Add("X-Forwarded-For", "5.6.7.8")
|
||||
c.Request.RemoteAddr = localhostIP + ":1234"
|
||||
|
||||
c.engine.ForwardedByClientIP = true
|
||||
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
|
||||
_ = c.engine.SetTrustedProxies([]string{localhostIP})
|
||||
|
||||
// Should return 5.6.7.8 (last non-trusted IP)
|
||||
assert.Equal(t, "5.6.7.8", c.ClientIP())
|
||||
}
|
||||
|
||||
func TestContextClientIPWithSingleHeader(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("X-Forwarded-For", "1.2.3.4, "+localhostIP)
|
||||
c.Request.RemoteAddr = localhostIP + ":1234"
|
||||
|
||||
c.engine.ForwardedByClientIP = true
|
||||
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
|
||||
_ = c.engine.SetTrustedProxies([]string{localhostIP})
|
||||
|
||||
// Should return 1.2.3.4
|
||||
assert.Equal(t, "1.2.3.4", c.ClientIP())
|
||||
}
|
||||
|
||||
// Tests that the response is serialized as Secure JSON
|
||||
// and Content-Type is set to application/json
|
||||
func TestContextRenderSecureJSON(t *testing.T) {
|
||||
@ -2260,16 +2229,6 @@ func TestContextClientIP(t *testing.T) {
|
||||
c.engine.trustedCIDRs, _ = c.engine.prepareTrustedCIDRs()
|
||||
resetContextForClientIPTests(c)
|
||||
|
||||
// unix address
|
||||
addr := &net.UnixAddr{Net: "unix", Name: "@"}
|
||||
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), http.LocalAddrContextKey, addr))
|
||||
c.Request.RemoteAddr = addr.String()
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
|
||||
// reset
|
||||
c.Request = c.Request.WithContext(context.Background())
|
||||
resetContextForClientIPTests(c)
|
||||
|
||||
// Legacy tests (validating that the defaults don't break the
|
||||
// (insecure!) old behaviour)
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
@ -2296,7 +2255,7 @@ func TestContextClientIP(t *testing.T) {
|
||||
resetContextForClientIPTests(c)
|
||||
|
||||
// IPv6 support
|
||||
c.Request.RemoteAddr = fmt.Sprintf("[%s]:12345", localhostIPv6)
|
||||
c.Request.RemoteAddr = "[::1]:12345"
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
|
||||
resetContextForClientIPTests(c)
|
||||
@ -3634,7 +3593,7 @@ func TestContextCopyShouldNotCancel(t *testing.T) {
|
||||
}()
|
||||
|
||||
addr := strings.Split(l.Addr().String(), ":")
|
||||
res, err := http.Get(fmt.Sprintf("http://%s:%s/", localhostIP, addr[len(addr)-1]))
|
||||
res, err := http.Get(fmt.Sprintf("http://127.0.0.1:%s/", addr[len(addr)-1]))
|
||||
if err != nil {
|
||||
t.Error(fmt.Errorf("request error: %w", err))
|
||||
return
|
||||
|
||||
@ -83,7 +83,7 @@ func TestLoadHTMLGlobDebugMode(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestH2c(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", localhostIP+":0")
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
49
recovery.go
49
recovery.go
@ -12,12 +12,12 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin/internal/bytesconv"
|
||||
@ -57,33 +57,40 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
|
||||
}
|
||||
return func(c *Context) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
if err := recover(); err != nil {
|
||||
// Check for a broken connection, as it is not really a
|
||||
// condition that warrants a panic stack trace.
|
||||
var isBrokenPipe bool
|
||||
err, ok := rec.(error)
|
||||
if ok {
|
||||
isBrokenPipe = errors.Is(err, syscall.EPIPE) ||
|
||||
errors.Is(err, syscall.ECONNRESET) ||
|
||||
errors.Is(err, http.ErrAbortHandler)
|
||||
}
|
||||
if logger != nil {
|
||||
if isBrokenPipe {
|
||||
logger.Printf("%s\n%s%s", rec, secureRequestDump(c.Request), reset)
|
||||
} else if IsDebugging() {
|
||||
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
|
||||
timeFormat(time.Now()), secureRequestDump(c.Request), rec, stack(stackSkip), reset)
|
||||
} else {
|
||||
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",
|
||||
timeFormat(time.Now()), rec, stack(stackSkip), reset)
|
||||
var brokenPipe bool
|
||||
if ne, ok := err.(*net.OpError); ok {
|
||||
var se *os.SyscallError
|
||||
if errors.As(ne, &se) {
|
||||
seStr := strings.ToLower(se.Error())
|
||||
if strings.Contains(seStr, "broken pipe") ||
|
||||
strings.Contains(seStr, "connection reset by peer") {
|
||||
brokenPipe = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if isBrokenPipe {
|
||||
if e, ok := err.(error); ok && errors.Is(e, http.ErrAbortHandler) {
|
||||
brokenPipe = true
|
||||
}
|
||||
if logger != nil {
|
||||
if brokenPipe {
|
||||
logger.Printf("%s\n%s%s", err, secureRequestDump(c.Request), reset)
|
||||
} else if IsDebugging() {
|
||||
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
|
||||
timeFormat(time.Now()), secureRequestDump(c.Request), err, stack(stackSkip), reset)
|
||||
} else {
|
||||
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",
|
||||
timeFormat(time.Now()), err, stack(stackSkip), reset)
|
||||
}
|
||||
}
|
||||
if brokenPipe {
|
||||
// If the connection is dead, we can't write a status to it.
|
||||
c.Error(err) //nolint: errcheck
|
||||
c.Error(err.(error)) //nolint: errcheck
|
||||
c.Abort()
|
||||
} else {
|
||||
handle(c, rec)
|
||||
handle(c, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
@ -98,13 +98,13 @@ func TestFunction(t *testing.T) {
|
||||
func TestPanicWithBrokenPipe(t *testing.T) {
|
||||
const expectCode = 204
|
||||
|
||||
expectErrnos := []syscall.Errno{
|
||||
syscall.EPIPE,
|
||||
syscall.ECONNRESET,
|
||||
expectMsgs := map[syscall.Errno]string{
|
||||
syscall.EPIPE: "broken pipe",
|
||||
syscall.ECONNRESET: "connection reset by peer",
|
||||
}
|
||||
|
||||
for _, errno := range expectErrnos {
|
||||
t.Run("Recovery from "+errno.Error(), func(t *testing.T) {
|
||||
for errno, expectMsg := range expectMsgs {
|
||||
t.Run(expectMsg, func(t *testing.T) {
|
||||
var buf strings.Builder
|
||||
|
||||
router := New()
|
||||
@ -122,8 +122,7 @@ func TestPanicWithBrokenPipe(t *testing.T) {
|
||||
w := PerformRequest(router, http.MethodGet, "/recovery")
|
||||
// TEST
|
||||
assert.Equal(t, expectCode, w.Code)
|
||||
assert.Contains(t, strings.ToLower(buf.String()), errno.Error())
|
||||
assert.NotContains(t, strings.ToLower(buf.String()), "[Recovery]")
|
||||
assert.Contains(t, strings.ToLower(buf.String()), expectMsg)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -128,9 +128,7 @@ func (w *responseWriter) CloseNotify() <-chan bool {
|
||||
// Flush implements the http.Flusher interface.
|
||||
func (w *responseWriter) Flush() {
|
||||
w.WriteHeaderNow()
|
||||
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
w.ResponseWriter.(http.Flusher).Flush()
|
||||
}
|
||||
|
||||
func (w *responseWriter) Pusher() (pusher http.Pusher) {
|
||||
|
||||
6
utils.go
6
utils.go
@ -19,12 +19,6 @@ import (
|
||||
// BindKey indicates a default bind key.
|
||||
const BindKey = "_gin-gonic/gin/bindkey"
|
||||
|
||||
// localhostIP indicates the default localhost IP address.
|
||||
const localhostIP = "127.0.0.1"
|
||||
|
||||
// localhostIPv6 indicates the default localhost IPv6 address.
|
||||
const localhostIPv6 = "::1"
|
||||
|
||||
// Bind is a helper function for given interface object and returns a Gin middleware.
|
||||
func Bind(val any) HandlerFunc {
|
||||
value := reflect.ValueOf(val)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user