access.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package access
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. "imuslab.com/zoraxy/mod/utils"
  9. )
  10. /*
  11. Access.go
  12. This module is the new version of access control system
  13. where now the blacklist / whitelist are seperated from
  14. geodb module
  15. */
  16. // Create a new access controller to handle blacklist / whitelist
  17. func NewAccessController(options *Options) (*Controller, error) {
  18. sysdb := options.Database
  19. if sysdb == nil {
  20. return nil, errors.New("missing database access")
  21. }
  22. //Create the config folder if not exists
  23. confFolder := options.ConfigFolder
  24. if !utils.FileExists(confFolder) {
  25. err := os.MkdirAll(confFolder, 0775)
  26. if err != nil {
  27. return nil, err
  28. }
  29. }
  30. // Create the global access rule if not exists
  31. var defaultAccessRule = AccessRule{
  32. ID: "default",
  33. Name: "Default",
  34. Desc: "Default access rule for all HTTP proxy hosts",
  35. BlacklistEnabled: false,
  36. WhitelistEnabled: false,
  37. WhiteListCountryCode: &map[string]string{},
  38. WhiteListIP: &map[string]string{},
  39. BlackListContryCode: &map[string]string{},
  40. BlackListIP: &map[string]string{},
  41. }
  42. defaultRuleSettingFile := filepath.Join(confFolder, "default.json")
  43. if utils.FileExists(defaultRuleSettingFile) {
  44. //Load from file
  45. defaultRuleBytes, err := os.ReadFile(defaultRuleSettingFile)
  46. if err == nil {
  47. err = json.Unmarshal(defaultRuleBytes, &defaultAccessRule)
  48. if err != nil {
  49. options.Logger.PrintAndLog("Access", "Unable to parse default routing rule config file. Using default", err)
  50. }
  51. }
  52. } else {
  53. //Create one
  54. js, _ := json.MarshalIndent(defaultAccessRule, "", " ")
  55. os.WriteFile(defaultRuleSettingFile, js, 0775)
  56. }
  57. //Generate a controller object
  58. thisController := Controller{
  59. DefaultAccessRule: &defaultAccessRule,
  60. ProxyAccessRule: &sync.Map{},
  61. Options: options,
  62. }
  63. //Load all acccess rules from file
  64. configFiles, err := filepath.Glob(options.ConfigFolder + "/*.json")
  65. if err != nil {
  66. return nil, err
  67. }
  68. ProxyAccessRules := sync.Map{}
  69. for _, configFile := range configFiles {
  70. if filepath.Base(configFile) == "default.json" {
  71. //Skip this, as this was already loaded as default
  72. continue
  73. }
  74. configContent, err := os.ReadFile(configFile)
  75. if err != nil {
  76. options.Logger.PrintAndLog("Access", "Unable to load config "+filepath.Base(configFile), err)
  77. continue
  78. }
  79. //Parse the config file into AccessRule
  80. thisAccessRule := AccessRule{}
  81. err = json.Unmarshal(configContent, &thisAccessRule)
  82. if err != nil {
  83. options.Logger.PrintAndLog("Access", "Unable to parse config "+filepath.Base(configFile), err)
  84. continue
  85. }
  86. thisAccessRule.parent = &thisController
  87. ProxyAccessRules.Store(thisAccessRule.ID, &thisAccessRule)
  88. }
  89. thisController.ProxyAccessRule = &ProxyAccessRules
  90. return &thisController, nil
  91. }
  92. // Get the global access rule
  93. func (c *Controller) GetGlobalAccessRule() (*AccessRule, error) {
  94. if c.DefaultAccessRule == nil {
  95. return nil, errors.New("global access rule is not set")
  96. }
  97. return c.DefaultAccessRule, nil
  98. }
  99. // Load access rules to runtime, require rule ID
  100. func (c *Controller) GetAccessRuleByID(accessRuleID string) (*AccessRule, error) {
  101. if accessRuleID == "default" || accessRuleID == "" {
  102. return c.DefaultAccessRule, nil
  103. }
  104. //Load from sync.Map, should be O(1)
  105. targetRule, ok := c.ProxyAccessRule.Load(accessRuleID)
  106. if !ok {
  107. return nil, errors.New("target access rule not exists")
  108. }
  109. ar, ok := targetRule.(*AccessRule)
  110. if !ok {
  111. return nil, errors.New("assertion of access rule failed, version too old?")
  112. }
  113. return ar, nil
  114. }
  115. // Return all the access rules currently in runtime, including default
  116. func (c *Controller) ListAllAccessRules() []*AccessRule {
  117. results := []*AccessRule{c.DefaultAccessRule}
  118. c.ProxyAccessRule.Range(func(key, value interface{}) bool {
  119. results = append(results, value.(*AccessRule))
  120. return true
  121. })
  122. return results
  123. }
  124. // Check if an access rule exists given the rule id
  125. func (c *Controller) AccessRuleExists(ruleID string) bool {
  126. r, _ := c.GetAccessRuleByID(ruleID)
  127. if r != nil {
  128. //An access rule with identical ID exists
  129. return true
  130. }
  131. return false
  132. }
  133. // Add a new access rule to runtime and save it to file
  134. func (c *Controller) AddNewAccessRule(newRule *AccessRule) error {
  135. r, _ := c.GetAccessRuleByID(newRule.ID)
  136. if r != nil {
  137. //An access rule with identical ID exists
  138. return errors.New("access rule already exists")
  139. }
  140. //Check if the blacklist and whitelist are populated with empty map
  141. if newRule.BlackListContryCode == nil {
  142. newRule.BlackListContryCode = &map[string]string{}
  143. }
  144. if newRule.BlackListIP == nil {
  145. newRule.BlackListIP = &map[string]string{}
  146. }
  147. if newRule.WhiteListCountryCode == nil {
  148. newRule.WhiteListCountryCode = &map[string]string{}
  149. }
  150. if newRule.WhiteListIP == nil {
  151. newRule.WhiteListIP = &map[string]string{}
  152. }
  153. //Add access rule to runtime
  154. newRule.parent = c
  155. c.ProxyAccessRule.Store(newRule.ID, newRule)
  156. //Save rule to file
  157. newRule.SaveChanges()
  158. return nil
  159. }
  160. // Update the access rule meta info.
  161. func (c *Controller) UpdateAccessRule(ruleID string, name string, desc string) error {
  162. targetAccessRule, err := c.GetAccessRuleByID(ruleID)
  163. if err != nil {
  164. return err
  165. }
  166. ///Update the name and desc
  167. targetAccessRule.Name = name
  168. targetAccessRule.Desc = desc
  169. //Overwrite the rule currently in sync map
  170. if ruleID == "default" {
  171. c.DefaultAccessRule = targetAccessRule
  172. } else {
  173. c.ProxyAccessRule.Store(ruleID, targetAccessRule)
  174. }
  175. return targetAccessRule.SaveChanges()
  176. }
  177. // Remove the access rule by its id
  178. func (c *Controller) RemoveAccessRuleByID(ruleID string) error {
  179. if !c.AccessRuleExists(ruleID) {
  180. return errors.New("access rule not exists")
  181. }
  182. //Default cannot be removed
  183. if ruleID == "default" {
  184. return errors.New("default access rule cannot be removed")
  185. }
  186. //Remove it
  187. return c.DeleteAccessRuleByID(ruleID)
  188. }