access.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. //Assign default access rule parent
  64. thisController.DefaultAccessRule.parent = &thisController
  65. //Load all acccess rules from file
  66. configFiles, err := filepath.Glob(options.ConfigFolder + "/*.json")
  67. if err != nil {
  68. return nil, err
  69. }
  70. ProxyAccessRules := sync.Map{}
  71. for _, configFile := range configFiles {
  72. if filepath.Base(configFile) == "default.json" {
  73. //Skip this, as this was already loaded as default
  74. continue
  75. }
  76. configContent, err := os.ReadFile(configFile)
  77. if err != nil {
  78. options.Logger.PrintAndLog("Access", "Unable to load config "+filepath.Base(configFile), err)
  79. continue
  80. }
  81. //Parse the config file into AccessRule
  82. thisAccessRule := AccessRule{}
  83. err = json.Unmarshal(configContent, &thisAccessRule)
  84. if err != nil {
  85. options.Logger.PrintAndLog("Access", "Unable to parse config "+filepath.Base(configFile), err)
  86. continue
  87. }
  88. thisAccessRule.parent = &thisController
  89. ProxyAccessRules.Store(thisAccessRule.ID, &thisAccessRule)
  90. }
  91. thisController.ProxyAccessRule = &ProxyAccessRules
  92. return &thisController, nil
  93. }
  94. // Get the global access rule
  95. func (c *Controller) GetGlobalAccessRule() (*AccessRule, error) {
  96. if c.DefaultAccessRule == nil {
  97. return nil, errors.New("global access rule is not set")
  98. }
  99. return c.DefaultAccessRule, nil
  100. }
  101. // Load access rules to runtime, require rule ID
  102. func (c *Controller) GetAccessRuleByID(accessRuleID string) (*AccessRule, error) {
  103. if accessRuleID == "default" || accessRuleID == "" {
  104. return c.DefaultAccessRule, nil
  105. }
  106. //Load from sync.Map, should be O(1)
  107. targetRule, ok := c.ProxyAccessRule.Load(accessRuleID)
  108. if !ok {
  109. return nil, errors.New("target access rule not exists")
  110. }
  111. ar, ok := targetRule.(*AccessRule)
  112. if !ok {
  113. return nil, errors.New("assertion of access rule failed, version too old?")
  114. }
  115. return ar, nil
  116. }
  117. // Return all the access rules currently in runtime, including default
  118. func (c *Controller) ListAllAccessRules() []*AccessRule {
  119. results := []*AccessRule{c.DefaultAccessRule}
  120. c.ProxyAccessRule.Range(func(key, value interface{}) bool {
  121. results = append(results, value.(*AccessRule))
  122. return true
  123. })
  124. return results
  125. }
  126. // Check if an access rule exists given the rule id
  127. func (c *Controller) AccessRuleExists(ruleID string) bool {
  128. r, _ := c.GetAccessRuleByID(ruleID)
  129. if r != nil {
  130. //An access rule with identical ID exists
  131. return true
  132. }
  133. return false
  134. }
  135. // Add a new access rule to runtime and save it to file
  136. func (c *Controller) AddNewAccessRule(newRule *AccessRule) error {
  137. r, _ := c.GetAccessRuleByID(newRule.ID)
  138. if r != nil {
  139. //An access rule with identical ID exists
  140. return errors.New("access rule already exists")
  141. }
  142. //Check if the blacklist and whitelist are populated with empty map
  143. if newRule.BlackListContryCode == nil {
  144. newRule.BlackListContryCode = &map[string]string{}
  145. }
  146. if newRule.BlackListIP == nil {
  147. newRule.BlackListIP = &map[string]string{}
  148. }
  149. if newRule.WhiteListCountryCode == nil {
  150. newRule.WhiteListCountryCode = &map[string]string{}
  151. }
  152. if newRule.WhiteListIP == nil {
  153. newRule.WhiteListIP = &map[string]string{}
  154. }
  155. //Add access rule to runtime
  156. newRule.parent = c
  157. c.ProxyAccessRule.Store(newRule.ID, newRule)
  158. //Save rule to file
  159. newRule.SaveChanges()
  160. return nil
  161. }
  162. // Update the access rule meta info.
  163. func (c *Controller) UpdateAccessRule(ruleID string, name string, desc string) error {
  164. targetAccessRule, err := c.GetAccessRuleByID(ruleID)
  165. if err != nil {
  166. return err
  167. }
  168. ///Update the name and desc
  169. targetAccessRule.Name = name
  170. targetAccessRule.Desc = desc
  171. //Overwrite the rule currently in sync map
  172. if ruleID == "default" {
  173. c.DefaultAccessRule = targetAccessRule
  174. } else {
  175. c.ProxyAccessRule.Store(ruleID, targetAccessRule)
  176. }
  177. return targetAccessRule.SaveChanges()
  178. }
  179. // Remove the access rule by its id
  180. func (c *Controller) RemoveAccessRuleByID(ruleID string) error {
  181. if !c.AccessRuleExists(ruleID) {
  182. return errors.New("access rule not exists")
  183. }
  184. //Default cannot be removed
  185. if ruleID == "default" {
  186. return errors.New("default access rule cannot be removed")
  187. }
  188. //Remove it
  189. return c.DeleteAccessRuleByID(ruleID)
  190. }