dataStore.go 35 KB

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