dataStore.go 29 KB

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