dataStore.go 29 KB

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