1
0

util.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package controller
  2. import (
  3. "fmt"
  4. "net"
  5. "net/http"
  6. "net/netip"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "github.com/mhsanaei/3x-ui/v3/logger"
  11. "github.com/mhsanaei/3x-ui/v3/web/entity"
  12. "github.com/mhsanaei/3x-ui/v3/web/service"
  13. "github.com/gin-gonic/gin"
  14. )
  15. // getRemoteIp extracts the real IP address from the request headers or remote address.
  16. func getRemoteIp(c *gin.Context) string {
  17. remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
  18. if !ok {
  19. return "unknown"
  20. }
  21. if isTrustedProxy(remoteIP) {
  22. if ip, ok := extractTrustedIP(c.GetHeader("X-Real-IP")); ok {
  23. return ip
  24. }
  25. if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
  26. for part := range strings.SplitSeq(xff, ",") {
  27. if ip, ok := extractTrustedIP(part); ok {
  28. return ip
  29. }
  30. }
  31. }
  32. }
  33. return remoteIP
  34. }
  35. func isTrustedForwardedRequest(c *gin.Context) bool {
  36. remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
  37. return ok && isTrustedProxy(remoteIP)
  38. }
  39. func isTrustedProxy(ip string) bool {
  40. addr, err := netip.ParseAddr(ip)
  41. if err != nil {
  42. return false
  43. }
  44. trusted := trustedProxyCIDRs()
  45. for value := range strings.SplitSeq(trusted, ",") {
  46. value = strings.TrimSpace(value)
  47. if value == "" {
  48. continue
  49. }
  50. if prefix, err := netip.ParsePrefix(value); err == nil {
  51. if prefix.Contains(addr) {
  52. return true
  53. }
  54. continue
  55. }
  56. if proxyIP, err := netip.ParseAddr(value); err == nil && proxyIP.Unmap() == addr.Unmap() {
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. func trustedProxyCIDRs() (trusted string) {
  63. trusted = "127.0.0.1/32,::1/128"
  64. defer func() {
  65. _ = recover()
  66. }()
  67. settingService := service.SettingService{}
  68. if value, err := settingService.GetTrustedProxyCIDRs(); err == nil && strings.TrimSpace(value) != "" {
  69. trusted = value
  70. }
  71. return trusted
  72. }
  73. func extractTrustedIP(value string) (string, bool) {
  74. candidate := strings.TrimSpace(value)
  75. if candidate == "" {
  76. return "", false
  77. }
  78. if ip, ok := parseIPCandidate(candidate); ok {
  79. return ip.String(), true
  80. }
  81. if host, _, err := net.SplitHostPort(candidate); err == nil {
  82. if ip, ok := parseIPCandidate(host); ok {
  83. return ip.String(), true
  84. }
  85. }
  86. if strings.Count(candidate, ":") == 1 {
  87. if host, _, err := net.SplitHostPort(fmt.Sprintf("[%s]", candidate)); err == nil {
  88. if ip, ok := parseIPCandidate(host); ok {
  89. return ip.String(), true
  90. }
  91. }
  92. }
  93. return "", false
  94. }
  95. func parseIPCandidate(value string) (netip.Addr, bool) {
  96. ip, err := netip.ParseAddr(strings.TrimSpace(value))
  97. if err != nil {
  98. return netip.Addr{}, false
  99. }
  100. return ip.Unmap(), true
  101. }
  102. // jsonMsg sends a JSON response with a message and error status.
  103. func jsonMsg(c *gin.Context, msg string, err error) {
  104. jsonMsgObj(c, msg, nil, err)
  105. }
  106. // jsonObj sends a JSON response with an object and error status.
  107. func jsonObj(c *gin.Context, obj any, err error) {
  108. jsonMsgObj(c, "", obj, err)
  109. }
  110. func requestErrorContext(c *gin.Context) string {
  111. handler, loc := callerOutsideUtil()
  112. return fmt.Sprintf("[%s %s handler=%s %s]", c.Request.Method, c.Request.URL.Path, handler, loc)
  113. }
  114. func callerOutsideUtil() (string, string) {
  115. var pcs [12]uintptr
  116. n := runtime.Callers(2, pcs[:])
  117. frames := runtime.CallersFrames(pcs[:n])
  118. for {
  119. frame, more := frames.Next()
  120. base := filepath.Base(frame.File)
  121. if base != "util.go" {
  122. name := frame.Function
  123. if idx := strings.LastIndex(name, "/"); idx >= 0 {
  124. name = name[idx+1:]
  125. }
  126. return name, fmt.Sprintf("%s:%d", base, frame.Line)
  127. }
  128. if !more {
  129. break
  130. }
  131. }
  132. return "unknown", "unknown"
  133. }
  134. // jsonMsgObj sends a JSON response with a message, object, and error status.
  135. func jsonMsgObj(c *gin.Context, msg string, obj any, err error) {
  136. m := entity.Msg{
  137. Obj: obj,
  138. }
  139. if err == nil {
  140. m.Success = true
  141. if msg != "" {
  142. m.Msg = msg
  143. }
  144. } else {
  145. m.Success = false
  146. ctx := requestErrorContext(c)
  147. fail := I18nWeb(c, "fail")
  148. errStr := err.Error()
  149. if errStr != "" {
  150. m.Msg = msg + " (" + errStr + ")"
  151. logger.Warningf("%s %s %s: %v", ctx, msg, fail, err)
  152. } else if msg != "" {
  153. m.Msg = msg
  154. logger.Warningf("%s %s %s", ctx, msg, fail)
  155. } else {
  156. m.Msg = I18nWeb(c, "somethingWentWrong")
  157. logger.Warningf("%s %s %s", ctx, m.Msg, fail)
  158. }
  159. }
  160. c.JSON(http.StatusOK, m)
  161. }
  162. // pureJsonMsg sends a pure JSON message response with custom status code.
  163. func pureJsonMsg(c *gin.Context, statusCode int, success bool, msg string) {
  164. c.JSON(statusCode, entity.Msg{
  165. Success: success,
  166. Msg: msg,
  167. })
  168. }
  169. // isAjax checks if the request is an AJAX request.
  170. func isAjax(c *gin.Context) bool {
  171. return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
  172. }