redirection.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package redirection
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "regexp"
  10. "strings"
  11. "sync"
  12. "imuslab.com/zoraxy/mod/info/logger"
  13. "imuslab.com/zoraxy/mod/utils"
  14. )
  15. type RuleTable struct {
  16. AllowRegex bool //Allow regular expression to be used in rule matching. Require up to O(n^m) time complexity
  17. Logger *logger.Logger
  18. configPath string //The location where the redirection rules is stored
  19. rules sync.Map //Store the redirection rules for this reverse proxy instance
  20. }
  21. type RedirectRules struct {
  22. RedirectURL string //The matching URL to redirect
  23. TargetURL string //The destination redirection url
  24. ForwardChildpath bool //Also redirect the pathname
  25. StatusCode int //Status Code for redirection
  26. }
  27. func NewRuleTable(configPath string, allowRegex bool) (*RuleTable, error) {
  28. thisRuleTable := RuleTable{
  29. rules: sync.Map{},
  30. configPath: configPath,
  31. AllowRegex: allowRegex,
  32. }
  33. //Load all the rules from the config path
  34. if !utils.FileExists(configPath) {
  35. os.MkdirAll(configPath, 0775)
  36. }
  37. // Load all the *.json from the configPath
  38. files, err := filepath.Glob(filepath.Join(configPath, "*.json"))
  39. if err != nil {
  40. return nil, err
  41. }
  42. // Parse the json content into RedirectRules
  43. var rules []*RedirectRules
  44. for _, file := range files {
  45. b, err := os.ReadFile(file)
  46. if err != nil {
  47. continue
  48. }
  49. thisRule := RedirectRules{}
  50. err = json.Unmarshal(b, &thisRule)
  51. if err != nil {
  52. continue
  53. }
  54. rules = append(rules, &thisRule)
  55. }
  56. //Map the rules into the sync map
  57. for _, rule := range rules {
  58. log.Println("Redirection rule added: " + rule.RedirectURL + " -> " + rule.TargetURL)
  59. thisRuleTable.rules.Store(rule.RedirectURL, rule)
  60. }
  61. return &thisRuleTable, nil
  62. }
  63. func (t *RuleTable) AddRedirectRule(redirectURL string, destURL string, forwardPathname bool, statusCode int) error {
  64. // Create a new RedirectRules object with the given parameters
  65. newRule := &RedirectRules{
  66. RedirectURL: redirectURL,
  67. TargetURL: destURL,
  68. ForwardChildpath: forwardPathname,
  69. StatusCode: statusCode,
  70. }
  71. // Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
  72. filename := utils.ReplaceSpecialCharacters(redirectURL) + ".json"
  73. // Create the full file path by joining the t.configPath with the filename
  74. filepath := path.Join(t.configPath, filename)
  75. // Create a new file for writing the JSON data
  76. file, err := os.Create(filepath)
  77. if err != nil {
  78. log.Printf("Error creating file %s: %s", filepath, err)
  79. return err
  80. }
  81. defer file.Close()
  82. // Encode the RedirectRules object to JSON and write it to the file
  83. err = json.NewEncoder(file).Encode(newRule)
  84. if err != nil {
  85. log.Printf("Error encoding JSON to file %s: %s", filepath, err)
  86. return err
  87. }
  88. // Store the RedirectRules object in the sync.Map
  89. t.rules.Store(redirectURL, newRule)
  90. return nil
  91. }
  92. func (t *RuleTable) DeleteRedirectRule(redirectURL string) error {
  93. // Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
  94. filename := utils.ReplaceSpecialCharacters(redirectURL) + ".json"
  95. // Create the full file path by joining the t.configPath with the filename
  96. filepath := path.Join(t.configPath, filename)
  97. fmt.Println(redirectURL, filename, filepath)
  98. // Check if the file exists
  99. if _, err := os.Stat(filepath); os.IsNotExist(err) {
  100. return nil // File doesn't exist, nothing to delete
  101. }
  102. // Delete the file
  103. if err := os.Remove(filepath); err != nil {
  104. log.Printf("Error deleting file %s: %s", filepath, err)
  105. return err
  106. }
  107. // Delete the key-value pair from the sync.Map
  108. t.rules.Delete(redirectURL)
  109. return nil
  110. }
  111. // Get a list of all the redirection rules
  112. func (t *RuleTable) GetAllRedirectRules() []*RedirectRules {
  113. rules := []*RedirectRules{}
  114. t.rules.Range(func(key, value interface{}) bool {
  115. r, ok := value.(*RedirectRules)
  116. if ok {
  117. rules = append(rules, r)
  118. }
  119. return true
  120. })
  121. return rules
  122. }
  123. // Check if a given request URL matched any of the redirection rule
  124. func (t *RuleTable) MatchRedirectRule(requestedURL string) *RedirectRules {
  125. // Iterate through all the keys in the rules map
  126. var targetRedirectionRule *RedirectRules = nil
  127. var maxMatch int = 0
  128. t.rules.Range(func(key interface{}, value interface{}) bool {
  129. // Check if the requested URL starts with the key as a prefix
  130. if t.AllowRegex {
  131. //Regexp matching rule
  132. matched, err := regexp.MatchString(key.(string), requestedURL)
  133. if err != nil {
  134. //Something wrong with the regex?
  135. t.log("Unable to match regex", err)
  136. return true
  137. }
  138. if matched {
  139. maxMatch = len(key.(string))
  140. targetRedirectionRule = value.(*RedirectRules)
  141. }
  142. } else {
  143. //Default: prefix matching redirect
  144. if strings.HasPrefix(requestedURL, key.(string)) {
  145. // This request URL matched the domain
  146. if len(key.(string)) > maxMatch {
  147. maxMatch = len(key.(string))
  148. targetRedirectionRule = value.(*RedirectRules)
  149. }
  150. }
  151. }
  152. return true
  153. })
  154. return targetRedirectionRule
  155. }
  156. // Log the message to log file, use STDOUT if logger not set
  157. func (t *RuleTable) log(message string, err error) {
  158. if t.Logger == nil {
  159. if err == nil {
  160. log.Println("[Redirect] " + message)
  161. } else {
  162. log.Println("[Redirect] " + message + ": " + err.Error())
  163. }
  164. } else {
  165. t.Logger.PrintAndLog("Redirect", message, err)
  166. }
  167. }