1
0

cache.go 6.4 KB

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