redirection.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package redirection
  2. import (
  3. "encoding/json"
  4. "log"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. "imuslab.com/zoraxy/mod/info/logger"
  12. "imuslab.com/zoraxy/mod/utils"
  13. )
  14. type RuleTable struct {
  15. AllowRegex bool //Allow regular expression to be used in rule matching. Require up to O(n^m) time complexity
  16. Logger *logger.Logger
  17. configPath string //The location where the redirection rules is stored
  18. rules sync.Map //Store the redirection rules for this reverse proxy instance
  19. }
  20. type RedirectRules struct {
  21. RedirectURL string //The matching URL to redirect
  22. TargetURL string //The destination redirection url
  23. ForwardChildpath bool //Also redirect the pathname
  24. StatusCode int //Status Code for redirection
  25. }
  26. func NewRuleTable(configPath string, allowRegex bool, logger *logger.Logger) (*RuleTable, error) {
  27. thisRuleTable := RuleTable{
  28. rules: sync.Map{},
  29. configPath: configPath,
  30. AllowRegex: allowRegex,
  31. Logger: logger,
  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. thisRuleTable.log("Redirection rule added: "+rule.RedirectURL+" -> "+rule.TargetURL, nil)
  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. t.log("Error creating file "+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. t.log("Error encoding JSON to file "+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. // Edit an existing redirection rule, the oldRedirectURL is used to find the rule to be edited
  93. func (t *RuleTable) EditRedirectRule(oldRedirectURL string, newRedirectURL string, destURL string, forwardPathname bool, statusCode int) error {
  94. newRule := &RedirectRules{
  95. RedirectURL: newRedirectURL,
  96. TargetURL: destURL,
  97. ForwardChildpath: forwardPathname,
  98. StatusCode: statusCode,
  99. }
  100. //Remove the old rule
  101. t.DeleteRedirectRule(oldRedirectURL)
  102. // Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
  103. filename := utils.ReplaceSpecialCharacters(newRedirectURL) + ".json"
  104. filepath := path.Join(t.configPath, filename)
  105. // Create a new file for writing the JSON data
  106. file, err := os.Create(filepath)
  107. if err != nil {
  108. t.log("Error creating file "+filepath, err)
  109. return err
  110. }
  111. defer file.Close()
  112. err = json.NewEncoder(file).Encode(newRule)
  113. if err != nil {
  114. t.log("Error encoding JSON to file "+filepath, err)
  115. return err
  116. }
  117. // Update the runtime map
  118. t.rules.Store(newRedirectURL, newRule)
  119. return nil
  120. }
  121. func (t *RuleTable) DeleteRedirectRule(redirectURL string) error {
  122. // Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
  123. filename := utils.ReplaceSpecialCharacters(redirectURL) + ".json"
  124. // Create the full file path by joining the t.configPath with the filename
  125. filepath := path.Join(t.configPath, filename)
  126. // Check if the file exists
  127. if _, err := os.Stat(filepath); os.IsNotExist(err) {
  128. return nil // File doesn't exist, nothing to delete
  129. }
  130. // Delete the file
  131. if err := os.Remove(filepath); err != nil {
  132. t.log("Error deleting file "+filepath, err)
  133. return err
  134. }
  135. // Delete the key-value pair from the sync.Map
  136. t.rules.Delete(redirectURL)
  137. return nil
  138. }
  139. // Get a list of all the redirection rules
  140. func (t *RuleTable) GetAllRedirectRules() []*RedirectRules {
  141. rules := []*RedirectRules{}
  142. t.rules.Range(func(key, value interface{}) bool {
  143. r, ok := value.(*RedirectRules)
  144. if ok {
  145. rules = append(rules, r)
  146. }
  147. return true
  148. })
  149. return rules
  150. }
  151. // Check if a given request URL matched any of the redirection rule
  152. func (t *RuleTable) MatchRedirectRule(requestedURL string) *RedirectRules {
  153. // Iterate through all the keys in the rules map
  154. var targetRedirectionRule *RedirectRules = nil
  155. var maxMatch int = 0
  156. t.rules.Range(func(key interface{}, value interface{}) bool {
  157. // Check if the requested URL starts with the key as a prefix
  158. if t.AllowRegex {
  159. //Regexp matching rule
  160. matched, err := regexp.MatchString(key.(string), requestedURL)
  161. if err != nil {
  162. //Something wrong with the regex?
  163. t.log("Unable to match regex", err)
  164. return true
  165. }
  166. if matched {
  167. maxMatch = len(key.(string))
  168. targetRedirectionRule = value.(*RedirectRules)
  169. }
  170. } else {
  171. //Default: prefix matching redirect
  172. if strings.HasPrefix(requestedURL, key.(string)) {
  173. // This request URL matched the domain
  174. if len(key.(string)) > maxMatch {
  175. maxMatch = len(key.(string))
  176. targetRedirectionRule = value.(*RedirectRules)
  177. }
  178. }
  179. }
  180. return true
  181. })
  182. return targetRedirectionRule
  183. }
  184. // Log the message to log file, use STDOUT if logger not set
  185. func (t *RuleTable) log(message string, err error) {
  186. if t.Logger == nil {
  187. if err == nil {
  188. log.Println("[Redirect] " + message)
  189. } else {
  190. log.Println("[Redirect] " + message + ": " + err.Error())
  191. }
  192. } else {
  193. t.Logger.PrintAndLog("redirect", message, err)
  194. }
  195. }