cache.go 8.7 KB

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