dataStore.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "bytes"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "math/rand"
  26. "os"
  27. "path/filepath"
  28. "sync"
  29. "time"
  30. "github.com/Psiphon-Labs/bolt"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. )
  35. // The BoltDB dataStore implementation is an alternative to the sqlite3-based
  36. // implementation in dataStore.go. Both implementations have the same interface.
  37. //
  38. // BoltDB is pure Go, and is intended to be used in cases where we have trouble
  39. // building sqlite3/CGO (e.g., currently go mobile due to
  40. // https://github.com/mattn/go-sqlite3/issues/201), and perhaps ultimately as
  41. // the primary dataStore implementation.
  42. //
  43. type dataStore struct {
  44. init sync.Once
  45. db *bolt.DB
  46. }
  47. const (
  48. serverEntriesBucket = "serverEntries"
  49. rankedServerEntriesBucket = "rankedServerEntries"
  50. rankedServerEntriesKey = "rankedServerEntries"
  51. splitTunnelRouteETagsBucket = "splitTunnelRouteETags"
  52. splitTunnelRouteDataBucket = "splitTunnelRouteData"
  53. urlETagsBucket = "urlETags"
  54. keyValueBucket = "keyValues"
  55. tunnelStatsBucket = "tunnelStats"
  56. remoteServerListStatsBucket = "remoteServerListStats"
  57. slokBucket = "SLOKs"
  58. tacticsBucket = "tactics"
  59. speedTestSamplesBucket = "speedTestSamples"
  60. rankedServerEntryCount = 100
  61. )
  62. const (
  63. DATA_STORE_FILENAME = "psiphon.boltdb"
  64. LEGACY_DATA_STORE_FILENAME = "psiphon.db"
  65. DATA_STORE_LAST_CONNECTED_KEY = "lastConnected"
  66. DATA_STORE_LAST_SERVER_ENTRY_FILTER_KEY = "lastServerEntryFilter"
  67. PERSISTENT_STAT_TYPE_REMOTE_SERVER_LIST = remoteServerListStatsBucket
  68. )
  69. var singleton dataStore
  70. // InitDataStore initializes the singleton instance of dataStore. This
  71. // function uses a sync.Once and is safe for use by concurrent goroutines.
  72. // The underlying sql.DB connection pool is also safe.
  73. //
  74. // Note: the sync.Once was more useful when initDataStore was private and
  75. // called on-demand by the public functions below. Now we require an explicit
  76. // InitDataStore() call with the filename passed in. The on-demand calls
  77. // have been replaced by checkInitDataStore() to assert that Init was called.
  78. func InitDataStore(config *Config) (err error) {
  79. singleton.init.Do(func() {
  80. // Need to gather the list of migratable server entries before
  81. // initializing the boltdb store (as prepareMigrationEntries
  82. // checks for the existence of the bolt db file)
  83. migratableServerEntries := prepareMigrationEntries(config)
  84. filename := filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)
  85. var db *bolt.DB
  86. for retry := 0; retry < 3; retry++ {
  87. if retry > 0 {
  88. NoticeAlert("InitDataStore retry: %d", retry)
  89. }
  90. db, err = bolt.Open(filename, 0600, &bolt.Options{Timeout: 1 * time.Second})
  91. // The datastore file may be corrupt, so attempt to delete and try again
  92. if err != nil {
  93. NoticeAlert("bolt.Open error: %s", err)
  94. os.Remove(filename)
  95. continue
  96. }
  97. // Run consistency checks on datastore and emit errors for diagnostics purposes
  98. // We assume this will complete quickly for typical size Psiphon datastores.
  99. err = db.View(func(tx *bolt.Tx) error {
  100. return tx.SynchronousCheck()
  101. })
  102. // The datastore file may be corrupt, so attempt to delete and try again
  103. if err != nil {
  104. NoticeAlert("bolt.SynchronousCheck error: %s", err)
  105. db.Close()
  106. os.Remove(filename)
  107. continue
  108. }
  109. break
  110. }
  111. if err != nil {
  112. // Note: intending to set the err return value for InitDataStore
  113. err = fmt.Errorf("initDataStore failed to open database: %s", err)
  114. return
  115. }
  116. err = db.Update(func(tx *bolt.Tx) error {
  117. requiredBuckets := []string{
  118. serverEntriesBucket,
  119. rankedServerEntriesBucket,
  120. splitTunnelRouteETagsBucket,
  121. splitTunnelRouteDataBucket,
  122. urlETagsBucket,
  123. keyValueBucket,
  124. tunnelStatsBucket,
  125. remoteServerListStatsBucket,
  126. slokBucket,
  127. tacticsBucket,
  128. speedTestSamplesBucket,
  129. }
  130. for _, bucket := range requiredBuckets {
  131. _, err := tx.CreateBucketIfNotExists([]byte(bucket))
  132. if err != nil {
  133. return err
  134. }
  135. }
  136. return nil
  137. })
  138. if err != nil {
  139. err = fmt.Errorf("initDataStore failed to create buckets: %s", err)
  140. return
  141. }
  142. // Cleanup obsolete tunnel (session) stats bucket, if one still exists
  143. err = db.Update(func(tx *bolt.Tx) error {
  144. tunnelStatsBucket := []byte("tunnelStats")
  145. if tx.Bucket(tunnelStatsBucket) != nil {
  146. err := tx.DeleteBucket(tunnelStatsBucket)
  147. if err != nil {
  148. NoticeAlert("DeleteBucket %s error: %s", tunnelStatsBucket, err)
  149. // Continue, since this is not fatal
  150. }
  151. }
  152. return nil
  153. })
  154. if err != nil {
  155. err = fmt.Errorf("initDataStore failed to create buckets: %s", err)
  156. return
  157. }
  158. singleton.db = db
  159. // The migrateServerEntries function requires the data store is
  160. // initialized prior to execution so that migrated entries can be stored
  161. if len(migratableServerEntries) > 0 {
  162. migrateEntries(
  163. config, migratableServerEntries, filepath.Join(config.DataStoreDirectory, LEGACY_DATA_STORE_FILENAME))
  164. }
  165. resetAllPersistentStatsToUnreported()
  166. })
  167. return err
  168. }
  169. func checkInitDataStore() {
  170. if singleton.db == nil {
  171. panic("checkInitDataStore: datastore not initialized")
  172. }
  173. }
  174. // StoreServerEntry adds the server entry to the data store.
  175. // A newly stored (or re-stored) server entry is assigned the next-to-top
  176. // rank for iteration order (the previous top ranked entry is promoted). The
  177. // purpose of inserting at next-to-top is to keep the last selected server
  178. // as the top ranked server.
  179. //
  180. // When a server entry already exists for a given server, it will be
  181. // replaced only if replaceIfExists is set or if the the ConfigurationVersion
  182. // field of the new entry is strictly higher than the existing entry.
  183. //
  184. // If the server entry data is malformed, an alert notice is issued and
  185. // the entry is skipped; no error is returned.
  186. func StoreServerEntry(serverEntry *protocol.ServerEntry, replaceIfExists bool) error {
  187. checkInitDataStore()
  188. // Server entries should already be validated before this point,
  189. // so instead of skipping we fail with an error.
  190. err := protocol.ValidateServerEntry(serverEntry)
  191. if err != nil {
  192. return common.ContextError(
  193. fmt.Errorf("invalid server entry: %s", err))
  194. }
  195. // BoltDB implementation note:
  196. // For simplicity, we don't maintain indexes on server entry
  197. // region or supported protocols. Instead, we perform full-bucket
  198. // scans with a filter. With a small enough database (thousands or
  199. // even tens of thousand of server entries) and common enough
  200. // values (e.g., many servers support all protocols), performance
  201. // is expected to be acceptable.
  202. err = singleton.db.Update(func(tx *bolt.Tx) error {
  203. serverEntries := tx.Bucket([]byte(serverEntriesBucket))
  204. // Check not only that the entry exists, but is valid. This
  205. // will replace in the rare case where the data is corrupt.
  206. existingConfigurationVersion := -1
  207. existingData := serverEntries.Get([]byte(serverEntry.IpAddress))
  208. if existingData != nil {
  209. var existingServerEntry *protocol.ServerEntry
  210. err := json.Unmarshal(existingData, &existingServerEntry)
  211. if err == nil {
  212. existingConfigurationVersion = existingServerEntry.ConfigurationVersion
  213. }
  214. }
  215. exists := existingConfigurationVersion > -1
  216. newer := exists && existingConfigurationVersion < serverEntry.ConfigurationVersion
  217. update := !exists || replaceIfExists || newer
  218. if !update {
  219. // Disabling this notice, for now, as it generates too much noise
  220. // in diagnostics with clients that always submit embedded servers
  221. // to the core on each run.
  222. // NoticeInfo("ignored update for server %s", serverEntry.IpAddress)
  223. return nil
  224. }
  225. data, err := json.Marshal(serverEntry)
  226. if err != nil {
  227. return common.ContextError(err)
  228. }
  229. err = serverEntries.Put([]byte(serverEntry.IpAddress), data)
  230. if err != nil {
  231. return common.ContextError(err)
  232. }
  233. err = insertRankedServerEntry(tx, serverEntry.IpAddress, 1)
  234. if err != nil {
  235. return common.ContextError(err)
  236. }
  237. NoticeInfo("updated server %s", serverEntry.IpAddress)
  238. return nil
  239. })
  240. if err != nil {
  241. return common.ContextError(err)
  242. }
  243. return nil
  244. }
  245. // StoreServerEntries stores a list of server entries.
  246. // There is an independent transaction for each entry insert/update.
  247. func StoreServerEntries(
  248. config *Config,
  249. serverEntries []*protocol.ServerEntry,
  250. replaceIfExists bool) error {
  251. checkInitDataStore()
  252. for _, serverEntry := range serverEntries {
  253. err := StoreServerEntry(serverEntry, replaceIfExists)
  254. if err != nil {
  255. return common.ContextError(err)
  256. }
  257. }
  258. return nil
  259. }
  260. // StreamingStoreServerEntries stores a list of server entries.
  261. // There is an independent transaction for each entry insert/update.
  262. func StreamingStoreServerEntries(
  263. config *Config,
  264. serverEntries *protocol.StreamingServerEntryDecoder,
  265. replaceIfExists bool) error {
  266. checkInitDataStore()
  267. // Note: both StreamingServerEntryDecoder.Next and StoreServerEntry
  268. // allocate temporary memory buffers for hex/JSON decoding/encoding,
  269. // so this isn't true constant-memory streaming (it depends on garbage
  270. // collection).
  271. for {
  272. serverEntry, err := serverEntries.Next()
  273. if err != nil {
  274. return common.ContextError(err)
  275. }
  276. if serverEntry == nil {
  277. // No more server entries
  278. break
  279. }
  280. err = StoreServerEntry(serverEntry, replaceIfExists)
  281. if err != nil {
  282. return common.ContextError(err)
  283. }
  284. }
  285. return nil
  286. }
  287. // PromoteServerEntry assigns the top rank (one more than current
  288. // max rank) to the specified server entry. Server candidates are
  289. // iterated in decending rank order, so this server entry will be
  290. // the first candidate in a subsequent tunnel establishment.
  291. func PromoteServerEntry(config *Config, ipAddress string) error {
  292. checkInitDataStore()
  293. err := singleton.db.Update(func(tx *bolt.Tx) error {
  294. // Ensure the corresponding entry exists before
  295. // inserting into rank.
  296. bucket := tx.Bucket([]byte(serverEntriesBucket))
  297. data := bucket.Get([]byte(ipAddress))
  298. if data == nil {
  299. NoticeAlert(
  300. "PromoteServerEntry: ignoring unknown server entry: %s",
  301. ipAddress)
  302. return nil
  303. }
  304. err := insertRankedServerEntry(tx, ipAddress, 0)
  305. if err != nil {
  306. return err
  307. }
  308. // Store the current server entry filter (e.g, region, etc.) that
  309. // was in use when the entry was promoted. This is used to detect
  310. // when the top ranked server entry was promoted under a different
  311. // filter.
  312. currentFilter, err := makeServerEntryFilterValue(config)
  313. if err != nil {
  314. return err
  315. }
  316. bucket = tx.Bucket([]byte(keyValueBucket))
  317. return bucket.Put([]byte(DATA_STORE_LAST_SERVER_ENTRY_FILTER_KEY), currentFilter)
  318. })
  319. if err != nil {
  320. return common.ContextError(err)
  321. }
  322. return nil
  323. }
  324. func makeServerEntryFilterValue(config *Config) ([]byte, error) {
  325. // Currently, only a change of EgressRegion will "break" server affinity.
  326. // If the tunnel protocol filter changes, any existing affinity server
  327. // either passes the new filter, or it will be skipped anyway.
  328. return []byte(config.EgressRegion), nil
  329. }
  330. func hasServerEntryFilterChanged(config *Config) (bool, error) {
  331. currentFilter, err := makeServerEntryFilterValue(config)
  332. if err != nil {
  333. return false, common.ContextError(err)
  334. }
  335. changed := false
  336. err = singleton.db.View(func(tx *bolt.Tx) error {
  337. // previousFilter will be nil not found (not previously
  338. // set) which will never match any current filter.
  339. bucket := tx.Bucket([]byte(keyValueBucket))
  340. previousFilter := bucket.Get([]byte(DATA_STORE_LAST_SERVER_ENTRY_FILTER_KEY))
  341. if bytes.Compare(previousFilter, currentFilter) != 0 {
  342. changed = true
  343. }
  344. return nil
  345. })
  346. if err != nil {
  347. return false, common.ContextError(err)
  348. }
  349. return changed, nil
  350. }
  351. func getRankedServerEntries(tx *bolt.Tx) ([]string, error) {
  352. bucket := tx.Bucket([]byte(rankedServerEntriesBucket))
  353. data := bucket.Get([]byte(rankedServerEntriesKey))
  354. if data == nil {
  355. return []string{}, nil
  356. }
  357. rankedServerEntries := make([]string, 0)
  358. err := json.Unmarshal(data, &rankedServerEntries)
  359. if err != nil {
  360. return nil, common.ContextError(err)
  361. }
  362. return rankedServerEntries, nil
  363. }
  364. func setRankedServerEntries(tx *bolt.Tx, rankedServerEntries []string) error {
  365. data, err := json.Marshal(rankedServerEntries)
  366. if err != nil {
  367. return common.ContextError(err)
  368. }
  369. bucket := tx.Bucket([]byte(rankedServerEntriesBucket))
  370. err = bucket.Put([]byte(rankedServerEntriesKey), data)
  371. if err != nil {
  372. return common.ContextError(err)
  373. }
  374. return nil
  375. }
  376. func insertRankedServerEntry(tx *bolt.Tx, serverEntryId string, position int) error {
  377. rankedServerEntries, err := getRankedServerEntries(tx)
  378. if err != nil {
  379. return common.ContextError(err)
  380. }
  381. // BoltDB implementation note:
  382. // For simplicity, we store the ranked server ids in an array serialized to
  383. // a single key value. To ensure this value doesn't grow without bound,
  384. // it's capped at rankedServerEntryCount. For now, this cap should be large
  385. // enough to meet the shuffleHeadLength = config.TunnelPoolSize criteria, for
  386. // any reasonable configuration of config.TunnelPoolSize.
  387. // Using: https://github.com/golang/go/wiki/SliceTricks
  388. // When serverEntryId is already ranked, remove it first to avoid duplicates
  389. for i, rankedServerEntryId := range rankedServerEntries {
  390. if rankedServerEntryId == serverEntryId {
  391. rankedServerEntries = append(
  392. rankedServerEntries[:i], rankedServerEntries[i+1:]...)
  393. break
  394. }
  395. }
  396. // SliceTricks insert, with length cap enforced
  397. if len(rankedServerEntries) < rankedServerEntryCount {
  398. rankedServerEntries = append(rankedServerEntries, "")
  399. }
  400. if position >= len(rankedServerEntries) {
  401. position = len(rankedServerEntries) - 1
  402. }
  403. copy(rankedServerEntries[position+1:], rankedServerEntries[position:])
  404. rankedServerEntries[position] = serverEntryId
  405. err = setRankedServerEntries(tx, rankedServerEntries)
  406. if err != nil {
  407. return common.ContextError(err)
  408. }
  409. return nil
  410. }
  411. // ServerEntryIterator is used to iterate over
  412. // stored server entries in rank order.
  413. type ServerEntryIterator struct {
  414. config *Config
  415. shuffleHeadLength int
  416. serverEntryIds []string
  417. serverEntryIndex int
  418. isTacticsServerEntryIterator bool
  419. isTargetServerEntryIterator bool
  420. hasNextTargetServerEntry bool
  421. targetServerEntry *protocol.ServerEntry
  422. }
  423. // NewServerEntryIterator creates a new ServerEntryIterator.
  424. //
  425. // The boolean return value indicates whether to treat the first server(s)
  426. // as affinity servers or not. When the server entry selection filter changes
  427. // such as from a specific region to any region, or when there was no previous
  428. // filter/iterator, the the first server(s) are arbitrary and should not be
  429. // given affinity treatment.
  430. //
  431. // NewServerEntryIterator and any returned ServerEntryIterator are not
  432. // designed for concurrent use as not all related datastore operations are
  433. // performed in a single transaction.
  434. //
  435. func NewServerEntryIterator(config *Config) (bool, *ServerEntryIterator, error) {
  436. // When configured, this target server entry is the only candidate
  437. if config.TargetServerEntry != "" {
  438. return newTargetServerEntryIterator(config, false)
  439. }
  440. checkInitDataStore()
  441. filterChanged, err := hasServerEntryFilterChanged(config)
  442. if err != nil {
  443. return false, nil, common.ContextError(err)
  444. }
  445. applyServerAffinity := !filterChanged
  446. iterator := &ServerEntryIterator{
  447. config: config,
  448. shuffleHeadLength: config.TunnelPoolSize,
  449. }
  450. err = iterator.Reset()
  451. if err != nil {
  452. return false, nil, common.ContextError(err)
  453. }
  454. return applyServerAffinity, iterator, nil
  455. }
  456. func NewTacticsServerEntryIterator(config *Config) (*ServerEntryIterator, error) {
  457. // When configured, this target server entry is the only candidate
  458. if config.TargetServerEntry != "" {
  459. _, iterator, err := newTargetServerEntryIterator(config, true)
  460. return iterator, err
  461. }
  462. checkInitDataStore()
  463. iterator := &ServerEntryIterator{
  464. shuffleHeadLength: 0,
  465. isTacticsServerEntryIterator: true,
  466. }
  467. err := iterator.Reset()
  468. if err != nil {
  469. return nil, common.ContextError(err)
  470. }
  471. return iterator, nil
  472. }
  473. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  474. func newTargetServerEntryIterator(config *Config, isTactics bool) (bool, *ServerEntryIterator, error) {
  475. serverEntry, err := protocol.DecodeServerEntry(
  476. config.TargetServerEntry, common.GetCurrentTimestamp(), protocol.SERVER_ENTRY_SOURCE_TARGET)
  477. if err != nil {
  478. return false, nil, common.ContextError(err)
  479. }
  480. if isTactics {
  481. if len(serverEntry.GetSupportedTacticsProtocols()) == 0 {
  482. return false, nil, common.ContextError(errors.New("TargetServerEntry does not support tactics protocols"))
  483. }
  484. } else {
  485. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  486. return false, nil, common.ContextError(errors.New("TargetServerEntry does not support EgressRegion"))
  487. }
  488. limitTunnelProtocols := config.clientParameters.Get().TunnelProtocols(parameters.LimitTunnelProtocols)
  489. if len(limitTunnelProtocols) > 0 {
  490. // At the ServerEntryIterator level, only limitTunnelProtocols is applied;
  491. // impairedTunnelProtocols and excludeMeek are handled higher up.
  492. if len(serverEntry.GetSupportedProtocols(limitTunnelProtocols, nil, false)) == 0 {
  493. return false, nil, common.ContextError(errors.New("TargetServerEntry does not support LimitTunnelProtocols"))
  494. }
  495. }
  496. }
  497. iterator := &ServerEntryIterator{
  498. isTacticsServerEntryIterator: isTactics,
  499. isTargetServerEntryIterator: true,
  500. hasNextTargetServerEntry: true,
  501. targetServerEntry: serverEntry,
  502. }
  503. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  504. return false, iterator, nil
  505. }
  506. // Reset a NewServerEntryIterator to the start of its cycle. The next
  507. // call to Next will return the first server entry.
  508. func (iterator *ServerEntryIterator) Reset() error {
  509. iterator.Close()
  510. if iterator.isTargetServerEntryIterator {
  511. iterator.hasNextTargetServerEntry = true
  512. return nil
  513. }
  514. // For diagnostics, it's useful to count the number of known server
  515. // entries that satisfy both the egress region and tunnel protocol
  516. // requirements. The tunnel protocol filter is not applied by the iterator
  517. // as protocol filtering, including impaire protocol and exclude-meek
  518. // logic, is all handled higher up.
  519. // TODO: for isTacticsServerEntryIterator, emit tactics candidate count.
  520. if !iterator.isTacticsServerEntryIterator {
  521. limitTunnelProtocols := iterator.config.clientParameters.Get().TunnelProtocols(
  522. parameters.LimitTunnelProtocols)
  523. count := CountServerEntries(iterator.config.EgressRegion, limitTunnelProtocols)
  524. NoticeCandidateServers(iterator.config.EgressRegion, limitTunnelProtocols, count)
  525. // LimitTunnelProtocols may have changed since the last ReportAvailableRegions,
  526. // and now there may be no servers with the required capabilities in the
  527. // selected region. ReportAvailableRegions will signal this to the client.
  528. if count == 0 {
  529. ReportAvailableRegions(iterator.config)
  530. }
  531. }
  532. // This query implements the Psiphon server candidate selection
  533. // algorithm: the first TunnelPoolSize server candidates are in rank
  534. // (priority) order, to favor previously successful servers; then the
  535. // remaining long tail is shuffled to raise up less recent candidates.
  536. // BoltDB implementation note:
  537. // We don't keep a transaction open for the duration of the iterator
  538. // because this would expose the following semantics to consumer code:
  539. //
  540. // Read-only transactions and read-write transactions ... generally
  541. // shouldn't be opened simultaneously in the same goroutine. This can
  542. // cause a deadlock as the read-write transaction needs to periodically
  543. // re-map the data file but it cannot do so while a read-only
  544. // transaction is open.
  545. // (https://github.com/boltdb/bolt)
  546. //
  547. // So the underlying serverEntriesBucket could change after the serverEntryIds
  548. // list is built.
  549. var serverEntryIds []string
  550. err := singleton.db.View(func(tx *bolt.Tx) error {
  551. var err error
  552. serverEntryIds, err = getRankedServerEntries(tx)
  553. if err != nil {
  554. return err
  555. }
  556. skipServerEntryIds := make(map[string]bool)
  557. for _, serverEntryId := range serverEntryIds {
  558. skipServerEntryIds[serverEntryId] = true
  559. }
  560. bucket := tx.Bucket([]byte(serverEntriesBucket))
  561. cursor := bucket.Cursor()
  562. for key, _ := cursor.Last(); key != nil; key, _ = cursor.Prev() {
  563. serverEntryId := string(key)
  564. if _, ok := skipServerEntryIds[serverEntryId]; ok {
  565. continue
  566. }
  567. serverEntryIds = append(serverEntryIds, serverEntryId)
  568. }
  569. return nil
  570. })
  571. if err != nil {
  572. return common.ContextError(err)
  573. }
  574. for i := len(serverEntryIds) - 1; i > iterator.shuffleHeadLength-1; i-- {
  575. j := rand.Intn(i+1-iterator.shuffleHeadLength) + iterator.shuffleHeadLength
  576. serverEntryIds[i], serverEntryIds[j] = serverEntryIds[j], serverEntryIds[i]
  577. }
  578. iterator.serverEntryIds = serverEntryIds
  579. iterator.serverEntryIndex = 0
  580. return nil
  581. }
  582. // Close cleans up resources associated with a ServerEntryIterator.
  583. func (iterator *ServerEntryIterator) Close() {
  584. iterator.serverEntryIds = nil
  585. iterator.serverEntryIndex = 0
  586. }
  587. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  588. // Returns nil with no error when there is no next item.
  589. func (iterator *ServerEntryIterator) Next() (*protocol.ServerEntry, error) {
  590. var err error
  591. var serverEntry *protocol.ServerEntry
  592. defer func() {
  593. if err != nil {
  594. iterator.Close()
  595. }
  596. }()
  597. if iterator.isTargetServerEntryIterator {
  598. if iterator.hasNextTargetServerEntry {
  599. iterator.hasNextTargetServerEntry = false
  600. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  601. }
  602. return nil, nil
  603. }
  604. // There are no region/protocol indexes for the server entries bucket.
  605. // Loop until we have the next server entry that matches the iterator
  606. // filter requirements.
  607. for {
  608. if iterator.serverEntryIndex >= len(iterator.serverEntryIds) {
  609. // There is no next item
  610. return nil, nil
  611. }
  612. serverEntryId := iterator.serverEntryIds[iterator.serverEntryIndex]
  613. iterator.serverEntryIndex += 1
  614. var data []byte
  615. err = singleton.db.View(func(tx *bolt.Tx) error {
  616. bucket := tx.Bucket([]byte(serverEntriesBucket))
  617. value := bucket.Get([]byte(serverEntryId))
  618. if value != nil {
  619. // Must make a copy as slice is only valid within transaction.
  620. data = make([]byte, len(value))
  621. copy(data, value)
  622. }
  623. return nil
  624. })
  625. if err != nil {
  626. return nil, common.ContextError(err)
  627. }
  628. if data == nil {
  629. // In case of data corruption or a bug causing this condition,
  630. // do not stop iterating.
  631. NoticeAlert("ServerEntryIterator.Next: unexpected missing server entry: %s", serverEntryId)
  632. continue
  633. }
  634. err = json.Unmarshal(data, &serverEntry)
  635. if err != nil {
  636. // In case of data corruption or a bug causing this condition,
  637. // do not stop iterating.
  638. NoticeAlert("ServerEntryIterator.Next: %s", common.ContextError(err))
  639. continue
  640. }
  641. // Check filter requirements
  642. if iterator.isTacticsServerEntryIterator {
  643. // Tactics doesn't filter by egress region.
  644. if len(serverEntry.GetSupportedTacticsProtocols()) > 0 {
  645. break
  646. }
  647. } else {
  648. if iterator.config.EgressRegion == "" ||
  649. serverEntry.Region == iterator.config.EgressRegion {
  650. break
  651. }
  652. }
  653. }
  654. return MakeCompatibleServerEntry(serverEntry), nil
  655. }
  656. // MakeCompatibleServerEntry provides backwards compatibility with old server entries
  657. // which have a single meekFrontingDomain and not a meekFrontingAddresses array.
  658. // By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
  659. // uses that single value as legacy clients do.
  660. func MakeCompatibleServerEntry(serverEntry *protocol.ServerEntry) *protocol.ServerEntry {
  661. if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
  662. serverEntry.MeekFrontingAddresses =
  663. append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
  664. }
  665. return serverEntry
  666. }
  667. func scanServerEntries(scanner func(*protocol.ServerEntry)) error {
  668. err := singleton.db.View(func(tx *bolt.Tx) error {
  669. bucket := tx.Bucket([]byte(serverEntriesBucket))
  670. cursor := bucket.Cursor()
  671. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  672. serverEntry := new(protocol.ServerEntry)
  673. err := json.Unmarshal(value, serverEntry)
  674. if err != nil {
  675. // In case of data corruption or a bug causing this condition,
  676. // do not stop iterating.
  677. NoticeAlert("scanServerEntries: %s", common.ContextError(err))
  678. continue
  679. }
  680. scanner(serverEntry)
  681. }
  682. return nil
  683. })
  684. if err != nil {
  685. return common.ContextError(err)
  686. }
  687. return nil
  688. }
  689. // CountServerEntries returns a count of stored servers for the
  690. // specified region and tunnel protocols.
  691. func CountServerEntries(region string, tunnelProtocols []string) int {
  692. checkInitDataStore()
  693. count := 0
  694. err := scanServerEntries(func(serverEntry *protocol.ServerEntry) {
  695. if (region == "" || serverEntry.Region == region) &&
  696. (len(tunnelProtocols) == 0 ||
  697. // When CountServerEntries is called only limitTunnelProtocols is known;
  698. // impairedTunnelProtocols and excludeMeek may not apply.
  699. len(serverEntry.GetSupportedProtocols(tunnelProtocols, nil, false)) > 0) {
  700. count += 1
  701. }
  702. })
  703. if err != nil {
  704. NoticeAlert("CountServerEntries failed: %s", err)
  705. return 0
  706. }
  707. return count
  708. }
  709. // CountNonImpairedProtocols returns the number of distinct tunnel
  710. // protocols supported by stored server entries, excluding the
  711. // specified impaired protocols.
  712. func CountNonImpairedProtocols(
  713. region string,
  714. limitTunnelProtocols, impairedProtocols []string) int {
  715. checkInitDataStore()
  716. distinctProtocols := make(map[string]bool)
  717. err := scanServerEntries(func(serverEntry *protocol.ServerEntry) {
  718. if region == "" || serverEntry.Region == region {
  719. for _, protocol := range protocol.SupportedTunnelProtocols {
  720. if serverEntry.SupportsProtocol(protocol) {
  721. if len(limitTunnelProtocols) == 0 ||
  722. common.Contains(limitTunnelProtocols, protocol) {
  723. distinctProtocols[protocol] = true
  724. }
  725. }
  726. }
  727. }
  728. })
  729. for _, protocol := range impairedProtocols {
  730. delete(distinctProtocols, protocol)
  731. }
  732. if err != nil {
  733. NoticeAlert("CountNonImpairedProtocols failed: %s", err)
  734. return 0
  735. }
  736. return len(distinctProtocols)
  737. }
  738. // ReportAvailableRegions prints a notice with the available egress regions.
  739. func ReportAvailableRegions(config *Config) {
  740. checkInitDataStore()
  741. limitTunnelProtocols := config.clientParameters.Get().TunnelProtocols(
  742. parameters.LimitTunnelProtocols)
  743. regions := make(map[string]bool)
  744. err := scanServerEntries(func(serverEntry *protocol.ServerEntry) {
  745. if len(limitTunnelProtocols) == 0 ||
  746. // When ReportAvailableRegions is called only limitTunnelProtocols is known;
  747. // impairedTunnelProtocols and excludeMeek may not apply.
  748. len(serverEntry.GetSupportedProtocols(limitTunnelProtocols, nil, false)) > 0 {
  749. regions[serverEntry.Region] = true
  750. }
  751. })
  752. if err != nil {
  753. NoticeAlert("ReportAvailableRegions failed: %s", err)
  754. return
  755. }
  756. regionList := make([]string, 0, len(regions))
  757. for region := range regions {
  758. // Some server entries do not have a region, but it makes no sense to return
  759. // an empty string as an "available region".
  760. if region != "" {
  761. regionList = append(regionList, region)
  762. }
  763. }
  764. NoticeAvailableEgressRegions(regionList)
  765. }
  766. // GetServerEntryIpAddresses returns an array containing
  767. // all stored server IP addresses.
  768. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  769. checkInitDataStore()
  770. ipAddresses = make([]string, 0)
  771. err = scanServerEntries(func(serverEntry *protocol.ServerEntry) {
  772. ipAddresses = append(ipAddresses, serverEntry.IpAddress)
  773. })
  774. if err != nil {
  775. return nil, common.ContextError(err)
  776. }
  777. return ipAddresses, nil
  778. }
  779. // SetSplitTunnelRoutes updates the cached routes data for
  780. // the given region. The associated etag is also stored and
  781. // used to make efficient web requests for updates to the data.
  782. func SetSplitTunnelRoutes(region, etag string, data []byte) error {
  783. checkInitDataStore()
  784. err := singleton.db.Update(func(tx *bolt.Tx) error {
  785. bucket := tx.Bucket([]byte(splitTunnelRouteETagsBucket))
  786. err := bucket.Put([]byte(region), []byte(etag))
  787. bucket = tx.Bucket([]byte(splitTunnelRouteDataBucket))
  788. err = bucket.Put([]byte(region), data)
  789. return err
  790. })
  791. if err != nil {
  792. return common.ContextError(err)
  793. }
  794. return nil
  795. }
  796. // GetSplitTunnelRoutesETag retrieves the etag for cached routes
  797. // data for the specified region. If not found, it returns an empty string value.
  798. func GetSplitTunnelRoutesETag(region string) (etag string, err error) {
  799. checkInitDataStore()
  800. err = singleton.db.View(func(tx *bolt.Tx) error {
  801. bucket := tx.Bucket([]byte(splitTunnelRouteETagsBucket))
  802. etag = string(bucket.Get([]byte(region)))
  803. return nil
  804. })
  805. if err != nil {
  806. return "", common.ContextError(err)
  807. }
  808. return etag, nil
  809. }
  810. // GetSplitTunnelRoutesData retrieves the cached routes data
  811. // for the specified region. If not found, it returns a nil value.
  812. func GetSplitTunnelRoutesData(region string) (data []byte, err error) {
  813. checkInitDataStore()
  814. err = singleton.db.View(func(tx *bolt.Tx) error {
  815. bucket := tx.Bucket([]byte(splitTunnelRouteDataBucket))
  816. value := bucket.Get([]byte(region))
  817. if value != nil {
  818. // Must make a copy as slice is only valid within transaction.
  819. data = make([]byte, len(value))
  820. copy(data, value)
  821. }
  822. return nil
  823. })
  824. if err != nil {
  825. return nil, common.ContextError(err)
  826. }
  827. return data, nil
  828. }
  829. // SetUrlETag stores an ETag for the specfied URL.
  830. // Note: input URL is treated as a string, and is not
  831. // encoded or decoded or otherwise canonicalized.
  832. func SetUrlETag(url, etag string) error {
  833. checkInitDataStore()
  834. err := singleton.db.Update(func(tx *bolt.Tx) error {
  835. bucket := tx.Bucket([]byte(urlETagsBucket))
  836. err := bucket.Put([]byte(url), []byte(etag))
  837. return err
  838. })
  839. if err != nil {
  840. return common.ContextError(err)
  841. }
  842. return nil
  843. }
  844. // GetUrlETag retrieves a previously stored an ETag for the
  845. // specfied URL. If not found, it returns an empty string value.
  846. func GetUrlETag(url string) (etag string, err error) {
  847. checkInitDataStore()
  848. err = singleton.db.View(func(tx *bolt.Tx) error {
  849. bucket := tx.Bucket([]byte(urlETagsBucket))
  850. etag = string(bucket.Get([]byte(url)))
  851. return nil
  852. })
  853. if err != nil {
  854. return "", common.ContextError(err)
  855. }
  856. return etag, nil
  857. }
  858. // SetKeyValue stores a key/value pair.
  859. func SetKeyValue(key, value string) error {
  860. checkInitDataStore()
  861. err := singleton.db.Update(func(tx *bolt.Tx) error {
  862. bucket := tx.Bucket([]byte(keyValueBucket))
  863. err := bucket.Put([]byte(key), []byte(value))
  864. return err
  865. })
  866. if err != nil {
  867. return common.ContextError(err)
  868. }
  869. return nil
  870. }
  871. // GetKeyValue retrieves the value for a given key. If not found,
  872. // it returns an empty string value.
  873. func GetKeyValue(key string) (value string, err error) {
  874. checkInitDataStore()
  875. err = singleton.db.View(func(tx *bolt.Tx) error {
  876. bucket := tx.Bucket([]byte(keyValueBucket))
  877. value = string(bucket.Get([]byte(key)))
  878. return nil
  879. })
  880. if err != nil {
  881. return "", common.ContextError(err)
  882. }
  883. return value, nil
  884. }
  885. // Persistent stat records in the persistentStatStateUnreported
  886. // state are available for take out.
  887. //
  888. // Records in the persistentStatStateReporting have been taken
  889. // out and are pending either deletion (for a successful request)
  890. // or change to StateUnreported (for a failed request).
  891. //
  892. // All persistent stat records are reverted to StateUnreported
  893. // when the datastore is initialized at start up.
  894. var persistentStatStateUnreported = []byte("0")
  895. var persistentStatStateReporting = []byte("1")
  896. var persistentStatTypes = []string{
  897. PERSISTENT_STAT_TYPE_REMOTE_SERVER_LIST,
  898. }
  899. // StorePersistentStat adds a new persistent stat record, which
  900. // is set to StateUnreported and is an immediate candidate for
  901. // reporting.
  902. //
  903. // The stat is a JSON byte array containing fields as
  904. // required by the Psiphon server API. It's assumed that the
  905. // JSON value contains enough unique information for the value to
  906. // function as a key in the key/value datastore. This assumption
  907. // is currently satisfied by the fields sessionId + tunnelNumber
  908. // for tunnel stats, and URL + ETag for remote server list stats.
  909. func StorePersistentStat(statType string, stat []byte) error {
  910. checkInitDataStore()
  911. if !common.Contains(persistentStatTypes, statType) {
  912. return common.ContextError(fmt.Errorf("invalid persistent stat type: %s", statType))
  913. }
  914. err := singleton.db.Update(func(tx *bolt.Tx) error {
  915. bucket := tx.Bucket([]byte(statType))
  916. err := bucket.Put(stat, persistentStatStateUnreported)
  917. return err
  918. })
  919. if err != nil {
  920. return common.ContextError(err)
  921. }
  922. return nil
  923. }
  924. // CountUnreportedPersistentStats returns the number of persistent
  925. // stat records in StateUnreported.
  926. func CountUnreportedPersistentStats() int {
  927. checkInitDataStore()
  928. unreported := 0
  929. err := singleton.db.View(func(tx *bolt.Tx) error {
  930. for _, statType := range persistentStatTypes {
  931. bucket := tx.Bucket([]byte(statType))
  932. cursor := bucket.Cursor()
  933. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  934. if 0 == bytes.Compare(value, persistentStatStateUnreported) {
  935. unreported++
  936. break
  937. }
  938. }
  939. }
  940. return nil
  941. })
  942. if err != nil {
  943. NoticeAlert("CountUnreportedPersistentStats failed: %s", err)
  944. return 0
  945. }
  946. return unreported
  947. }
  948. // TakeOutUnreportedPersistentStats returns up to maxCount persistent
  949. // stats records that are in StateUnreported. The records are set to
  950. // StateReporting. If the records are successfully reported, clear them
  951. // with ClearReportedPersistentStats. If the records are not successfully
  952. // reported, restore them with PutBackUnreportedPersistentStats.
  953. func TakeOutUnreportedPersistentStats(maxCount int) (map[string][][]byte, error) {
  954. checkInitDataStore()
  955. stats := make(map[string][][]byte)
  956. err := singleton.db.Update(func(tx *bolt.Tx) error {
  957. count := 0
  958. for _, statType := range persistentStatTypes {
  959. bucket := tx.Bucket([]byte(statType))
  960. cursor := bucket.Cursor()
  961. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  962. if count >= maxCount {
  963. break
  964. }
  965. // Perform a test JSON unmarshaling. In case of data corruption or a bug,
  966. // skip the record.
  967. var jsonData interface{}
  968. err := json.Unmarshal(key, &jsonData)
  969. if err != nil {
  970. NoticeAlert(
  971. "Invalid key in TakeOutUnreportedPersistentStats: %s: %s",
  972. string(key), err)
  973. continue
  974. }
  975. if 0 == bytes.Compare(value, persistentStatStateUnreported) {
  976. // Must make a copy as slice is only valid within transaction.
  977. data := make([]byte, len(key))
  978. copy(data, key)
  979. if stats[statType] == nil {
  980. stats[statType] = make([][]byte, 0)
  981. }
  982. stats[statType] = append(stats[statType], data)
  983. count += 1
  984. }
  985. }
  986. for _, key := range stats[statType] {
  987. err := bucket.Put(key, persistentStatStateReporting)
  988. if err != nil {
  989. return err
  990. }
  991. }
  992. }
  993. return nil
  994. })
  995. if err != nil {
  996. return nil, common.ContextError(err)
  997. }
  998. return stats, nil
  999. }
  1000. // PutBackUnreportedPersistentStats restores a list of persistent
  1001. // stat records to StateUnreported.
  1002. func PutBackUnreportedPersistentStats(stats map[string][][]byte) error {
  1003. checkInitDataStore()
  1004. err := singleton.db.Update(func(tx *bolt.Tx) error {
  1005. for _, statType := range persistentStatTypes {
  1006. bucket := tx.Bucket([]byte(statType))
  1007. for _, key := range stats[statType] {
  1008. err := bucket.Put(key, persistentStatStateUnreported)
  1009. if err != nil {
  1010. return err
  1011. }
  1012. }
  1013. }
  1014. return nil
  1015. })
  1016. if err != nil {
  1017. return common.ContextError(err)
  1018. }
  1019. return nil
  1020. }
  1021. // ClearReportedPersistentStats deletes a list of persistent
  1022. // stat records that were successfully reported.
  1023. func ClearReportedPersistentStats(stats map[string][][]byte) error {
  1024. checkInitDataStore()
  1025. err := singleton.db.Update(func(tx *bolt.Tx) error {
  1026. for _, statType := range persistentStatTypes {
  1027. bucket := tx.Bucket([]byte(statType))
  1028. for _, key := range stats[statType] {
  1029. err := bucket.Delete(key)
  1030. if err != nil {
  1031. return err
  1032. }
  1033. }
  1034. }
  1035. return nil
  1036. })
  1037. if err != nil {
  1038. return common.ContextError(err)
  1039. }
  1040. return nil
  1041. }
  1042. // resetAllPersistentStatsToUnreported sets all persistent stat
  1043. // records to StateUnreported. This reset is called when the
  1044. // datastore is initialized at start up, as we do not know if
  1045. // persistent records in StateReporting were reported or not.
  1046. func resetAllPersistentStatsToUnreported() error {
  1047. checkInitDataStore()
  1048. err := singleton.db.Update(func(tx *bolt.Tx) error {
  1049. for _, statType := range persistentStatTypes {
  1050. bucket := tx.Bucket([]byte(statType))
  1051. resetKeys := make([][]byte, 0)
  1052. cursor := bucket.Cursor()
  1053. for key, _ := cursor.First(); key != nil; key, _ = cursor.Next() {
  1054. resetKeys = append(resetKeys, key)
  1055. }
  1056. // TODO: data mutation is done outside cursor. Is this
  1057. // strictly necessary in this case? As is, this means
  1058. // all stats need to be loaded into memory at once.
  1059. // https://godoc.org/github.com/boltdb/bolt#Cursor
  1060. for _, key := range resetKeys {
  1061. err := bucket.Put(key, persistentStatStateUnreported)
  1062. if err != nil {
  1063. return err
  1064. }
  1065. }
  1066. }
  1067. return nil
  1068. })
  1069. if err != nil {
  1070. return common.ContextError(err)
  1071. }
  1072. return nil
  1073. }
  1074. // CountSLOKs returns the total number of SLOK records.
  1075. func CountSLOKs() int {
  1076. checkInitDataStore()
  1077. count := 0
  1078. err := singleton.db.View(func(tx *bolt.Tx) error {
  1079. bucket := tx.Bucket([]byte(slokBucket))
  1080. cursor := bucket.Cursor()
  1081. for key, _ := cursor.First(); key != nil; key, _ = cursor.Next() {
  1082. count++
  1083. }
  1084. return nil
  1085. })
  1086. if err != nil {
  1087. NoticeAlert("CountSLOKs failed: %s", err)
  1088. return 0
  1089. }
  1090. return count
  1091. }
  1092. // DeleteSLOKs deletes all SLOK records.
  1093. func DeleteSLOKs() error {
  1094. checkInitDataStore()
  1095. err := singleton.db.Update(func(tx *bolt.Tx) error {
  1096. bucket := tx.Bucket([]byte(slokBucket))
  1097. return bucket.ForEach(
  1098. func(id, _ []byte) error {
  1099. return bucket.Delete(id)
  1100. })
  1101. })
  1102. if err != nil {
  1103. return common.ContextError(err)
  1104. }
  1105. return nil
  1106. }
  1107. // SetSLOK stores a SLOK key, referenced by its ID. The bool
  1108. // return value indicates whether the SLOK was already stored.
  1109. func SetSLOK(id, key []byte) (bool, error) {
  1110. checkInitDataStore()
  1111. var duplicate bool
  1112. err := singleton.db.Update(func(tx *bolt.Tx) error {
  1113. bucket := tx.Bucket([]byte(slokBucket))
  1114. duplicate = bucket.Get(id) != nil
  1115. err := bucket.Put([]byte(id), []byte(key))
  1116. return err
  1117. })
  1118. if err != nil {
  1119. return false, common.ContextError(err)
  1120. }
  1121. return duplicate, nil
  1122. }
  1123. // GetSLOK returns a SLOK key for the specified ID. The return
  1124. // value is nil if the SLOK is not found.
  1125. func GetSLOK(id []byte) (key []byte, err error) {
  1126. checkInitDataStore()
  1127. err = singleton.db.View(func(tx *bolt.Tx) error {
  1128. bucket := tx.Bucket([]byte(slokBucket))
  1129. key = bucket.Get(id)
  1130. return nil
  1131. })
  1132. if err != nil {
  1133. return nil, common.ContextError(err)
  1134. }
  1135. return key, nil
  1136. }
  1137. // TacticsStorer implements tactics.Storer.
  1138. type TacticsStorer struct {
  1139. }
  1140. func (t *TacticsStorer) SetTacticsRecord(networkID string, record []byte) error {
  1141. return setBucketValue([]byte(tacticsBucket), []byte(networkID), record)
  1142. }
  1143. func (t *TacticsStorer) GetTacticsRecord(networkID string) ([]byte, error) {
  1144. return getBucketValue([]byte(tacticsBucket), []byte(networkID))
  1145. }
  1146. func (t *TacticsStorer) SetSpeedTestSamplesRecord(networkID string, record []byte) error {
  1147. return setBucketValue([]byte(speedTestSamplesBucket), []byte(networkID), record)
  1148. }
  1149. func (t *TacticsStorer) GetSpeedTestSamplesRecord(networkID string) ([]byte, error) {
  1150. return getBucketValue([]byte(speedTestSamplesBucket), []byte(networkID))
  1151. }
  1152. // GetTacticsStorer creates a TacticsStorer.
  1153. func GetTacticsStorer() *TacticsStorer {
  1154. return &TacticsStorer{}
  1155. }
  1156. func setBucketValue(bucket, key, value []byte) error {
  1157. checkInitDataStore()
  1158. err := singleton.db.Update(func(tx *bolt.Tx) error {
  1159. bucket := tx.Bucket(bucket)
  1160. err := bucket.Put(key, value)
  1161. return err
  1162. })
  1163. if err != nil {
  1164. return common.ContextError(err)
  1165. }
  1166. return nil
  1167. }
  1168. func getBucketValue(bucket, key []byte) (value []byte, err error) {
  1169. checkInitDataStore()
  1170. err = singleton.db.View(func(tx *bolt.Tx) error {
  1171. bucket := tx.Bucket(bucket)
  1172. value = bucket.Get(key)
  1173. return nil
  1174. })
  1175. if err != nil {
  1176. return nil, common.ContextError(err)
  1177. }
  1178. return value, nil
  1179. }