dataStore.go 40 KB

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