cache.go 6.9 KB

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