cache.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package cachefile
  2. import (
  3. "context"
  4. "errors"
  5. "net/netip"
  6. "os"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/sagernet/bbolt"
  11. bboltErrors "github.com/sagernet/bbolt/errors"
  12. "github.com/sagernet/sing-box/adapter"
  13. "github.com/sagernet/sing-box/option"
  14. "github.com/sagernet/sing/common"
  15. E "github.com/sagernet/sing/common/exceptions"
  16. "github.com/sagernet/sing/service/filemanager"
  17. )
  18. var (
  19. bucketSelected = []byte("selected")
  20. bucketExpand = []byte("group_expand")
  21. bucketMode = []byte("clash_mode")
  22. bucketRuleSet = []byte("rule_set")
  23. bucketNameList = []string{
  24. string(bucketSelected),
  25. string(bucketExpand),
  26. string(bucketMode),
  27. string(bucketRuleSet),
  28. string(bucketRDRC),
  29. }
  30. cacheIDDefault = []byte("default")
  31. )
  32. var _ adapter.CacheFile = (*CacheFile)(nil)
  33. type CacheFile struct {
  34. ctx context.Context
  35. path string
  36. cacheID []byte
  37. storeFakeIP bool
  38. storeRDRC bool
  39. rdrcTimeout time.Duration
  40. DB *bbolt.DB
  41. saveMetadataTimer *time.Timer
  42. saveFakeIPAccess sync.RWMutex
  43. saveDomain map[netip.Addr]string
  44. saveAddress4 map[string]netip.Addr
  45. saveAddress6 map[string]netip.Addr
  46. saveRDRCAccess sync.RWMutex
  47. saveRDRC map[saveRDRCCacheKey]bool
  48. }
  49. type saveRDRCCacheKey struct {
  50. TransportName string
  51. QuestionName string
  52. }
  53. func New(ctx context.Context, options option.CacheFileOptions) *CacheFile {
  54. var path string
  55. if options.Path != "" {
  56. path = options.Path
  57. } else {
  58. path = "cache.db"
  59. }
  60. var cacheIDBytes []byte
  61. if options.CacheID != "" {
  62. cacheIDBytes = append([]byte{0}, []byte(options.CacheID)...)
  63. }
  64. var rdrcTimeout time.Duration
  65. if options.StoreRDRC {
  66. if options.RDRCTimeout > 0 {
  67. rdrcTimeout = time.Duration(options.RDRCTimeout)
  68. } else {
  69. rdrcTimeout = 7 * 24 * time.Hour
  70. }
  71. }
  72. return &CacheFile{
  73. ctx: ctx,
  74. path: filemanager.BasePath(ctx, path),
  75. cacheID: cacheIDBytes,
  76. storeFakeIP: options.StoreFakeIP,
  77. storeRDRC: options.StoreRDRC,
  78. rdrcTimeout: rdrcTimeout,
  79. saveDomain: make(map[netip.Addr]string),
  80. saveAddress4: make(map[string]netip.Addr),
  81. saveAddress6: make(map[string]netip.Addr),
  82. saveRDRC: make(map[saveRDRCCacheKey]bool),
  83. }
  84. }
  85. func (c *CacheFile) start() error {
  86. const fileMode = 0o666
  87. options := bbolt.Options{Timeout: time.Second}
  88. var (
  89. db *bbolt.DB
  90. err error
  91. )
  92. for i := 0; i < 10; i++ {
  93. db, err = bbolt.Open(c.path, fileMode, &options)
  94. if err == nil {
  95. break
  96. }
  97. if errors.Is(err, bboltErrors.ErrTimeout) {
  98. continue
  99. }
  100. if E.IsMulti(err, bboltErrors.ErrInvalid, bboltErrors.ErrChecksum, bboltErrors.ErrVersionMismatch) {
  101. rmErr := os.Remove(c.path)
  102. if rmErr != nil {
  103. return err
  104. }
  105. }
  106. time.Sleep(100 * time.Millisecond)
  107. }
  108. if err != nil {
  109. return err
  110. }
  111. err = filemanager.Chown(c.ctx, c.path)
  112. if err != nil {
  113. db.Close()
  114. return E.Cause(err, "platform chown")
  115. }
  116. err = db.Batch(func(tx *bbolt.Tx) error {
  117. return tx.ForEach(func(name []byte, b *bbolt.Bucket) error {
  118. if name[0] == 0 {
  119. return b.ForEachBucket(func(k []byte) error {
  120. bucketName := string(k)
  121. if !(common.Contains(bucketNameList, bucketName)) {
  122. _ = b.DeleteBucket(name)
  123. }
  124. return nil
  125. })
  126. } else {
  127. bucketName := string(name)
  128. if !(common.Contains(bucketNameList, bucketName) || strings.HasPrefix(bucketName, fakeipBucketPrefix)) {
  129. _ = tx.DeleteBucket(name)
  130. }
  131. }
  132. return nil
  133. })
  134. })
  135. if err != nil {
  136. db.Close()
  137. return err
  138. }
  139. c.DB = db
  140. return nil
  141. }
  142. func (c *CacheFile) PreStart() error {
  143. return c.start()
  144. }
  145. func (c *CacheFile) Start() error {
  146. return nil
  147. }
  148. func (c *CacheFile) Close() error {
  149. if c.DB == nil {
  150. return nil
  151. }
  152. return c.DB.Close()
  153. }
  154. func (c *CacheFile) StoreFakeIP() bool {
  155. return c.storeFakeIP
  156. }
  157. func (c *CacheFile) LoadMode() string {
  158. var mode string
  159. c.DB.View(func(t *bbolt.Tx) error {
  160. bucket := t.Bucket(bucketMode)
  161. if bucket == nil {
  162. return nil
  163. }
  164. var modeBytes []byte
  165. if len(c.cacheID) > 0 {
  166. modeBytes = bucket.Get(c.cacheID)
  167. } else {
  168. modeBytes = bucket.Get(cacheIDDefault)
  169. }
  170. mode = string(modeBytes)
  171. return nil
  172. })
  173. return mode
  174. }
  175. func (c *CacheFile) StoreMode(mode string) error {
  176. return c.DB.Batch(func(t *bbolt.Tx) error {
  177. bucket, err := t.CreateBucketIfNotExists(bucketMode)
  178. if err != nil {
  179. return err
  180. }
  181. if len(c.cacheID) > 0 {
  182. return bucket.Put(c.cacheID, []byte(mode))
  183. } else {
  184. return bucket.Put(cacheIDDefault, []byte(mode))
  185. }
  186. })
  187. }
  188. func (c *CacheFile) bucket(t *bbolt.Tx, key []byte) *bbolt.Bucket {
  189. if c.cacheID == nil {
  190. return t.Bucket(key)
  191. }
  192. bucket := t.Bucket(c.cacheID)
  193. if bucket == nil {
  194. return nil
  195. }
  196. return bucket.Bucket(key)
  197. }
  198. func (c *CacheFile) createBucket(t *bbolt.Tx, key []byte) (*bbolt.Bucket, error) {
  199. if c.cacheID == nil {
  200. return t.CreateBucketIfNotExists(key)
  201. }
  202. bucket, err := t.CreateBucketIfNotExists(c.cacheID)
  203. if bucket == nil {
  204. return nil, err
  205. }
  206. return bucket.CreateBucketIfNotExists(key)
  207. }
  208. func (c *CacheFile) LoadSelected(group string) string {
  209. var selected string
  210. c.DB.View(func(t *bbolt.Tx) error {
  211. bucket := c.bucket(t, bucketSelected)
  212. if bucket == nil {
  213. return nil
  214. }
  215. selectedBytes := bucket.Get([]byte(group))
  216. if len(selectedBytes) > 0 {
  217. selected = string(selectedBytes)
  218. }
  219. return nil
  220. })
  221. return selected
  222. }
  223. func (c *CacheFile) StoreSelected(group, selected string) error {
  224. return c.DB.Batch(func(t *bbolt.Tx) error {
  225. bucket, err := c.createBucket(t, bucketSelected)
  226. if err != nil {
  227. return err
  228. }
  229. return bucket.Put([]byte(group), []byte(selected))
  230. })
  231. }
  232. func (c *CacheFile) LoadGroupExpand(group string) (isExpand bool, loaded bool) {
  233. c.DB.View(func(t *bbolt.Tx) error {
  234. bucket := c.bucket(t, bucketExpand)
  235. if bucket == nil {
  236. return nil
  237. }
  238. expandBytes := bucket.Get([]byte(group))
  239. if len(expandBytes) == 1 {
  240. isExpand = expandBytes[0] == 1
  241. loaded = true
  242. }
  243. return nil
  244. })
  245. return
  246. }
  247. func (c *CacheFile) StoreGroupExpand(group string, isExpand bool) error {
  248. return c.DB.Batch(func(t *bbolt.Tx) error {
  249. bucket, err := c.createBucket(t, bucketExpand)
  250. if err != nil {
  251. return err
  252. }
  253. if isExpand {
  254. return bucket.Put([]byte(group), []byte{1})
  255. } else {
  256. return bucket.Put([]byte(group), []byte{0})
  257. }
  258. })
  259. }
  260. func (c *CacheFile) LoadRuleSet(tag string) *adapter.SavedRuleSet {
  261. var savedSet adapter.SavedRuleSet
  262. err := c.DB.View(func(t *bbolt.Tx) error {
  263. bucket := c.bucket(t, bucketRuleSet)
  264. if bucket == nil {
  265. return os.ErrNotExist
  266. }
  267. setBinary := bucket.Get([]byte(tag))
  268. if len(setBinary) == 0 {
  269. return os.ErrInvalid
  270. }
  271. return savedSet.UnmarshalBinary(setBinary)
  272. })
  273. if err != nil {
  274. return nil
  275. }
  276. return &savedSet
  277. }
  278. func (c *CacheFile) SaveRuleSet(tag string, set *adapter.SavedRuleSet) error {
  279. return c.DB.Batch(func(t *bbolt.Tx) error {
  280. bucket, err := c.createBucket(t, bucketRuleSet)
  281. if err != nil {
  282. return err
  283. }
  284. setBinary, err := set.MarshalBinary()
  285. if err != nil {
  286. return err
  287. }
  288. return bucket.Put([]byte(tag), setBinary)
  289. })
  290. }