recovery.go
This file
Path
recovery.go
204 lines · 5.7 KiB · Go
Last changed by
fix(recovery): record recovered panics in c.Errors (#4698)DadaVinqibefore adoption4a3eb31
History of this fileTake it
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8 "bufio"9 "bytes"10 "cmp"11 "errors"12 "fmt"13 "io"14 "log"15 "net/http"16 "net/http/httputil"17 "os"18 "runtime"19 "strings"20 "syscall"21 "time"2223 "github.com/gin-gonic/gin/internal/bytesconv"24)2526const (27 dunno = "???"28 stackSkip = 329)3031// RecoveryFunc defines the function passable to CustomRecovery.32type RecoveryFunc func(c *Context, err any)3334// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.35func Recovery() HandlerFunc {36 return RecoveryWithWriter(DefaultErrorWriter)37}3839// CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.40func CustomRecovery(handle RecoveryFunc) HandlerFunc {41 return RecoveryWithWriter(DefaultErrorWriter, handle)42}4344// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.45func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc {46 if len(recovery) > 0 {47 return CustomRecoveryWithWriter(out, recovery[0])48 }49 return CustomRecoveryWithWriter(out, defaultHandleRecovery)50}5152// CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.53func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {54 var logger *log.Logger55 if out != nil {56 logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)57 }58 return func(c *Context) {59 defer func() {60 if rec := recover(); rec != nil {61 // Check for a broken connection, as it is not really a62 // condition that warrants a panic stack trace.63 var isBrokenPipe bool64 err, ok := rec.(error)65 if ok {66 isBrokenPipe = errors.Is(err, syscall.EPIPE) ||67 errors.Is(err, syscall.ECONNRESET) ||68 errors.Is(err, http.ErrAbortHandler)69 }70 if logger != nil {71 if isBrokenPipe {72 logger.Printf("%s\n%s%s", rec, secureRequestDump(c.Request), reset)73 } else if IsDebugging() {74 logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",75 timeFormat(time.Now()), secureRequestDump(c.Request), rec, stack(stackSkip), reset)76 } else {77 logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",78 timeFormat(time.Now()), rec, stack(stackSkip), reset)79 }80 }81 if isBrokenPipe {82 // If the connection is dead, we can't write a status to it.83 c.Error(err) //nolint: errcheck84 c.Abort()85 } else {86 handle(c, rec)87 }88 }89 }()90 c.Next()91 }92}9394// secureRequestDump returns a sanitized HTTP request dump where the Authorization header,95// if present, is replaced with a masked value ("Authorization: *") to avoid leaking sensitive credentials.96//97// Currently, only the Authorization header is sanitized. All other headers and request data remain unchanged.98func secureRequestDump(r *http.Request) string {99 httpRequest, _ := httputil.DumpRequest(r, false)100 lines := strings.Split(bytesconv.BytesToString(httpRequest), "\r\n")101 for i, line := range lines {102 if strings.HasPrefix(line, "Authorization:") {103 lines[i] = "Authorization: *"104 }105 }106 return strings.Join(lines, "\r\n")107}108109func defaultHandleRecovery(c *Context, err any) {110 e, ok := err.(error)111 if !ok {112 e = fmt.Errorf("%v", err)113 }114 c.Error(e) //nolint: errcheck115 c.AbortWithStatus(http.StatusInternalServerError)116}117118// stack returns a nicely formatted stack frame, skipping skip frames.119func stack(skip int) []byte {120 buf := new(bytes.Buffer) // the returned data121 // As we loop, we open files and read them. These variables record the currently122 // loaded file.123 var (124 nLine string125 lastFile string126 err error127 )128 for i := skip; ; i++ { // Skip the expected number of frames129 pc, file, line, ok := runtime.Caller(i)130 if !ok {131 break132 }133 // Print this much at least. If we can't find the source, it won't show.134 fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)135 if file != lastFile {136 nLine, err = readNthLine(file, line-1)137 if err != nil {138 continue139 }140 lastFile = file141 }142 fmt.Fprintf(buf, "\t%s: %s\n", function(pc), cmp.Or(nLine, dunno))143 }144 return buf.Bytes()145}146147// readNthLine reads the nth line from the file.148// It returns the trimmed content of the line if found,149// or an empty string if the line doesn't exist.150// If there's an error opening the file, it returns the error.151func readNthLine(file string, n int) (string, error) {152 if n < 0 {153 return "", nil154 }155156 f, err := os.Open(file)157 if err != nil {158 return "", err159 }160 defer f.Close()161162 scanner := bufio.NewScanner(f)163 for i := 0; i < n; i++ {164 if !scanner.Scan() {165 return "", nil166 }167 }168169 if scanner.Scan() {170 return strings.TrimSpace(scanner.Text()), nil171 }172173 return "", nil174}175176// function returns, if possible, the name of the function containing the PC.177func function(pc uintptr) string {178 fn := runtime.FuncForPC(pc)179 if fn == nil {180 return dunno181 }182 name := fn.Name()183 // The name includes the path name to the package, which is unnecessary184 // since the file name is already included. Plus, it has center dots.185 // That is, we see186 // runtime/debug.*T·ptrmethod187 // and want188 // *T.ptrmethod189 // Also the package path might contain dot (e.g. code.google.com/...),190 // so first eliminate the path prefix191 if lastSlash := strings.LastIndexByte(name, '/'); lastSlash >= 0 {192 name = name[lastSlash+1:]193 }194 if period := strings.IndexByte(name, '.'); period >= 0 {195 name = name[period+1:]196 }197 name = strings.ReplaceAll(name, "·", ".")198 return name199}200201// timeFormat returns a customized time string for logger.202func timeFormat(t time.Time) string {203 return t.Format("2006/01/02 - 15:04:05")204}