cache.go 7.0 KB

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