dataStore.go 29 KB

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