proxy_parser.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package upstream
  2. import (
  3. "net/url"
  4. "regexp"
  5. "strings"
  6. "github.com/0xJacky/Nginx-UI/internal/nginx"
  7. "github.com/0xJacky/Nginx-UI/settings"
  8. )
  9. // ProxyTarget represents a proxy destination
  10. type ProxyTarget struct {
  11. Host string `json:"host"`
  12. Port string `json:"port"`
  13. Type string `json:"type"` // "proxy_pass" or "upstream"
  14. }
  15. // ParseProxyTargetsFromRawContent parses proxy targets from raw nginx configuration content
  16. func ParseProxyTargetsFromRawContent(content string) []ProxyTarget {
  17. var targets []ProxyTarget
  18. // First, collect all upstream names
  19. upstreamNames := make(map[string]bool)
  20. upstreamRegex := regexp.MustCompile(`(?s)upstream\s+([^\s]+)\s*\{([^}]+)\}`)
  21. upstreamMatches := upstreamRegex.FindAllStringSubmatch(content, -1)
  22. // Parse upstream blocks and collect upstream names
  23. for _, match := range upstreamMatches {
  24. if len(match) >= 3 {
  25. upstreamName := match[1]
  26. upstreamNames[upstreamName] = true
  27. upstreamContent := match[2]
  28. serverRegex := regexp.MustCompile(`(?m)^\s*server\s+([^;]+);`)
  29. serverMatches := serverRegex.FindAllStringSubmatch(upstreamContent, -1)
  30. for _, serverMatch := range serverMatches {
  31. if len(serverMatch) >= 2 {
  32. target := parseServerAddress(strings.TrimSpace(serverMatch[1]), "upstream")
  33. if target.Host != "" {
  34. targets = append(targets, target)
  35. }
  36. }
  37. }
  38. }
  39. }
  40. // Parse proxy_pass directives, but skip upstream references
  41. proxyPassRegex := regexp.MustCompile(`(?m)^\s*proxy_pass\s+([^;]+);`)
  42. proxyMatches := proxyPassRegex.FindAllStringSubmatch(content, -1)
  43. for _, match := range proxyMatches {
  44. if len(match) >= 2 {
  45. proxyPassURL := strings.TrimSpace(match[1])
  46. // Skip if this proxy_pass references an upstream
  47. if !isUpstreamReference(proxyPassURL, upstreamNames) {
  48. target := parseProxyPassURL(proxyPassURL)
  49. if target.Host != "" {
  50. targets = append(targets, target)
  51. }
  52. }
  53. }
  54. }
  55. return deduplicateTargets(targets)
  56. }
  57. // parseUpstreamServers extracts server addresses from upstream blocks
  58. func parseUpstreamServers(upstream *nginx.NgxUpstream) []ProxyTarget {
  59. var targets []ProxyTarget
  60. for _, directive := range upstream.Directives {
  61. if directive.Directive == "server" {
  62. target := parseServerAddress(directive.Params, "upstream")
  63. if target.Host != "" {
  64. targets = append(targets, target)
  65. }
  66. }
  67. }
  68. return targets
  69. }
  70. // parseLocationProxyPass extracts proxy_pass from location content
  71. func parseLocationProxyPass(content string) []ProxyTarget {
  72. var targets []ProxyTarget
  73. // Use regex to find proxy_pass directives
  74. proxyPassRegex := regexp.MustCompile(`(?m)^\s*proxy_pass\s+([^;]+);`)
  75. matches := proxyPassRegex.FindAllStringSubmatch(content, -1)
  76. for _, match := range matches {
  77. if len(match) >= 2 {
  78. target := parseProxyPassURL(strings.TrimSpace(match[1]))
  79. if target.Host != "" {
  80. targets = append(targets, target)
  81. }
  82. }
  83. }
  84. return targets
  85. }
  86. // parseProxyPassURL parses a proxy_pass URL and extracts host and port
  87. func parseProxyPassURL(proxyPass string) ProxyTarget {
  88. proxyPass = strings.TrimSpace(proxyPass)
  89. // Handle HTTP/HTTPS URLs (e.g., "http://backend")
  90. if strings.HasPrefix(proxyPass, "http://") || strings.HasPrefix(proxyPass, "https://") {
  91. // Handle URLs with nginx variables by extracting the base URL before variables
  92. baseURL := proxyPass
  93. if dollarIndex := strings.Index(proxyPass, "$"); dollarIndex != -1 {
  94. baseURL = proxyPass[:dollarIndex]
  95. }
  96. if parsedURL, err := url.Parse(baseURL); err == nil {
  97. host := parsedURL.Hostname()
  98. port := parsedURL.Port()
  99. // Set default ports if not specified
  100. if port == "" {
  101. if parsedURL.Scheme == "https" {
  102. port = "443"
  103. } else {
  104. port = "80"
  105. }
  106. }
  107. // Skip if this is the HTTP challenge port used by Let's Encrypt
  108. if host == "127.0.0.1" && port == settings.CertSettings.HTTPChallengePort {
  109. return ProxyTarget{}
  110. }
  111. return ProxyTarget{
  112. Host: host,
  113. Port: port,
  114. Type: "proxy_pass",
  115. }
  116. }
  117. }
  118. // Handle direct address format for stream module (e.g., "127.0.0.1:8080", "backend.example.com:12345")
  119. // This is used in stream configurations where proxy_pass doesn't require a protocol
  120. if !strings.Contains(proxyPass, "://") {
  121. target := parseServerAddress(proxyPass, "proxy_pass")
  122. // Skip if this is the HTTP challenge port used by Let's Encrypt
  123. if target.Host == "127.0.0.1" && target.Port == settings.CertSettings.HTTPChallengePort {
  124. return ProxyTarget{}
  125. }
  126. return target
  127. }
  128. return ProxyTarget{}
  129. }
  130. // parseServerAddress parses upstream server address
  131. func parseServerAddress(serverAddr string, targetType string) ProxyTarget {
  132. serverAddr = strings.TrimSpace(serverAddr)
  133. // Remove additional parameters (weight, max_fails, etc.)
  134. parts := strings.Fields(serverAddr)
  135. if len(parts) == 0 {
  136. return ProxyTarget{}
  137. }
  138. addr := parts[0]
  139. // Handle IPv6 addresses
  140. if strings.HasPrefix(addr, "[") {
  141. // IPv6 format: [::1]:8080
  142. if idx := strings.LastIndex(addr, "]:"); idx != -1 {
  143. host := addr[1:idx]
  144. port := addr[idx+2:]
  145. // Skip if this is the HTTP challenge port used by Let's Encrypt
  146. if host == "::1" && port == settings.CertSettings.HTTPChallengePort {
  147. return ProxyTarget{}
  148. }
  149. return ProxyTarget{
  150. Host: host,
  151. Port: port,
  152. Type: targetType,
  153. }
  154. }
  155. // IPv6 without port: [::1]
  156. host := strings.Trim(addr, "[]")
  157. return ProxyTarget{
  158. Host: host,
  159. Port: "80",
  160. Type: targetType,
  161. }
  162. }
  163. // Handle IPv4 addresses and hostnames
  164. if strings.Contains(addr, ":") {
  165. parts := strings.Split(addr, ":")
  166. if len(parts) == 2 {
  167. // Skip if this is the HTTP challenge port used by Let's Encrypt
  168. if parts[0] == "127.0.0.1" && parts[1] == settings.CertSettings.HTTPChallengePort {
  169. return ProxyTarget{}
  170. }
  171. return ProxyTarget{
  172. Host: parts[0],
  173. Port: parts[1],
  174. Type: targetType,
  175. }
  176. }
  177. }
  178. // No port specified, use default
  179. return ProxyTarget{
  180. Host: addr,
  181. Port: "80",
  182. Type: targetType,
  183. }
  184. }
  185. // deduplicateTargets removes duplicate proxy targets
  186. func deduplicateTargets(targets []ProxyTarget) []ProxyTarget {
  187. seen := make(map[string]bool)
  188. var result []ProxyTarget
  189. for _, target := range targets {
  190. key := target.Host + ":" + target.Port + ":" + target.Type
  191. if !seen[key] {
  192. seen[key] = true
  193. result = append(result, target)
  194. }
  195. }
  196. return result
  197. }
  198. // isUpstreamReference checks if a proxy_pass URL references an upstream block
  199. func isUpstreamReference(proxyPass string, upstreamNames map[string]bool) bool {
  200. proxyPass = strings.TrimSpace(proxyPass)
  201. // For HTTP/HTTPS URLs, parse the URL to extract the hostname
  202. if strings.HasPrefix(proxyPass, "http://") || strings.HasPrefix(proxyPass, "https://") {
  203. // Handle URLs with nginx variables (e.g., "https://myUpStr$request_uri")
  204. // Extract the scheme and hostname part before any nginx variables
  205. schemeAndHost := proxyPass
  206. if dollarIndex := strings.Index(proxyPass, "$"); dollarIndex != -1 {
  207. schemeAndHost = proxyPass[:dollarIndex]
  208. }
  209. // Try to parse the URL, if it fails, try manual extraction
  210. if parsedURL, err := url.Parse(schemeAndHost); err == nil {
  211. hostname := parsedURL.Hostname()
  212. // Check if the hostname matches any upstream name
  213. return upstreamNames[hostname]
  214. } else {
  215. // Fallback: manually extract hostname for URLs with variables
  216. // Remove scheme prefix
  217. withoutScheme := proxyPass
  218. if strings.HasPrefix(proxyPass, "https://") {
  219. withoutScheme = strings.TrimPrefix(proxyPass, "https://")
  220. } else if strings.HasPrefix(proxyPass, "http://") {
  221. withoutScheme = strings.TrimPrefix(proxyPass, "http://")
  222. }
  223. // Extract hostname before any path, port, or variable
  224. hostname := withoutScheme
  225. if slashIndex := strings.Index(hostname, "/"); slashIndex != -1 {
  226. hostname = hostname[:slashIndex]
  227. }
  228. if colonIndex := strings.Index(hostname, ":"); colonIndex != -1 {
  229. hostname = hostname[:colonIndex]
  230. }
  231. if dollarIndex := strings.Index(hostname, "$"); dollarIndex != -1 {
  232. hostname = hostname[:dollarIndex]
  233. }
  234. return upstreamNames[hostname]
  235. }
  236. }
  237. // For stream module, proxy_pass can directly reference upstream name without protocol
  238. // Check if the proxy_pass value directly matches an upstream name
  239. if !strings.Contains(proxyPass, "://") && !strings.Contains(proxyPass, ":") {
  240. return upstreamNames[proxyPass]
  241. }
  242. return false
  243. }