dataStore_alt.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. // +build !windows
  2. /*
  3. * Copyright (c) 2015, Psiphon Inc.
  4. * All rights reserved.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package psiphon
  21. import (
  22. "bytes"
  23. "encoding/json"
  24. "errors"
  25. "fmt"
  26. "math/rand"
  27. "path/filepath"
  28. "strings"
  29. "sync"
  30. "time"
  31. "github.com/Psiphon-Inc/bolt"
  32. )
  33. // The BoltDB dataStore implementation is an alternative to the sqlite3-based
  34. // implementation in dataStore.go. Both implementations have the same interface.
  35. //
  36. // BoltDB is pure Go, and is intended to be used in cases where we have trouble
  37. // building sqlite3/CGO (e.g., currently go mobile due to
  38. // https://github.com/mattn/go-sqlite3/issues/201), and perhaps ultimately as
  39. // the primary dataStore implementation.
  40. //
  41. type dataStore struct {
  42. init sync.Once
  43. db *bolt.DB
  44. }
  45. const (
  46. serverEntriesBucket = "serverEntries"
  47. rankedServerEntriesBucket = "rankedServerEntries"
  48. rankedServerEntriesKey = "rankedServerEntries"
  49. splitTunnelRouteETagsBucket = "splitTunnelRouteETags"
  50. splitTunnelRouteDataBucket = "splitTunnelRouteData"
  51. urlETagsBucket = "urlETags"
  52. keyValueBucket = "keyValues"
  53. tunnelDurationsBucket = "tunnelDurations"
  54. rankedServerEntryCount = 100
  55. )
  56. var singleton dataStore
  57. // InitDataStore initializes the singleton instance of dataStore. This
  58. // function uses a sync.Once and is safe for use by concurrent goroutines.
  59. // The underlying sql.DB connection pool is also safe.
  60. //
  61. // Note: the sync.Once was more useful when initDataStore was private and
  62. // called on-demand by the public functions below. Now we require an explicit
  63. // InitDataStore() call with the filename passed in. The on-demand calls
  64. // have been replaced by checkInitDataStore() to assert that Init was called.
  65. func InitDataStore(config *Config) (err error) {
  66. singleton.init.Do(func() {
  67. filename := filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)
  68. var db *bolt.DB
  69. db, err = bolt.Open(filename, 0600, &bolt.Options{Timeout: 1 * time.Second})
  70. if err != nil {
  71. // Note: intending to set the err return value for InitDataStore
  72. err = fmt.Errorf("initDataStore failed to open database: %s", err)
  73. return
  74. }
  75. err = db.Update(func(tx *bolt.Tx) error {
  76. requiredBuckets := []string{
  77. serverEntriesBucket,
  78. rankedServerEntriesBucket,
  79. splitTunnelRouteETagsBucket,
  80. splitTunnelRouteDataBucket,
  81. urlETagsBucket,
  82. keyValueBucket,
  83. tunnelDurationsBucket,
  84. }
  85. for _, bucket := range requiredBuckets {
  86. _, err := tx.CreateBucketIfNotExists([]byte(bucket))
  87. if err != nil {
  88. return err
  89. }
  90. }
  91. return nil
  92. })
  93. if err != nil {
  94. err = fmt.Errorf("initDataStore failed to create buckets: %s", err)
  95. return
  96. }
  97. singleton.db = db
  98. resetAllTunnelDurationsToUnreported()
  99. })
  100. return err
  101. }
  102. func checkInitDataStore() {
  103. if singleton.db == nil {
  104. panic("checkInitDataStore: datastore not initialized")
  105. }
  106. }
  107. // StoreServerEntry adds the server entry to the data store.
  108. // A newly stored (or re-stored) server entry is assigned the next-to-top
  109. // rank for iteration order (the previous top ranked entry is promoted). The
  110. // purpose of inserting at next-to-top is to keep the last selected server
  111. // as the top ranked server.
  112. // When replaceIfExists is true, an existing server entry record is
  113. // overwritten; otherwise, the existing record is unchanged.
  114. // If the server entry data is malformed, an alert notice is issued and
  115. // the entry is skipped; no error is returned.
  116. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  117. checkInitDataStore()
  118. // Server entries should already be validated before this point,
  119. // so instead of skipping we fail with an error.
  120. err := ValidateServerEntry(serverEntry)
  121. if err != nil {
  122. return ContextError(errors.New("invalid server entry"))
  123. }
  124. // BoltDB implementation note:
  125. // For simplicity, we don't maintain indexes on server entry
  126. // region or supported protocols. Instead, we perform full-bucket
  127. // scans with a filter. With a small enough database (thousands or
  128. // even tens of thousand of server entries) and common enough
  129. // values (e.g., many servers support all protocols), performance
  130. // is expected to be acceptable.
  131. serverEntryExists := false
  132. err = singleton.db.Update(func(tx *bolt.Tx) error {
  133. serverEntries := tx.Bucket([]byte(serverEntriesBucket))
  134. serverEntryExists = (serverEntries.Get([]byte(serverEntry.IpAddress)) != nil)
  135. if serverEntryExists && !replaceIfExists {
  136. // Disabling this notice, for now, as it generates too much noise
  137. // in diagnostics with clients that always submit embedded servers
  138. // to the core on each run.
  139. // NoticeInfo("ignored update for server %s", serverEntry.IpAddress)
  140. return nil
  141. }
  142. data, err := json.Marshal(serverEntry)
  143. if err != nil {
  144. return ContextError(err)
  145. }
  146. err = serverEntries.Put([]byte(serverEntry.IpAddress), data)
  147. if err != nil {
  148. return ContextError(err)
  149. }
  150. err = insertRankedServerEntry(tx, serverEntry.IpAddress, 1)
  151. if err != nil {
  152. return ContextError(err)
  153. }
  154. return nil
  155. })
  156. if err != nil {
  157. return ContextError(err)
  158. }
  159. if !serverEntryExists {
  160. NoticeInfo("updated server %s", serverEntry.IpAddress)
  161. }
  162. return nil
  163. }
  164. // StoreServerEntries shuffles and stores a list of server entries.
  165. // Shuffling is performed on imported server entrues as part of client-side
  166. // load balancing.
  167. // There is an independent transaction for each entry insert/update.
  168. func StoreServerEntries(serverEntries []*ServerEntry, replaceIfExists bool) error {
  169. checkInitDataStore()
  170. for index := len(serverEntries) - 1; index > 0; index-- {
  171. swapIndex := rand.Intn(index + 1)
  172. serverEntries[index], serverEntries[swapIndex] = serverEntries[swapIndex], serverEntries[index]
  173. }
  174. for _, serverEntry := range serverEntries {
  175. err := StoreServerEntry(serverEntry, replaceIfExists)
  176. if err != nil {
  177. return ContextError(err)
  178. }
  179. }
  180. // Since there has possibly been a significant change in the server entries,
  181. // take this opportunity to update the available egress regions.
  182. ReportAvailableRegions()
  183. return nil
  184. }
  185. // PromoteServerEntry assigns the top rank (one more than current
  186. // max rank) to the specified server entry. Server candidates are
  187. // iterated in decending rank order, so this server entry will be
  188. // the first candidate in a subsequent tunnel establishment.
  189. func PromoteServerEntry(ipAddress string) error {
  190. checkInitDataStore()
  191. err := singleton.db.Update(func(tx *bolt.Tx) error {
  192. return insertRankedServerEntry(tx, ipAddress, 0)
  193. })
  194. if err != nil {
  195. return ContextError(err)
  196. }
  197. return nil
  198. }
  199. func getRankedServerEntries(tx *bolt.Tx) ([]string, error) {
  200. bucket := tx.Bucket([]byte(rankedServerEntriesBucket))
  201. data := bucket.Get([]byte(rankedServerEntriesKey))
  202. if data == nil {
  203. return []string{}, nil
  204. }
  205. rankedServerEntries := make([]string, 0)
  206. err := json.Unmarshal(data, &rankedServerEntries)
  207. if err != nil {
  208. return nil, ContextError(err)
  209. }
  210. return rankedServerEntries, nil
  211. }
  212. func setRankedServerEntries(tx *bolt.Tx, rankedServerEntries []string) error {
  213. data, err := json.Marshal(rankedServerEntries)
  214. if err != nil {
  215. return ContextError(err)
  216. }
  217. bucket := tx.Bucket([]byte(rankedServerEntriesBucket))
  218. err = bucket.Put([]byte(rankedServerEntriesKey), data)
  219. if err != nil {
  220. return ContextError(err)
  221. }
  222. return nil
  223. }
  224. func insertRankedServerEntry(tx *bolt.Tx, serverEntryId string, position int) error {
  225. rankedServerEntries, err := getRankedServerEntries(tx)
  226. if err != nil {
  227. return ContextError(err)
  228. }
  229. // BoltDB implementation note:
  230. // For simplicity, we store the ranked server ids in an array serialized to
  231. // a single key value. To ensure this value doesn't grow without bound,
  232. // it's capped at rankedServerEntryCount. For now, this cap should be large
  233. // enough to meet the shuffleHeadLength = config.TunnelPoolSize criteria, for
  234. // any reasonable configuration of config.TunnelPoolSize.
  235. if position >= len(rankedServerEntries) {
  236. rankedServerEntries = append(rankedServerEntries, serverEntryId)
  237. } else {
  238. end := len(rankedServerEntries)
  239. if end+1 > rankedServerEntryCount {
  240. end = rankedServerEntryCount
  241. }
  242. // insert: https://github.com/golang/go/wiki/SliceTricks
  243. rankedServerEntries = append(
  244. rankedServerEntries[:position],
  245. append([]string{serverEntryId},
  246. rankedServerEntries[position:end]...)...)
  247. }
  248. err = setRankedServerEntries(tx, rankedServerEntries)
  249. if err != nil {
  250. return ContextError(err)
  251. }
  252. return nil
  253. }
  254. func serverEntrySupportsProtocol(serverEntry *ServerEntry, protocol string) bool {
  255. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  256. // and the additonal OSSH service is assumed to be available internally.
  257. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  258. return Contains(serverEntry.Capabilities, requiredCapability)
  259. }
  260. // ServerEntryIterator is used to iterate over
  261. // stored server entries in rank order.
  262. type ServerEntryIterator struct {
  263. region string
  264. protocol string
  265. shuffleHeadLength int
  266. serverEntryIds []string
  267. serverEntryIndex int
  268. isTargetServerEntryIterator bool
  269. hasNextTargetServerEntry bool
  270. targetServerEntry *ServerEntry
  271. }
  272. // NewServerEntryIterator creates a new ServerEntryIterator
  273. func NewServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  274. // When configured, this target server entry is the only candidate
  275. if config.TargetServerEntry != "" {
  276. return newTargetServerEntryIterator(config)
  277. }
  278. checkInitDataStore()
  279. iterator = &ServerEntryIterator{
  280. region: config.EgressRegion,
  281. protocol: config.TunnelProtocol,
  282. shuffleHeadLength: config.TunnelPoolSize,
  283. isTargetServerEntryIterator: false,
  284. }
  285. err = iterator.Reset()
  286. if err != nil {
  287. return nil, err
  288. }
  289. return iterator, nil
  290. }
  291. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  292. func newTargetServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  293. serverEntry, err := DecodeServerEntry(config.TargetServerEntry)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  298. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  299. }
  300. if config.TunnelProtocol != "" {
  301. // Note: same capability/protocol mapping as in StoreServerEntry
  302. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  303. if !Contains(serverEntry.Capabilities, requiredCapability) {
  304. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  305. }
  306. }
  307. iterator = &ServerEntryIterator{
  308. isTargetServerEntryIterator: true,
  309. hasNextTargetServerEntry: true,
  310. targetServerEntry: serverEntry,
  311. }
  312. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  313. return iterator, nil
  314. }
  315. // Reset a NewServerEntryIterator to the start of its cycle. The next
  316. // call to Next will return the first server entry.
  317. func (iterator *ServerEntryIterator) Reset() error {
  318. iterator.Close()
  319. if iterator.isTargetServerEntryIterator {
  320. iterator.hasNextTargetServerEntry = true
  321. return nil
  322. }
  323. count := CountServerEntries(iterator.region, iterator.protocol)
  324. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  325. // This query implements the Psiphon server candidate selection
  326. // algorithm: the first TunnelPoolSize server candidates are in rank
  327. // (priority) order, to favor previously successful servers; then the
  328. // remaining long tail is shuffled to raise up less recent candidates.
  329. // BoltDB implementation note:
  330. // We don't keep a transaction open for the duration of the iterator
  331. // because this would expose the following semantics to consumer code:
  332. //
  333. // Read-only transactions and read-write transactions ... generally
  334. // shouldn't be opened simultaneously in the same goroutine. This can
  335. // cause a deadlock as the read-write transaction needs to periodically
  336. // re-map the data file but it cannot do so while a read-only
  337. // transaction is open.
  338. // (https://github.com/boltdb/bolt)
  339. //
  340. // So the underlying serverEntriesBucket could change after the serverEntryIds
  341. // list is built.
  342. var serverEntryIds []string
  343. err := singleton.db.View(func(tx *bolt.Tx) error {
  344. var err error
  345. serverEntryIds, err = getRankedServerEntries(tx)
  346. if err != nil {
  347. return err
  348. }
  349. skipServerEntryIds := make(map[string]bool)
  350. for _, serverEntryId := range serverEntryIds {
  351. skipServerEntryIds[serverEntryId] = true
  352. }
  353. bucket := tx.Bucket([]byte(serverEntriesBucket))
  354. cursor := bucket.Cursor()
  355. for key, _ := cursor.Last(); key != nil; key, _ = cursor.Prev() {
  356. serverEntryId := string(key)
  357. if _, ok := skipServerEntryIds[serverEntryId]; ok {
  358. continue
  359. }
  360. serverEntryIds = append(serverEntryIds, serverEntryId)
  361. }
  362. return nil
  363. })
  364. if err != nil {
  365. return ContextError(err)
  366. }
  367. for i := len(serverEntryIds) - 1; i > iterator.shuffleHeadLength-1; i-- {
  368. j := rand.Intn(i+1-iterator.shuffleHeadLength) + iterator.shuffleHeadLength
  369. serverEntryIds[i], serverEntryIds[j] = serverEntryIds[j], serverEntryIds[i]
  370. }
  371. iterator.serverEntryIds = serverEntryIds
  372. iterator.serverEntryIndex = 0
  373. return nil
  374. }
  375. // Close cleans up resources associated with a ServerEntryIterator.
  376. func (iterator *ServerEntryIterator) Close() {
  377. iterator.serverEntryIds = nil
  378. iterator.serverEntryIndex = 0
  379. }
  380. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  381. // Returns nil with no error when there is no next item.
  382. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  383. defer func() {
  384. if err != nil {
  385. iterator.Close()
  386. }
  387. }()
  388. if iterator.isTargetServerEntryIterator {
  389. if iterator.hasNextTargetServerEntry {
  390. iterator.hasNextTargetServerEntry = false
  391. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  392. }
  393. return nil, nil
  394. }
  395. // There are no region/protocol indexes for the server entries bucket.
  396. // Loop until we have the next server entry that matches the iterator
  397. // filter requirements.
  398. for {
  399. if iterator.serverEntryIndex >= len(iterator.serverEntryIds) {
  400. // There is no next item
  401. return nil, nil
  402. }
  403. serverEntryId := iterator.serverEntryIds[iterator.serverEntryIndex]
  404. iterator.serverEntryIndex += 1
  405. var data []byte
  406. err = singleton.db.View(func(tx *bolt.Tx) error {
  407. bucket := tx.Bucket([]byte(serverEntriesBucket))
  408. data = bucket.Get([]byte(serverEntryId))
  409. return nil
  410. })
  411. if err != nil {
  412. return nil, ContextError(err)
  413. }
  414. if data == nil {
  415. return nil, ContextError(
  416. fmt.Errorf("Unexpected missing server entry: %s", serverEntryId))
  417. }
  418. serverEntry = new(ServerEntry)
  419. err = json.Unmarshal(data, serverEntry)
  420. if err != nil {
  421. return nil, ContextError(err)
  422. }
  423. if (iterator.region == "" || serverEntry.Region == iterator.region) &&
  424. (iterator.protocol == "" || serverEntrySupportsProtocol(serverEntry, iterator.protocol)) {
  425. break
  426. }
  427. }
  428. return MakeCompatibleServerEntry(serverEntry), nil
  429. }
  430. // MakeCompatibleServerEntry provides backwards compatibility with old server entries
  431. // which have a single meekFrontingDomain and not a meekFrontingAddresses array.
  432. // By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
  433. // uses that single value as legacy clients do.
  434. func MakeCompatibleServerEntry(serverEntry *ServerEntry) *ServerEntry {
  435. if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
  436. serverEntry.MeekFrontingAddresses =
  437. append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
  438. }
  439. return serverEntry
  440. }
  441. func scanServerEntries(scanner func(*ServerEntry)) error {
  442. err := singleton.db.View(func(tx *bolt.Tx) error {
  443. bucket := tx.Bucket([]byte(serverEntriesBucket))
  444. cursor := bucket.Cursor()
  445. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  446. serverEntry := new(ServerEntry)
  447. err := json.Unmarshal(value, serverEntry)
  448. if err != nil {
  449. return err
  450. }
  451. scanner(serverEntry)
  452. }
  453. return nil
  454. })
  455. if err != nil {
  456. return ContextError(err)
  457. }
  458. return nil
  459. }
  460. // CountServerEntries returns a count of stored servers for the
  461. // specified region and protocol.
  462. func CountServerEntries(region, protocol string) int {
  463. checkInitDataStore()
  464. count := 0
  465. err := scanServerEntries(func(serverEntry *ServerEntry) {
  466. if (region == "" || serverEntry.Region == region) &&
  467. (protocol == "" || serverEntrySupportsProtocol(serverEntry, protocol)) {
  468. count += 1
  469. }
  470. })
  471. if err != nil {
  472. NoticeAlert("CountServerEntries failed: %s", err)
  473. return 0
  474. }
  475. return count
  476. }
  477. // ReportAvailableRegions prints a notice with the available egress regions.
  478. // Note that this report ignores config.TunnelProtocol.
  479. func ReportAvailableRegions() {
  480. checkInitDataStore()
  481. regions := make(map[string]bool)
  482. err := scanServerEntries(func(serverEntry *ServerEntry) {
  483. regions[serverEntry.Region] = true
  484. })
  485. if err != nil {
  486. NoticeAlert("ReportAvailableRegions failed: %s", err)
  487. return
  488. }
  489. regionList := make([]string, 0, len(regions))
  490. for region, _ := range regions {
  491. // Some server entries do not have a region, but it makes no sense to return
  492. // an empty string as an "available region".
  493. if region != "" {
  494. regionList = append(regionList, region)
  495. }
  496. }
  497. NoticeAvailableEgressRegions(regionList)
  498. }
  499. // GetServerEntryIpAddresses returns an array containing
  500. // all stored server IP addresses.
  501. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  502. checkInitDataStore()
  503. ipAddresses = make([]string, 0)
  504. err = scanServerEntries(func(serverEntry *ServerEntry) {
  505. ipAddresses = append(ipAddresses, serverEntry.IpAddress)
  506. })
  507. if err != nil {
  508. return nil, ContextError(err)
  509. }
  510. return ipAddresses, nil
  511. }
  512. // SetSplitTunnelRoutes updates the cached routes data for
  513. // the given region. The associated etag is also stored and
  514. // used to make efficient web requests for updates to the data.
  515. func SetSplitTunnelRoutes(region, etag string, data []byte) error {
  516. checkInitDataStore()
  517. err := singleton.db.Update(func(tx *bolt.Tx) error {
  518. bucket := tx.Bucket([]byte(splitTunnelRouteETagsBucket))
  519. err := bucket.Put([]byte(region), []byte(etag))
  520. bucket = tx.Bucket([]byte(splitTunnelRouteDataBucket))
  521. err = bucket.Put([]byte(region), data)
  522. return err
  523. })
  524. if err != nil {
  525. return ContextError(err)
  526. }
  527. return nil
  528. }
  529. // GetSplitTunnelRoutesETag retrieves the etag for cached routes
  530. // data for the specified region. If not found, it returns an empty string value.
  531. func GetSplitTunnelRoutesETag(region string) (etag string, err error) {
  532. checkInitDataStore()
  533. err = singleton.db.View(func(tx *bolt.Tx) error {
  534. bucket := tx.Bucket([]byte(splitTunnelRouteETagsBucket))
  535. etag = string(bucket.Get([]byte(region)))
  536. return nil
  537. })
  538. if err != nil {
  539. return "", ContextError(err)
  540. }
  541. return etag, nil
  542. }
  543. // GetSplitTunnelRoutesData retrieves the cached routes data
  544. // for the specified region. If not found, it returns a nil value.
  545. func GetSplitTunnelRoutesData(region string) (data []byte, err error) {
  546. checkInitDataStore()
  547. err = singleton.db.View(func(tx *bolt.Tx) error {
  548. bucket := tx.Bucket([]byte(splitTunnelRouteDataBucket))
  549. data = bucket.Get([]byte(region))
  550. return nil
  551. })
  552. if err != nil {
  553. return nil, ContextError(err)
  554. }
  555. return data, nil
  556. }
  557. // SetUrlETag stores an ETag for the specfied URL.
  558. // Note: input URL is treated as a string, and is not
  559. // encoded or decoded or otherwise canonicalized.
  560. func SetUrlETag(url, etag string) error {
  561. checkInitDataStore()
  562. err := singleton.db.Update(func(tx *bolt.Tx) error {
  563. bucket := tx.Bucket([]byte(urlETagsBucket))
  564. err := bucket.Put([]byte(url), []byte(etag))
  565. return err
  566. })
  567. if err != nil {
  568. return ContextError(err)
  569. }
  570. return nil
  571. }
  572. // GetUrlETag retrieves a previously stored an ETag for the
  573. // specfied URL. If not found, it returns an empty string value.
  574. func GetUrlETag(url string) (etag string, err error) {
  575. checkInitDataStore()
  576. err = singleton.db.View(func(tx *bolt.Tx) error {
  577. bucket := tx.Bucket([]byte(urlETagsBucket))
  578. etag = string(bucket.Get([]byte(url)))
  579. return nil
  580. })
  581. if err != nil {
  582. return "", ContextError(err)
  583. }
  584. return etag, nil
  585. }
  586. // SetKeyValue stores a key/value pair.
  587. func SetKeyValue(key, value string) error {
  588. checkInitDataStore()
  589. err := singleton.db.Update(func(tx *bolt.Tx) error {
  590. bucket := tx.Bucket([]byte(keyValueBucket))
  591. err := bucket.Put([]byte(key), []byte(value))
  592. return err
  593. })
  594. if err != nil {
  595. return ContextError(err)
  596. }
  597. return nil
  598. }
  599. // GetKeyValue retrieves the value for a given key. If not found,
  600. // it returns an empty string value.
  601. func GetKeyValue(key string) (value string, err error) {
  602. checkInitDataStore()
  603. err = singleton.db.View(func(tx *bolt.Tx) error {
  604. bucket := tx.Bucket([]byte(keyValueBucket))
  605. value = string(bucket.Get([]byte(key)))
  606. return nil
  607. })
  608. if err != nil {
  609. return "", ContextError(err)
  610. }
  611. return value, nil
  612. }
  613. // Tunnel duration records in the tunnelDurationStateUnreported
  614. // state are available for take out.
  615. // Records in the tunnelDurationStateReporting have been
  616. // taken out and are pending either deleting (for a
  617. // successful request) or change to StateUnreported (for
  618. // a failed request).
  619. // All tunnel durations are reverted to StateUnreported when
  620. // the datastore is initialized at start up.
  621. var tunnelDurationStateUnreported = []byte("0")
  622. var tunnelDurationStateReporting = []byte("1")
  623. // StoreTunnelDuration adds a new tunnel duration, which is
  624. // set to StateUnreported and is an immediate candidate for
  625. // reporting.
  626. // tunnelDuration is a JSON byte array containing fields as
  627. // required by the Psiphon server API (see RecordTunnelDuration).
  628. // It's assumed that the JSON value contains enough unique
  629. // information for the value to function as a key in the
  630. // key/value datastore. This assumption is currently satisfied
  631. // by the fields sessionId + tunnelNumber.
  632. func StoreTunnelDuration(tunnelDuration []byte) error {
  633. checkInitDataStore()
  634. err := singleton.db.Update(func(tx *bolt.Tx) error {
  635. bucket := tx.Bucket([]byte(tunnelDurationsBucket))
  636. err := bucket.Put(tunnelDuration, tunnelDurationStateUnreported)
  637. return err
  638. })
  639. if err != nil {
  640. return ContextError(err)
  641. }
  642. return nil
  643. }
  644. // CountUnreportedTunnelDurations returns the number of tunnel
  645. // duration records in StateUnreported.
  646. func CountUnreportedTunnelDurations() int {
  647. checkInitDataStore()
  648. unreported := 0
  649. err := singleton.db.Update(func(tx *bolt.Tx) error {
  650. bucket := tx.Bucket([]byte(tunnelDurationsBucket))
  651. cursor := bucket.Cursor()
  652. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  653. if 0 == bytes.Compare(value, tunnelDurationStateUnreported) {
  654. unreported++
  655. break
  656. }
  657. }
  658. return nil
  659. })
  660. if err != nil {
  661. NoticeAlert("CountUnreportedTunnelDurations failed: %s", err)
  662. return 0
  663. }
  664. return unreported
  665. }
  666. // TakeOutUnreportedTunnelDurations returns up to maxCount tunnel
  667. // durations that are in StateUnreported. The records are set to
  668. // StateReporting. If the records are successfully reported,
  669. // clear them with ClearReportedTunnelDurations. If the records are
  670. // not successfully reported, restore them with
  671. // PutBackUnreportedTunnelDurations.
  672. func TakeOutUnreportedTunnelDurations(maxCount int) ([][]byte, error) {
  673. checkInitDataStore()
  674. tunnelDurations := make([][]byte, 0)
  675. err := singleton.db.Update(func(tx *bolt.Tx) error {
  676. bucket := tx.Bucket([]byte(tunnelDurationsBucket))
  677. cursor := bucket.Cursor()
  678. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  679. if 0 == bytes.Compare(value, tunnelDurationStateUnreported) {
  680. err := bucket.Put(key, tunnelDurationStateReporting)
  681. if err != nil {
  682. return err
  683. }
  684. tunnelDurations = append(tunnelDurations, key)
  685. if len(tunnelDurations) >= maxCount {
  686. break
  687. }
  688. }
  689. }
  690. return nil
  691. })
  692. if err != nil {
  693. return nil, ContextError(err)
  694. }
  695. return tunnelDurations, nil
  696. }
  697. // PutBackUnreportedTunnelDurations restores a list of tunnel
  698. // durations to StateUnreported.
  699. func PutBackUnreportedTunnelDurations(tunnelDurations [][]byte) error {
  700. checkInitDataStore()
  701. err := singleton.db.Update(func(tx *bolt.Tx) error {
  702. bucket := tx.Bucket([]byte(tunnelDurationsBucket))
  703. for _, tunnelDuration := range tunnelDurations {
  704. err := bucket.Put(tunnelDuration, tunnelDurationStateUnreported)
  705. if err != nil {
  706. return err
  707. }
  708. }
  709. return nil
  710. })
  711. if err != nil {
  712. return ContextError(err)
  713. }
  714. return nil
  715. }
  716. // ClearReportedTunnelDurations deletes a list of tunnel
  717. // durations that were succesdfully reported.
  718. func ClearReportedTunnelDurations(tunnelDurations [][]byte) error {
  719. checkInitDataStore()
  720. err := singleton.db.Update(func(tx *bolt.Tx) error {
  721. bucket := tx.Bucket([]byte(tunnelDurationsBucket))
  722. for _, tunnelDuration := range tunnelDurations {
  723. err := bucket.Delete(tunnelDuration)
  724. if err != nil {
  725. return err
  726. }
  727. }
  728. return nil
  729. })
  730. if err != nil {
  731. return ContextError(err)
  732. }
  733. return nil
  734. }
  735. // resetAllTunnelDurationsToUnreported sets all tunnel
  736. // duration records to StateUnreported. This reset is called
  737. // when the datastore is initialized at start up, as we do
  738. // not know if tunnel records in StateReporting were reported
  739. // or not.
  740. func resetAllTunnelDurationsToUnreported() error {
  741. checkInitDataStore()
  742. err := singleton.db.Update(func(tx *bolt.Tx) error {
  743. bucket := tx.Bucket([]byte(tunnelDurationsBucket))
  744. cursor := bucket.Cursor()
  745. for key, _ := cursor.First(); key != nil; key, _ = cursor.Next() {
  746. err := bucket.Put(key, tunnelDurationStateUnreported)
  747. if err != nil {
  748. return err
  749. }
  750. }
  751. return nil
  752. })
  753. if err != nil {
  754. return ContextError(err)
  755. }
  756. return nil
  757. }