dataStore.go 34 KB

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