dataStore.go 33 KB

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