dataStore.go 36 KB

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