dataStore.go 27 KB

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