access.go 6.0 KB

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