cache.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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/experimental/deprecated"
  14. "github.com/sagernet/sing-box/option"
  15. "github.com/sagernet/sing/common"
  16. E "github.com/sagernet/sing/common/exceptions"
  17. "github.com/sagernet/sing/common/logger"
  18. "github.com/sagernet/sing/service/filemanager"
  19. )
  20. var (
  21. bucketSelected = []byte("selected")
  22. bucketExpand = []byte("group_expand")
  23. bucketMode = []byte("clash_mode")
  24. bucketRuleSet = []byte("rule_set")
  25. bucketNameList = []string{
  26. string(bucketSelected),
  27. string(bucketExpand),
  28. string(bucketMode),
  29. string(bucketRuleSet),
  30. string(bucketRDRC),
  31. string(bucketDNSCache),
  32. }
  33. cacheIDDefault = []byte("default")
  34. )
  35. var _ adapter.CacheFile = (*CacheFile)(nil)
  36. type CacheFile struct {
  37. ctx context.Context
  38. logger logger.Logger
  39. path string
  40. cacheID []byte
  41. storeFakeIP bool
  42. storeRDRC bool
  43. storeDNS bool
  44. disableExpire bool
  45. rdrcTimeout time.Duration
  46. optimisticTimeout time.Duration
  47. DB *bbolt.DB
  48. resetAccess sync.Mutex
  49. saveMetadataTimer *time.Timer
  50. saveFakeIPAccess sync.RWMutex
  51. saveDomain map[netip.Addr]string
  52. saveAddress4 map[string]netip.Addr
  53. saveAddress6 map[string]netip.Addr
  54. saveRDRCAccess sync.RWMutex
  55. saveRDRC map[saveCacheKey]bool
  56. saveDNSCacheAccess sync.RWMutex
  57. saveDNSCache map[saveCacheKey]saveDNSCacheEntry
  58. }
  59. type saveCacheKey struct {
  60. TransportName string
  61. QuestionName string
  62. QType uint16
  63. }
  64. type saveDNSCacheEntry struct {
  65. rawMessage []byte
  66. expireAt time.Time
  67. sequence uint64
  68. saving bool
  69. }
  70. func New(ctx context.Context, logger logger.Logger, options option.CacheFileOptions) *CacheFile {
  71. var path string
  72. if options.Path != "" {
  73. path = options.Path
  74. } else {
  75. path = "cache.db"
  76. }
  77. var cacheIDBytes []byte
  78. if options.CacheID != "" {
  79. cacheIDBytes = append([]byte{0}, []byte(options.CacheID)...)
  80. }
  81. if options.StoreRDRC {
  82. deprecated.Report(ctx, deprecated.OptionStoreRDRC)
  83. }
  84. var rdrcTimeout time.Duration
  85. if options.StoreRDRC {
  86. if options.RDRCTimeout > 0 {
  87. rdrcTimeout = time.Duration(options.RDRCTimeout)
  88. } else {
  89. rdrcTimeout = 7 * 24 * time.Hour
  90. }
  91. }
  92. return &CacheFile{
  93. ctx: ctx,
  94. logger: logger,
  95. path: filemanager.BasePath(ctx, path),
  96. cacheID: cacheIDBytes,
  97. storeFakeIP: options.StoreFakeIP,
  98. storeRDRC: options.StoreRDRC,
  99. storeDNS: options.StoreDNS,
  100. rdrcTimeout: rdrcTimeout,
  101. saveDomain: make(map[netip.Addr]string),
  102. saveAddress4: make(map[string]netip.Addr),
  103. saveAddress6: make(map[string]netip.Addr),
  104. saveRDRC: make(map[saveCacheKey]bool),
  105. saveDNSCache: make(map[saveCacheKey]saveDNSCacheEntry),
  106. }
  107. }
  108. func (c *CacheFile) Name() string {
  109. return "cache-file"
  110. }
  111. func (c *CacheFile) Dependencies() []string {
  112. return nil
  113. }
  114. func (c *CacheFile) SetOptimisticTimeout(timeout time.Duration) {
  115. c.optimisticTimeout = timeout
  116. }
  117. func (c *CacheFile) SetDisableExpire(disableExpire bool) {
  118. c.disableExpire = disableExpire
  119. }
  120. func (c *CacheFile) Start(stage adapter.StartStage) error {
  121. switch stage {
  122. case adapter.StartStateInitialize:
  123. return c.start()
  124. case adapter.StartStateStart:
  125. c.startCacheCleanup()
  126. }
  127. return nil
  128. }
  129. func (c *CacheFile) startCacheCleanup() {
  130. if c.storeDNS {
  131. c.clearRDRC()
  132. c.cleanupDNSCache()
  133. interval := c.optimisticTimeout / 2
  134. if interval <= 0 {
  135. interval = time.Hour
  136. }
  137. go c.loopCacheCleanup(interval, c.cleanupDNSCache)
  138. } else if c.storeRDRC {
  139. c.cleanupRDRC()
  140. interval := c.rdrcTimeout / 2
  141. if interval <= 0 {
  142. interval = time.Hour
  143. }
  144. go c.loopCacheCleanup(interval, c.cleanupRDRC)
  145. }
  146. }
  147. func (c *CacheFile) start() error {
  148. const fileMode = 0o666
  149. options := bbolt.Options{Timeout: time.Second}
  150. var (
  151. db *bbolt.DB
  152. err error
  153. )
  154. for i := 0; i < 10; i++ {
  155. db, err = bbolt.Open(c.path, fileMode, &options)
  156. if err == nil {
  157. break
  158. }
  159. if errors.Is(err, bboltErrors.ErrTimeout) {
  160. continue
  161. }
  162. if E.IsMulti(err, bboltErrors.ErrInvalid, bboltErrors.ErrChecksum, bboltErrors.ErrVersionMismatch) {
  163. rmErr := os.Remove(c.path)
  164. if rmErr != nil {
  165. return err
  166. }
  167. }
  168. time.Sleep(100 * time.Millisecond)
  169. }
  170. if err != nil {
  171. return err
  172. }
  173. err = filemanager.Chown(c.ctx, c.path)
  174. if err != nil {
  175. db.Close()
  176. return E.Cause(err, "platform chown")
  177. }
  178. err = db.Batch(func(tx *bbolt.Tx) error {
  179. return tx.ForEach(func(name []byte, b *bbolt.Bucket) error {
  180. if name[0] == 0 {
  181. return b.ForEachBucket(func(k []byte) error {
  182. bucketName := string(k)
  183. if !(common.Contains(bucketNameList, bucketName)) {
  184. _ = b.DeleteBucket(name)
  185. }
  186. return nil
  187. })
  188. } else {
  189. bucketName := string(name)
  190. if !(common.Contains(bucketNameList, bucketName) || strings.HasPrefix(bucketName, fakeipBucketPrefix)) {
  191. _ = tx.DeleteBucket(name)
  192. }
  193. }
  194. return nil
  195. })
  196. })
  197. if err != nil {
  198. db.Close()
  199. return err
  200. }
  201. c.DB = db
  202. return nil
  203. }
  204. func (c *CacheFile) Close() error {
  205. if c.DB == nil {
  206. return nil
  207. }
  208. return c.DB.Close()
  209. }
  210. func (c *CacheFile) view(fn func(tx *bbolt.Tx) error) (err error) {
  211. defer func() {
  212. if r := recover(); r != nil {
  213. c.resetDB()
  214. err = E.New("database corrupted: ", r)
  215. }
  216. }()
  217. return c.DB.View(fn)
  218. }
  219. func (c *CacheFile) batch(fn func(tx *bbolt.Tx) error) (err error) {
  220. defer func() {
  221. if r := recover(); r != nil {
  222. c.resetDB()
  223. err = E.New("database corrupted: ", r)
  224. }
  225. }()
  226. return c.DB.Batch(fn)
  227. }
  228. func (c *CacheFile) update(fn func(tx *bbolt.Tx) error) (err error) {
  229. defer func() {
  230. if r := recover(); r != nil {
  231. c.resetDB()
  232. err = E.New("database corrupted: ", r)
  233. }
  234. }()
  235. return c.DB.Update(fn)
  236. }
  237. func (c *CacheFile) resetDB() {
  238. c.resetAccess.Lock()
  239. defer c.resetAccess.Unlock()
  240. c.DB.Close()
  241. os.Remove(c.path)
  242. db, err := bbolt.Open(c.path, 0o666, &bbolt.Options{Timeout: time.Second})
  243. if err == nil {
  244. _ = filemanager.Chown(c.ctx, c.path)
  245. c.DB = db
  246. }
  247. }
  248. func (c *CacheFile) StoreFakeIP() bool {
  249. return c.storeFakeIP
  250. }
  251. func (c *CacheFile) LoadMode() string {
  252. var mode string
  253. c.view(func(t *bbolt.Tx) error {
  254. bucket := t.Bucket(bucketMode)
  255. if bucket == nil {
  256. return nil
  257. }
  258. var modeBytes []byte
  259. if len(c.cacheID) > 0 {
  260. modeBytes = bucket.Get(c.cacheID)
  261. } else {
  262. modeBytes = bucket.Get(cacheIDDefault)
  263. }
  264. mode = string(modeBytes)
  265. return nil
  266. })
  267. return mode
  268. }
  269. func (c *CacheFile) StoreMode(mode string) error {
  270. return c.batch(func(t *bbolt.Tx) error {
  271. bucket, err := t.CreateBucketIfNotExists(bucketMode)
  272. if err != nil {
  273. return err
  274. }
  275. if len(c.cacheID) > 0 {
  276. return bucket.Put(c.cacheID, []byte(mode))
  277. } else {
  278. return bucket.Put(cacheIDDefault, []byte(mode))
  279. }
  280. })
  281. }
  282. func (c *CacheFile) bucket(t *bbolt.Tx, key []byte) *bbolt.Bucket {
  283. if c.cacheID == nil {
  284. return t.Bucket(key)
  285. }
  286. bucket := t.Bucket(c.cacheID)
  287. if bucket == nil {
  288. return nil
  289. }
  290. return bucket.Bucket(key)
  291. }
  292. func (c *CacheFile) createBucket(t *bbolt.Tx, key []byte) (*bbolt.Bucket, error) {
  293. if c.cacheID == nil {
  294. return t.CreateBucketIfNotExists(key)
  295. }
  296. bucket, err := t.CreateBucketIfNotExists(c.cacheID)
  297. if bucket == nil {
  298. return nil, err
  299. }
  300. return bucket.CreateBucketIfNotExists(key)
  301. }
  302. func (c *CacheFile) LoadSelected(group string) string {
  303. var selected string
  304. c.view(func(t *bbolt.Tx) error {
  305. bucket := c.bucket(t, bucketSelected)
  306. if bucket == nil {
  307. return nil
  308. }
  309. selectedBytes := bucket.Get([]byte(group))
  310. if len(selectedBytes) > 0 {
  311. selected = string(selectedBytes)
  312. }
  313. return nil
  314. })
  315. return selected
  316. }
  317. func (c *CacheFile) StoreSelected(group, selected string) error {
  318. return c.batch(func(t *bbolt.Tx) error {
  319. bucket, err := c.createBucket(t, bucketSelected)
  320. if err != nil {
  321. return err
  322. }
  323. return bucket.Put([]byte(group), []byte(selected))
  324. })
  325. }
  326. func (c *CacheFile) LoadGroupExpand(group string) (isExpand bool, loaded bool) {
  327. c.view(func(t *bbolt.Tx) error {
  328. bucket := c.bucket(t, bucketExpand)
  329. if bucket == nil {
  330. return nil
  331. }
  332. expandBytes := bucket.Get([]byte(group))
  333. if len(expandBytes) == 1 {
  334. isExpand = expandBytes[0] == 1
  335. loaded = true
  336. }
  337. return nil
  338. })
  339. return
  340. }
  341. func (c *CacheFile) StoreGroupExpand(group string, isExpand bool) error {
  342. return c.batch(func(t *bbolt.Tx) error {
  343. bucket, err := c.createBucket(t, bucketExpand)
  344. if err != nil {
  345. return err
  346. }
  347. if isExpand {
  348. return bucket.Put([]byte(group), []byte{1})
  349. } else {
  350. return bucket.Put([]byte(group), []byte{0})
  351. }
  352. })
  353. }
  354. func (c *CacheFile) LoadRuleSet(tag string) *adapter.SavedBinary {
  355. var savedSet adapter.SavedBinary
  356. err := c.view(func(t *bbolt.Tx) error {
  357. bucket := c.bucket(t, bucketRuleSet)
  358. if bucket == nil {
  359. return os.ErrNotExist
  360. }
  361. setBinary := bucket.Get([]byte(tag))
  362. if len(setBinary) == 0 {
  363. return os.ErrInvalid
  364. }
  365. return savedSet.UnmarshalBinary(setBinary)
  366. })
  367. if err != nil {
  368. return nil
  369. }
  370. return &savedSet
  371. }
  372. func (c *CacheFile) SaveRuleSet(tag string, set *adapter.SavedBinary) error {
  373. return c.batch(func(t *bbolt.Tx) error {
  374. bucket, err := c.createBucket(t, bucketRuleSet)
  375. if err != nil {
  376. return err
  377. }
  378. setBinary, err := set.MarshalBinary()
  379. if err != nil {
  380. return err
  381. }
  382. return bucket.Put([]byte(tag), setBinary)
  383. })
  384. }