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