nginx_log.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package nginx_log
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "regexp"
  7. "strings"
  8. "github.com/0xJacky/Nginx-UI/internal/cache"
  9. "github.com/0xJacky/Nginx-UI/internal/helper"
  10. "github.com/0xJacky/Nginx-UI/internal/nginx"
  11. "github.com/0xJacky/Nginx-UI/settings"
  12. "github.com/uozi-tech/cosy/logger"
  13. )
  14. // Regular expression for log directives - matches access_log or error_log
  15. var logDirectiveRegex = regexp.MustCompile(`(?m)(access_log|error_log)\s+([^\s;]+)(?:\s+[^;]+)?;`)
  16. // Use init function to automatically register callback
  17. func init() {
  18. // Register the callback directly with the global registry
  19. cache.RegisterCallback(scanForLogDirectives)
  20. }
  21. // scanForLogDirectives scans and parses configuration files for log directives
  22. func scanForLogDirectives(configPath string, content []byte) error {
  23. // First, remove all log paths that came from this config file
  24. // This ensures that removed log directives are properly cleaned up
  25. RemoveLogPathsFromConfig(configPath)
  26. // Find log directives using regex
  27. matches := logDirectiveRegex.FindAllSubmatch(content, -1)
  28. prefix := nginx.GetPrefix()
  29. // Parse log paths
  30. for _, match := range matches {
  31. if len(match) >= 3 {
  32. // Check if this match is from a commented line
  33. if isCommentedMatch(content, match) {
  34. continue // Skip commented directives
  35. }
  36. directiveType := string(match[1]) // "access_log" or "error_log"
  37. logPath := string(match[2]) // Path to log file
  38. // Handle relative paths by joining with nginx prefix
  39. if !filepath.IsAbs(logPath) {
  40. logPath = filepath.Join(prefix, logPath)
  41. }
  42. // Validate log path
  43. if isValidLogPath(logPath) {
  44. logType := "access"
  45. if directiveType == "error_log" {
  46. logType = "error"
  47. }
  48. // Add to cache with config file path
  49. AddLogPath(logPath, logType, filepath.Base(logPath), configPath)
  50. }
  51. }
  52. }
  53. return nil
  54. }
  55. // isCommentedMatch checks if a regex match is from a commented line
  56. func isCommentedMatch(content []byte, match [][]byte) bool {
  57. // Find the position of the match in the content
  58. matchStr := string(match[0])
  59. matchIndex := strings.Index(string(content), matchStr)
  60. if matchIndex == -1 {
  61. return false
  62. }
  63. // Find the start of the line containing this match
  64. lineStart := matchIndex
  65. for lineStart > 0 && content[lineStart-1] != '\n' {
  66. lineStart--
  67. }
  68. // Check if the line starts with # (possibly with leading whitespace)
  69. for i := lineStart; i < matchIndex; i++ {
  70. char := content[i]
  71. if char == '#' {
  72. return true // This is a commented line
  73. }
  74. if char != ' ' && char != '\t' {
  75. return false // Found non-whitespace before the directive, not a comment
  76. }
  77. }
  78. return false
  79. }
  80. // GetAllLogs returns all log paths
  81. func GetAllLogs(filters ...func(*NginxLogCache) bool) []*NginxLogCache {
  82. return GetAllLogPaths(filters...)
  83. }
  84. // isValidLogPath checks if a log path is valid:
  85. // 1. It must be a regular file or a symlink to a regular file
  86. // 2. It must not point to a console or special device
  87. // 3. It must be under the whitelist directories
  88. func isValidLogPath(logPath string) bool {
  89. // First check if the path is in the whitelist
  90. if !IsLogPathUnderWhiteList(logPath) {
  91. logger.Warn("Log path is not under whitelist:", logPath)
  92. return false
  93. }
  94. // Check if the path exists
  95. fileInfo, err := os.Lstat(logPath)
  96. if err != nil {
  97. // If the file doesn't exist, it might be created later
  98. // We'll assume it's valid for now
  99. return true
  100. }
  101. // If it's a symlink, follow it safely
  102. if fileInfo.Mode()&os.ModeSymlink != 0 {
  103. // Use EvalSymlinks to safely resolve the entire symlink chain
  104. // This function detects circular symlinks and returns an error
  105. resolvedPath, err := filepath.EvalSymlinks(logPath)
  106. if err != nil {
  107. logger.Warn("Failed to resolve symlink (possible circular reference):", logPath, "error:", err)
  108. return false
  109. }
  110. // Check the resolved target file
  111. targetInfo, err := os.Stat(resolvedPath)
  112. if err != nil {
  113. return false
  114. }
  115. // Only accept regular files as targets
  116. return targetInfo.Mode().IsRegular()
  117. }
  118. // For non-symlinks, just check if it's a regular file
  119. return fileInfo.Mode().IsRegular()
  120. }
  121. // IsLogPathUnderWhiteList checks if a log path is under one of the paths in LogDirWhiteList
  122. func IsLogPathUnderWhiteList(path string) bool {
  123. cacheKey := fmt.Sprintf("isLogPathUnderWhiteList:%s", path)
  124. res, ok := cache.Get(cacheKey)
  125. // If cached, return the result directly
  126. if ok {
  127. return res.(bool)
  128. }
  129. // Only build the whitelist when cache miss occurs
  130. logDirWhiteList := append([]string{}, settings.NginxSettings.LogDirWhiteList...)
  131. accessLogPath := nginx.GetAccessLogPath()
  132. errorLogPath := nginx.GetErrorLogPath()
  133. if accessLogPath != "" {
  134. logDirWhiteList = append(logDirWhiteList, filepath.Dir(accessLogPath))
  135. }
  136. if errorLogPath != "" {
  137. logDirWhiteList = append(logDirWhiteList, filepath.Dir(errorLogPath))
  138. }
  139. if nginx.GetPrefix() != "" {
  140. logDirWhiteList = append(logDirWhiteList, nginx.GetPrefix())
  141. }
  142. // Check if path is under any whitelist directory
  143. for _, whitePath := range logDirWhiteList {
  144. if helper.IsUnderDirectory(path, whitePath) {
  145. cache.Set(cacheKey, true, 0)
  146. return true
  147. }
  148. }
  149. // Cache negative result as well to avoid repeated checks
  150. cache.Set(cacheKey, false, 0)
  151. return false
  152. }