redirection.go 5.3 KB

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