dataStore.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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(
  339. config.TargetServerEntry, GetCurrentTimestamp(), SERVER_ENTRY_SOURCE_TARGET)
  340. if err != nil {
  341. return nil, err
  342. }
  343. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  344. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  345. }
  346. if config.TunnelProtocol != "" {
  347. // Note: same capability/protocol mapping as in StoreServerEntry
  348. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  349. if !Contains(serverEntry.Capabilities, requiredCapability) {
  350. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  351. }
  352. }
  353. iterator = &ServerEntryIterator{
  354. isTargetServerEntryIterator: true,
  355. hasNextTargetServerEntry: true,
  356. targetServerEntry: serverEntry,
  357. }
  358. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  359. return iterator, nil
  360. }
  361. // Reset a NewServerEntryIterator to the start of its cycle. The next
  362. // call to Next will return the first server entry.
  363. func (iterator *ServerEntryIterator) Reset() error {
  364. iterator.Close()
  365. if iterator.isTargetServerEntryIterator {
  366. iterator.hasNextTargetServerEntry = true
  367. return nil
  368. }
  369. count := CountServerEntries(iterator.region, iterator.protocol)
  370. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  371. // This query implements the Psiphon server candidate selection
  372. // algorithm: the first TunnelPoolSize server candidates are in rank
  373. // (priority) order, to favor previously successful servers; then the
  374. // remaining long tail is shuffled to raise up less recent candidates.
  375. // BoltDB implementation note:
  376. // We don't keep a transaction open for the duration of the iterator
  377. // because this would expose the following semantics to consumer code:
  378. //
  379. // Read-only transactions and read-write transactions ... generally
  380. // shouldn't be opened simultaneously in the same goroutine. This can
  381. // cause a deadlock as the read-write transaction needs to periodically
  382. // re-map the data file but it cannot do so while a read-only
  383. // transaction is open.
  384. // (https://github.com/boltdb/bolt)
  385. //
  386. // So the underlying serverEntriesBucket could change after the serverEntryIds
  387. // list is built.
  388. var serverEntryIds []string
  389. err := singleton.db.View(func(tx *bolt.Tx) error {
  390. var err error
  391. serverEntryIds, err = getRankedServerEntries(tx)
  392. if err != nil {
  393. return err
  394. }
  395. skipServerEntryIds := make(map[string]bool)
  396. for _, serverEntryId := range serverEntryIds {
  397. skipServerEntryIds[serverEntryId] = true
  398. }
  399. bucket := tx.Bucket([]byte(serverEntriesBucket))
  400. cursor := bucket.Cursor()
  401. for key, _ := cursor.Last(); key != nil; key, _ = cursor.Prev() {
  402. serverEntryId := string(key)
  403. if _, ok := skipServerEntryIds[serverEntryId]; ok {
  404. continue
  405. }
  406. serverEntryIds = append(serverEntryIds, serverEntryId)
  407. }
  408. return nil
  409. })
  410. if err != nil {
  411. return ContextError(err)
  412. }
  413. for i := len(serverEntryIds) - 1; i > iterator.shuffleHeadLength-1; i-- {
  414. j := rand.Intn(i+1-iterator.shuffleHeadLength) + iterator.shuffleHeadLength
  415. serverEntryIds[i], serverEntryIds[j] = serverEntryIds[j], serverEntryIds[i]
  416. }
  417. iterator.serverEntryIds = serverEntryIds
  418. iterator.serverEntryIndex = 0
  419. return nil
  420. }
  421. // Close cleans up resources associated with a ServerEntryIterator.
  422. func (iterator *ServerEntryIterator) Close() {
  423. iterator.serverEntryIds = nil
  424. iterator.serverEntryIndex = 0
  425. }
  426. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  427. // Returns nil with no error when there is no next item.
  428. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  429. defer func() {
  430. if err != nil {
  431. iterator.Close()
  432. }
  433. }()
  434. if iterator.isTargetServerEntryIterator {
  435. if iterator.hasNextTargetServerEntry {
  436. iterator.hasNextTargetServerEntry = false
  437. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  438. }
  439. return nil, nil
  440. }
  441. // There are no region/protocol indexes for the server entries bucket.
  442. // Loop until we have the next server entry that matches the iterator
  443. // filter requirements.
  444. for {
  445. if iterator.serverEntryIndex >= len(iterator.serverEntryIds) {
  446. // There is no next item
  447. return nil, nil
  448. }
  449. serverEntryId := iterator.serverEntryIds[iterator.serverEntryIndex]
  450. iterator.serverEntryIndex += 1
  451. var data []byte
  452. err = singleton.db.View(func(tx *bolt.Tx) error {
  453. bucket := tx.Bucket([]byte(serverEntriesBucket))
  454. value := bucket.Get([]byte(serverEntryId))
  455. if value != nil {
  456. // Must make a copy as slice is only valid within transaction.
  457. data = make([]byte, len(value))
  458. copy(data, value)
  459. }
  460. return nil
  461. })
  462. if err != nil {
  463. return nil, ContextError(err)
  464. }
  465. if data == nil {
  466. // In case of data corruption or a bug causing this condition,
  467. // do not stop iterating.
  468. NoticeAlert("ServerEntryIterator.Next: unexpected missing server entry: %s", serverEntryId)
  469. continue
  470. }
  471. serverEntry = new(ServerEntry)
  472. err = json.Unmarshal(data, serverEntry)
  473. if err != nil {
  474. // In case of data corruption or a bug causing this condition,
  475. // do not stop iterating.
  476. NoticeAlert("ServerEntryIterator.Next: %s", ContextError(err))
  477. continue
  478. }
  479. // Check filter requirements
  480. if (iterator.region == "" || serverEntry.Region == iterator.region) &&
  481. (iterator.protocol == "" || serverEntrySupportsProtocol(serverEntry, iterator.protocol)) {
  482. break
  483. }
  484. }
  485. return MakeCompatibleServerEntry(serverEntry), nil
  486. }
  487. // MakeCompatibleServerEntry provides backwards compatibility with old server entries
  488. // which have a single meekFrontingDomain and not a meekFrontingAddresses array.
  489. // By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
  490. // uses that single value as legacy clients do.
  491. func MakeCompatibleServerEntry(serverEntry *ServerEntry) *ServerEntry {
  492. if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
  493. serverEntry.MeekFrontingAddresses =
  494. append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
  495. }
  496. return serverEntry
  497. }
  498. func scanServerEntries(scanner func(*ServerEntry)) error {
  499. err := singleton.db.View(func(tx *bolt.Tx) error {
  500. bucket := tx.Bucket([]byte(serverEntriesBucket))
  501. cursor := bucket.Cursor()
  502. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  503. serverEntry := new(ServerEntry)
  504. err := json.Unmarshal(value, serverEntry)
  505. if err != nil {
  506. // In case of data corruption or a bug causing this condition,
  507. // do not stop iterating.
  508. NoticeAlert("scanServerEntries: %s", ContextError(err))
  509. continue
  510. }
  511. scanner(serverEntry)
  512. }
  513. return nil
  514. })
  515. if err != nil {
  516. return ContextError(err)
  517. }
  518. return nil
  519. }
  520. // CountServerEntries returns a count of stored servers for the
  521. // specified region and protocol.
  522. func CountServerEntries(region, protocol string) int {
  523. checkInitDataStore()
  524. count := 0
  525. err := scanServerEntries(func(serverEntry *ServerEntry) {
  526. if (region == "" || serverEntry.Region == region) &&
  527. (protocol == "" || serverEntrySupportsProtocol(serverEntry, protocol)) {
  528. count += 1
  529. }
  530. })
  531. if err != nil {
  532. NoticeAlert("CountServerEntries failed: %s", err)
  533. return 0
  534. }
  535. return count
  536. }
  537. // ReportAvailableRegions prints a notice with the available egress regions.
  538. // Note that this report ignores config.TunnelProtocol.
  539. func ReportAvailableRegions() {
  540. checkInitDataStore()
  541. regions := make(map[string]bool)
  542. err := scanServerEntries(func(serverEntry *ServerEntry) {
  543. regions[serverEntry.Region] = true
  544. })
  545. if err != nil {
  546. NoticeAlert("ReportAvailableRegions failed: %s", err)
  547. return
  548. }
  549. regionList := make([]string, 0, len(regions))
  550. for region, _ := range regions {
  551. // Some server entries do not have a region, but it makes no sense to return
  552. // an empty string as an "available region".
  553. if region != "" {
  554. regionList = append(regionList, region)
  555. }
  556. }
  557. NoticeAvailableEgressRegions(regionList)
  558. }
  559. // GetServerEntryIpAddresses returns an array containing
  560. // all stored server IP addresses.
  561. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  562. checkInitDataStore()
  563. ipAddresses = make([]string, 0)
  564. err = scanServerEntries(func(serverEntry *ServerEntry) {
  565. ipAddresses = append(ipAddresses, serverEntry.IpAddress)
  566. })
  567. if err != nil {
  568. return nil, ContextError(err)
  569. }
  570. return ipAddresses, nil
  571. }
  572. // SetSplitTunnelRoutes updates the cached routes data for
  573. // the given region. The associated etag is also stored and
  574. // used to make efficient web requests for updates to the data.
  575. func SetSplitTunnelRoutes(region, etag string, data []byte) error {
  576. checkInitDataStore()
  577. err := singleton.db.Update(func(tx *bolt.Tx) error {
  578. bucket := tx.Bucket([]byte(splitTunnelRouteETagsBucket))
  579. err := bucket.Put([]byte(region), []byte(etag))
  580. bucket = tx.Bucket([]byte(splitTunnelRouteDataBucket))
  581. err = bucket.Put([]byte(region), data)
  582. return err
  583. })
  584. if err != nil {
  585. return ContextError(err)
  586. }
  587. return nil
  588. }
  589. // GetSplitTunnelRoutesETag retrieves the etag for cached routes
  590. // data for the specified region. If not found, it returns an empty string value.
  591. func GetSplitTunnelRoutesETag(region string) (etag string, err error) {
  592. checkInitDataStore()
  593. err = singleton.db.View(func(tx *bolt.Tx) error {
  594. bucket := tx.Bucket([]byte(splitTunnelRouteETagsBucket))
  595. etag = string(bucket.Get([]byte(region)))
  596. return nil
  597. })
  598. if err != nil {
  599. return "", ContextError(err)
  600. }
  601. return etag, nil
  602. }
  603. // GetSplitTunnelRoutesData retrieves the cached routes data
  604. // for the specified region. If not found, it returns a nil value.
  605. func GetSplitTunnelRoutesData(region string) (data []byte, err error) {
  606. checkInitDataStore()
  607. err = singleton.db.View(func(tx *bolt.Tx) error {
  608. bucket := tx.Bucket([]byte(splitTunnelRouteDataBucket))
  609. value := bucket.Get([]byte(region))
  610. if value != nil {
  611. // Must make a copy as slice is only valid within transaction.
  612. data = make([]byte, len(value))
  613. copy(data, value)
  614. }
  615. return nil
  616. })
  617. if err != nil {
  618. return nil, ContextError(err)
  619. }
  620. return data, nil
  621. }
  622. // SetUrlETag stores an ETag for the specfied URL.
  623. // Note: input URL is treated as a string, and is not
  624. // encoded or decoded or otherwise canonicalized.
  625. func SetUrlETag(url, etag string) error {
  626. checkInitDataStore()
  627. err := singleton.db.Update(func(tx *bolt.Tx) error {
  628. bucket := tx.Bucket([]byte(urlETagsBucket))
  629. err := bucket.Put([]byte(url), []byte(etag))
  630. return err
  631. })
  632. if err != nil {
  633. return ContextError(err)
  634. }
  635. return nil
  636. }
  637. // GetUrlETag retrieves a previously stored an ETag for the
  638. // specfied URL. If not found, it returns an empty string value.
  639. func GetUrlETag(url string) (etag string, err error) {
  640. checkInitDataStore()
  641. err = singleton.db.View(func(tx *bolt.Tx) error {
  642. bucket := tx.Bucket([]byte(urlETagsBucket))
  643. etag = string(bucket.Get([]byte(url)))
  644. return nil
  645. })
  646. if err != nil {
  647. return "", ContextError(err)
  648. }
  649. return etag, nil
  650. }
  651. // SetKeyValue stores a key/value pair.
  652. func SetKeyValue(key, value string) error {
  653. checkInitDataStore()
  654. err := singleton.db.Update(func(tx *bolt.Tx) error {
  655. bucket := tx.Bucket([]byte(keyValueBucket))
  656. err := bucket.Put([]byte(key), []byte(value))
  657. return err
  658. })
  659. if err != nil {
  660. return ContextError(err)
  661. }
  662. return nil
  663. }
  664. // GetKeyValue retrieves the value for a given key. If not found,
  665. // it returns an empty string value.
  666. func GetKeyValue(key string) (value string, err error) {
  667. checkInitDataStore()
  668. err = singleton.db.View(func(tx *bolt.Tx) error {
  669. bucket := tx.Bucket([]byte(keyValueBucket))
  670. value = string(bucket.Get([]byte(key)))
  671. return nil
  672. })
  673. if err != nil {
  674. return "", ContextError(err)
  675. }
  676. return value, nil
  677. }
  678. // Tunnel stats records in the tunnelStatsStateUnreported
  679. // state are available for take out.
  680. // Records in the tunnelStatsStateReporting have been
  681. // taken out and are pending either deleting (for a
  682. // successful request) or change to StateUnreported (for
  683. // a failed request).
  684. // All tunnel stats records are reverted to StateUnreported
  685. // when the datastore is initialized at start up.
  686. var tunnelStatsStateUnreported = []byte("0")
  687. var tunnelStatsStateReporting = []byte("1")
  688. // StoreTunnelStats adds a new tunnel stats record, which is
  689. // set to StateUnreported and is an immediate candidate for
  690. // reporting.
  691. // tunnelStats is a JSON byte array containing fields as
  692. // required by the Psiphon server API (see RecordTunnelStats).
  693. // It's assumed that the JSON value contains enough unique
  694. // information for the value to function as a key in the
  695. // key/value datastore. This assumption is currently satisfied
  696. // by the fields sessionId + tunnelNumber.
  697. func StoreTunnelStats(tunnelStats []byte) error {
  698. checkInitDataStore()
  699. err := singleton.db.Update(func(tx *bolt.Tx) error {
  700. bucket := tx.Bucket([]byte(tunnelStatsBucket))
  701. err := bucket.Put(tunnelStats, tunnelStatsStateUnreported)
  702. return err
  703. })
  704. if err != nil {
  705. return ContextError(err)
  706. }
  707. return nil
  708. }
  709. // CountUnreportedTunnelStats returns the number of tunnel
  710. // stats records in StateUnreported.
  711. func CountUnreportedTunnelStats() int {
  712. checkInitDataStore()
  713. unreported := 0
  714. err := singleton.db.Update(func(tx *bolt.Tx) error {
  715. bucket := tx.Bucket([]byte(tunnelStatsBucket))
  716. cursor := bucket.Cursor()
  717. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  718. if 0 == bytes.Compare(value, tunnelStatsStateUnreported) {
  719. unreported++
  720. break
  721. }
  722. }
  723. return nil
  724. })
  725. if err != nil {
  726. NoticeAlert("CountUnreportedTunnelStats failed: %s", err)
  727. return 0
  728. }
  729. return unreported
  730. }
  731. // TakeOutUnreportedTunnelStats returns up to maxCount tunnel
  732. // stats records that are in StateUnreported. The records are set
  733. // to StateReporting. If the records are successfully reported,
  734. // clear them with ClearReportedTunnelStats. If the records are
  735. // not successfully reported, restore them with
  736. // PutBackUnreportedTunnelStats.
  737. func TakeOutUnreportedTunnelStats(maxCount int) ([][]byte, error) {
  738. checkInitDataStore()
  739. tunnelStats := make([][]byte, 0)
  740. err := singleton.db.Update(func(tx *bolt.Tx) error {
  741. bucket := tx.Bucket([]byte(tunnelStatsBucket))
  742. cursor := bucket.Cursor()
  743. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  744. // Perform a test JSON unmarshaling. In case of data corruption or a bug,
  745. // skip the record.
  746. var jsonData interface{}
  747. err := json.Unmarshal(key, &jsonData)
  748. if err != nil {
  749. NoticeAlert(
  750. "Invalid key in TakeOutUnreportedTunnelStats: %s: %s",
  751. string(key), err)
  752. continue
  753. }
  754. if 0 == bytes.Compare(value, tunnelStatsStateUnreported) {
  755. // Must make a copy as slice is only valid within transaction.
  756. data := make([]byte, len(key))
  757. copy(data, key)
  758. tunnelStats = append(tunnelStats, data)
  759. if len(tunnelStats) >= maxCount {
  760. break
  761. }
  762. }
  763. }
  764. for _, key := range tunnelStats {
  765. err := bucket.Put(key, tunnelStatsStateReporting)
  766. if err != nil {
  767. return err
  768. }
  769. }
  770. return nil
  771. })
  772. if err != nil {
  773. return nil, ContextError(err)
  774. }
  775. return tunnelStats, nil
  776. }
  777. // PutBackUnreportedTunnelStats restores a list of tunnel
  778. // stats records to StateUnreported.
  779. func PutBackUnreportedTunnelStats(tunnelStats [][]byte) error {
  780. checkInitDataStore()
  781. err := singleton.db.Update(func(tx *bolt.Tx) error {
  782. bucket := tx.Bucket([]byte(tunnelStatsBucket))
  783. for _, key := range tunnelStats {
  784. err := bucket.Put(key, tunnelStatsStateUnreported)
  785. if err != nil {
  786. return err
  787. }
  788. }
  789. return nil
  790. })
  791. if err != nil {
  792. return ContextError(err)
  793. }
  794. return nil
  795. }
  796. // ClearReportedTunnelStats deletes a list of tunnel
  797. // stats records that were succesdfully reported.
  798. func ClearReportedTunnelStats(tunnelStats [][]byte) error {
  799. checkInitDataStore()
  800. err := singleton.db.Update(func(tx *bolt.Tx) error {
  801. bucket := tx.Bucket([]byte(tunnelStatsBucket))
  802. for _, key := range tunnelStats {
  803. err := bucket.Delete(key)
  804. if err != nil {
  805. return err
  806. }
  807. }
  808. return nil
  809. })
  810. if err != nil {
  811. return ContextError(err)
  812. }
  813. return nil
  814. }
  815. // resetAllTunnelStatsToUnreported sets all tunnel
  816. // stats records to StateUnreported. This reset is called
  817. // when the datastore is initialized at start up, as we do
  818. // not know if tunnel records in StateReporting were reported
  819. // or not.
  820. func resetAllTunnelStatsToUnreported() error {
  821. checkInitDataStore()
  822. err := singleton.db.Update(func(tx *bolt.Tx) error {
  823. bucket := tx.Bucket([]byte(tunnelStatsBucket))
  824. resetKeys := make([][]byte, 0)
  825. cursor := bucket.Cursor()
  826. for key, _ := cursor.First(); key != nil; key, _ = cursor.Next() {
  827. resetKeys = append(resetKeys, key)
  828. }
  829. // TODO: data mutation is done outside cursor. Is this
  830. // strictly necessary in this case?
  831. // https://godoc.org/github.com/boltdb/bolt#Cursor
  832. for _, key := range resetKeys {
  833. err := bucket.Put(key, tunnelStatsStateUnreported)
  834. if err != nil {
  835. return err
  836. }
  837. }
  838. return nil
  839. })
  840. if err != nil {
  841. return ContextError(err)
  842. }
  843. return nil
  844. }