util.go 3.8 KB

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