dataStore.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. "database/sql"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "math/rand"
  26. "path/filepath"
  27. "strings"
  28. "sync"
  29. "time"
  30. sqlite3 "github.com/Psiphon-Inc/go-sqlite3"
  31. )
  32. type dataStore struct {
  33. init sync.Once
  34. db *sql.DB
  35. }
  36. var singleton dataStore
  37. // InitDataStore initializes the singleton instance of dataStore. This
  38. // function uses a sync.Once and is safe for use by concurrent goroutines.
  39. // The underlying sql.DB connection pool is also safe.
  40. //
  41. // Note: the sync.Once was more useful when initDataStore was private and
  42. // called on-demand by the public functions below. Now we require an explicit
  43. // InitDataStore() call with the filename passed in. The on-demand calls
  44. // have been replaced by checkInitDataStore() to assert that Init was called.
  45. func InitDataStore(config *Config) (err error) {
  46. singleton.init.Do(func() {
  47. filename := filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)
  48. var db *sql.DB
  49. db, err = sql.Open(
  50. "sqlite3",
  51. fmt.Sprintf("file:%s?cache=private&mode=rwc", filename))
  52. if err != nil {
  53. // Note: intending to set the err return value for InitDataStore
  54. err = fmt.Errorf("initDataStore failed to open database: %s", err)
  55. return
  56. }
  57. initialization := "pragma journal_mode=WAL;\n"
  58. if config.DataStoreTempDirectory != "" {
  59. // On some platforms (e.g., Android), the standard temporary directories expected
  60. // by sqlite (see unixGetTempname in aggregate sqlite3.c) may not be present.
  61. // In that case, sqlite tries to use the current working directory; but this may
  62. // be "/" (again, on Android) which is not writable.
  63. // Instead of setting the process current working directory from this library,
  64. // use the deprecated temp_store_directory pragma to force use of a specified
  65. // temporary directory: https://www.sqlite.org/pragma.html#pragma_temp_store_directory.
  66. // TODO: is there another way to restrict writing of temporary files? E.g. temp_store=3?
  67. initialization += fmt.Sprintf(
  68. "pragma temp_store_directory=\"%s\";\n", config.DataStoreDirectory)
  69. }
  70. initialization += `
  71. create table if not exists serverEntry
  72. (id text not null primary key,
  73. rank integer not null unique,
  74. region text not null,
  75. data blob not null);
  76. create table if not exists serverEntryProtocol
  77. (serverEntryId text not null,
  78. protocol text not null,
  79. primary key (serverEntryId, protocol));
  80. create table if not exists splitTunnelRoutes
  81. (region text not null primary key,
  82. etag text not null,
  83. data blob not null);
  84. create table if not exists keyValue
  85. (key text not null primary key,
  86. value text not null);
  87. `
  88. _, err = db.Exec(initialization)
  89. if err != nil {
  90. err = fmt.Errorf("initDataStore failed to initialize: %s", err)
  91. return
  92. }
  93. singleton.db = db
  94. })
  95. return err
  96. }
  97. func checkInitDataStore() {
  98. if singleton.db == nil {
  99. panic("checkInitDataStore: datastore not initialized")
  100. }
  101. }
  102. func canRetry(err error) bool {
  103. sqlError, ok := err.(sqlite3.Error)
  104. return ok && (sqlError.Code == sqlite3.ErrBusy ||
  105. sqlError.Code == sqlite3.ErrLocked ||
  106. sqlError.ExtendedCode == sqlite3.ErrLockedSharedCache ||
  107. sqlError.ExtendedCode == sqlite3.ErrBusySnapshot)
  108. }
  109. // transactionWithRetry will retry a write transaction if sqlite3
  110. // reports a table is locked by another writer.
  111. func transactionWithRetry(updater func(*sql.Tx) error) error {
  112. checkInitDataStore()
  113. for i := 0; i < 10; i++ {
  114. if i > 0 {
  115. // Delay on retry
  116. time.Sleep(100)
  117. }
  118. transaction, err := singleton.db.Begin()
  119. if err != nil {
  120. return ContextError(err)
  121. }
  122. err = updater(transaction)
  123. if err != nil {
  124. transaction.Rollback()
  125. if canRetry(err) {
  126. continue
  127. }
  128. return ContextError(err)
  129. }
  130. err = transaction.Commit()
  131. if err != nil {
  132. transaction.Rollback()
  133. if canRetry(err) {
  134. continue
  135. }
  136. return ContextError(err)
  137. }
  138. return nil
  139. }
  140. return ContextError(errors.New("retries exhausted"))
  141. }
  142. // serverEntryExists returns true if a serverEntry with the
  143. // given ipAddress id already exists.
  144. func serverEntryExists(transaction *sql.Tx, ipAddress string) (bool, error) {
  145. query := "select count(*) from serverEntry where id = ?;"
  146. var count int
  147. err := singleton.db.QueryRow(query, ipAddress).Scan(&count)
  148. if err != nil {
  149. return false, ContextError(err)
  150. }
  151. return count > 0, nil
  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. Note, server candidates are iterated in decending
  158. // rank order, so the largest rank is top rank.
  159. // When replaceIfExists is true, an existing server entry record is
  160. // overwritten; otherwise, the existing record is unchanged.
  161. // If the server entry data is malformed, an alert notice is issued and
  162. // the entry is skipped; no error is returned.
  163. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  164. // Server entries should already be validated before this point,
  165. // so instead of skipping we fail with an error.
  166. err := ValidateServerEntry(serverEntry)
  167. if err != nil {
  168. return ContextError(errors.New("invalid server entry"))
  169. }
  170. return transactionWithRetry(func(transaction *sql.Tx) error {
  171. serverEntryExists, err := serverEntryExists(transaction, serverEntry.IpAddress)
  172. if err != nil {
  173. return ContextError(err)
  174. }
  175. if serverEntryExists && !replaceIfExists {
  176. // Disabling this notice, for now, as it generates too much noise
  177. // in diagnostics with clients that always submit embedded servers
  178. // to the core on each run.
  179. // NoticeInfo("ignored update for server %s", serverEntry.IpAddress)
  180. return nil
  181. }
  182. _, err = transaction.Exec(`
  183. update serverEntry set rank = rank + 1
  184. where id = (select id from serverEntry order by rank desc limit 1);
  185. `)
  186. if err != nil {
  187. // Note: ContextError() would break canRetry()
  188. return err
  189. }
  190. data, err := json.Marshal(serverEntry)
  191. if err != nil {
  192. return ContextError(err)
  193. }
  194. _, err = transaction.Exec(`
  195. insert or replace into serverEntry (id, rank, region, data)
  196. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  197. `, serverEntry.IpAddress, serverEntry.Region, data)
  198. if err != nil {
  199. return err
  200. }
  201. _, err = transaction.Exec(`
  202. delete from serverEntryProtocol where serverEntryId = ?;
  203. `, serverEntry.IpAddress)
  204. if err != nil {
  205. return err
  206. }
  207. for _, protocol := range SupportedTunnelProtocols {
  208. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  209. // and the additonal OSSH service is assumed to be available internally.
  210. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  211. if Contains(serverEntry.Capabilities, requiredCapability) {
  212. _, err = transaction.Exec(`
  213. insert into serverEntryProtocol (serverEntryId, protocol)
  214. values (?, ?);
  215. `, serverEntry.IpAddress, protocol)
  216. if err != nil {
  217. return err
  218. }
  219. }
  220. }
  221. // TODO: post notice after commit
  222. if !serverEntryExists {
  223. NoticeInfo("updated server %s", serverEntry.IpAddress)
  224. }
  225. return nil
  226. })
  227. }
  228. // StoreServerEntries shuffles and stores a list of server entries.
  229. // Shuffling is performed on imported server entrues as part of client-side
  230. // load balancing.
  231. // There is an independent transaction for each entry insert/update.
  232. func StoreServerEntries(serverEntries []*ServerEntry, replaceIfExists bool) error {
  233. for index := len(serverEntries) - 1; index > 0; index-- {
  234. swapIndex := rand.Intn(index + 1)
  235. serverEntries[index], serverEntries[swapIndex] = serverEntries[swapIndex], serverEntries[index]
  236. }
  237. for _, serverEntry := range serverEntries {
  238. err := StoreServerEntry(serverEntry, replaceIfExists)
  239. if err != nil {
  240. return ContextError(err)
  241. }
  242. }
  243. return nil
  244. }
  245. // PromoteServerEntry assigns the top rank (one more than current
  246. // max rank) to the specified server entry. Server candidates are
  247. // iterated in decending rank order, so this server entry will be
  248. // the first candidate in a subsequent tunnel establishment.
  249. func PromoteServerEntry(ipAddress string) error {
  250. return transactionWithRetry(func(transaction *sql.Tx) error {
  251. _, err := transaction.Exec(`
  252. update serverEntry
  253. set rank = (select MAX(rank)+1 from serverEntry)
  254. where id = ?;
  255. `, ipAddress)
  256. if err != nil {
  257. // Note: ContextError() would break canRetry()
  258. return err
  259. }
  260. return nil
  261. })
  262. }
  263. // ServerEntryIterator is used to iterate over
  264. // stored server entries in rank order.
  265. type ServerEntryIterator struct {
  266. region string
  267. protocol string
  268. shuffleHeadLength int
  269. transaction *sql.Tx
  270. cursor *sql.Rows
  271. isTargetServerEntryIterator bool
  272. hasNextTargetServerEntry bool
  273. targetServerEntry *ServerEntry
  274. }
  275. // NewServerEntryIterator creates a new NewServerEntryIterator
  276. func NewServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  277. // When configured, this target server entry is the only candidate
  278. if config.TargetServerEntry != "" {
  279. return newTargetServerEntryIterator(config)
  280. }
  281. checkInitDataStore()
  282. iterator = &ServerEntryIterator{
  283. region: config.EgressRegion,
  284. protocol: config.TunnelProtocol,
  285. shuffleHeadLength: config.TunnelPoolSize,
  286. isTargetServerEntryIterator: false,
  287. }
  288. err = iterator.Reset()
  289. if err != nil {
  290. return nil, err
  291. }
  292. return iterator, nil
  293. }
  294. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  295. func newTargetServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  296. serverEntry, err := DecodeServerEntry(config.TargetServerEntry)
  297. if err != nil {
  298. return nil, err
  299. }
  300. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  301. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  302. }
  303. if config.TunnelProtocol != "" {
  304. // Note: same capability/protocol mapping as in StoreServerEntry
  305. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  306. if !Contains(serverEntry.Capabilities, requiredCapability) {
  307. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  308. }
  309. }
  310. iterator = &ServerEntryIterator{
  311. isTargetServerEntryIterator: true,
  312. hasNextTargetServerEntry: true,
  313. targetServerEntry: serverEntry,
  314. }
  315. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  316. return iterator, nil
  317. }
  318. // Reset a NewServerEntryIterator to the start of its cycle. The next
  319. // call to Next will return the first server entry.
  320. func (iterator *ServerEntryIterator) Reset() error {
  321. iterator.Close()
  322. if iterator.isTargetServerEntryIterator {
  323. iterator.hasNextTargetServerEntry = true
  324. return nil
  325. }
  326. count := CountServerEntries(iterator.region, iterator.protocol)
  327. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  328. transaction, err := singleton.db.Begin()
  329. if err != nil {
  330. return ContextError(err)
  331. }
  332. var cursor *sql.Rows
  333. // This query implements the Psiphon server candidate selection
  334. // algorithm: the first TunnelPoolSize server candidates are in rank
  335. // (priority) order, to favor previously successful servers; then the
  336. // remaining long tail is shuffled to raise up less recent candidates.
  337. whereClause, whereParams := makeServerEntryWhereClause(
  338. iterator.region, iterator.protocol, nil)
  339. headLength := iterator.shuffleHeadLength
  340. queryFormat := `
  341. select data from serverEntry %s
  342. order by case
  343. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  344. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  345. end desc;`
  346. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  347. params := make([]interface{}, 0)
  348. params = append(params, whereParams...)
  349. params = append(params, whereParams...)
  350. params = append(params, headLength)
  351. params = append(params, whereParams...)
  352. params = append(params, headLength)
  353. cursor, err = transaction.Query(query, params...)
  354. if err != nil {
  355. transaction.Rollback()
  356. return ContextError(err)
  357. }
  358. iterator.transaction = transaction
  359. iterator.cursor = cursor
  360. return nil
  361. }
  362. // Close cleans up resources associated with a ServerEntryIterator.
  363. func (iterator *ServerEntryIterator) Close() {
  364. if iterator.cursor != nil {
  365. iterator.cursor.Close()
  366. }
  367. iterator.cursor = nil
  368. if iterator.transaction != nil {
  369. iterator.transaction.Rollback()
  370. }
  371. iterator.transaction = nil
  372. }
  373. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  374. // Returns nil with no error when there is no next item.
  375. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  376. defer func() {
  377. if err != nil {
  378. iterator.Close()
  379. }
  380. }()
  381. if iterator.isTargetServerEntryIterator {
  382. if iterator.hasNextTargetServerEntry {
  383. iterator.hasNextTargetServerEntry = false
  384. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  385. }
  386. return nil, nil
  387. }
  388. if !iterator.cursor.Next() {
  389. err = iterator.cursor.Err()
  390. if err != nil {
  391. return nil, ContextError(err)
  392. }
  393. // There is no next item
  394. return nil, nil
  395. }
  396. var data []byte
  397. err = iterator.cursor.Scan(&data)
  398. if err != nil {
  399. return nil, ContextError(err)
  400. }
  401. serverEntry = new(ServerEntry)
  402. err = json.Unmarshal(data, serverEntry)
  403. if err != nil {
  404. return nil, ContextError(err)
  405. }
  406. return MakeCompatibleServerEntry(serverEntry), nil
  407. }
  408. // MakeCompatibleServerEntry provides backwards compatibility with old server entries
  409. // which have a single meekFrontingDomain and not a meekFrontingAddresses array.
  410. // By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
  411. // uses that single value as legacy clients do.
  412. func MakeCompatibleServerEntry(serverEntry *ServerEntry) *ServerEntry {
  413. if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
  414. serverEntry.MeekFrontingAddresses =
  415. append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
  416. }
  417. return serverEntry
  418. }
  419. func makeServerEntryWhereClause(
  420. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  421. whereClause = ""
  422. whereParams = make([]interface{}, 0)
  423. if region != "" {
  424. whereClause += " where region = ?"
  425. whereParams = append(whereParams, region)
  426. }
  427. if protocol != "" {
  428. if len(whereClause) > 0 {
  429. whereClause += " and"
  430. } else {
  431. whereClause += " where"
  432. }
  433. whereClause +=
  434. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  435. whereParams = append(whereParams, protocol)
  436. }
  437. if len(excludeIds) > 0 {
  438. if len(whereClause) > 0 {
  439. whereClause += " and"
  440. } else {
  441. whereClause += " where"
  442. }
  443. whereClause += " id in ("
  444. for index, id := range excludeIds {
  445. if index > 0 {
  446. whereClause += ", "
  447. }
  448. whereClause += "?"
  449. whereParams = append(whereParams, id)
  450. }
  451. whereClause += ")"
  452. }
  453. return whereClause, whereParams
  454. }
  455. // CountServerEntries returns a count of stored servers for the
  456. // specified region and protocol.
  457. func CountServerEntries(region, protocol string) int {
  458. checkInitDataStore()
  459. var count int
  460. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  461. query := "select count(*) from serverEntry" + whereClause
  462. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  463. if err != nil {
  464. NoticeAlert("CountServerEntries failed: %s", err)
  465. return 0
  466. }
  467. if region == "" {
  468. region = "(any)"
  469. }
  470. if protocol == "" {
  471. protocol = "(any)"
  472. }
  473. NoticeInfo("servers for region %s and protocol %s: %d",
  474. region, protocol, count)
  475. return count
  476. }
  477. // GetServerEntryIpAddresses returns an array containing
  478. // all stored server IP addresses.
  479. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  480. checkInitDataStore()
  481. ipAddresses = make([]string, 0)
  482. rows, err := singleton.db.Query("select id from serverEntry;")
  483. if err != nil {
  484. return nil, ContextError(err)
  485. }
  486. defer rows.Close()
  487. for rows.Next() {
  488. var ipAddress string
  489. err = rows.Scan(&ipAddress)
  490. if err != nil {
  491. return nil, ContextError(err)
  492. }
  493. ipAddresses = append(ipAddresses, ipAddress)
  494. }
  495. if err = rows.Err(); err != nil {
  496. return nil, ContextError(err)
  497. }
  498. return ipAddresses, nil
  499. }
  500. // SetSplitTunnelRoutes updates the cached routes data for
  501. // the given region. The associated etag is also stored and
  502. // used to make efficient web requests for updates to the data.
  503. func SetSplitTunnelRoutes(region, etag string, data []byte) error {
  504. return transactionWithRetry(func(transaction *sql.Tx) error {
  505. _, err := transaction.Exec(`
  506. insert or replace into splitTunnelRoutes (region, etag, data)
  507. values (?, ?, ?);
  508. `, region, etag, data)
  509. if err != nil {
  510. // Note: ContextError() would break canRetry()
  511. return err
  512. }
  513. return nil
  514. })
  515. }
  516. // GetSplitTunnelRoutesETag retrieves the etag for cached routes
  517. // data for the specified region. If not found, it returns an empty string value.
  518. func GetSplitTunnelRoutesETag(region string) (etag string, err error) {
  519. checkInitDataStore()
  520. rows := singleton.db.QueryRow("select etag from splitTunnelRoutes where region = ?;", region)
  521. err = rows.Scan(&etag)
  522. if err == sql.ErrNoRows {
  523. return "", nil
  524. }
  525. if err != nil {
  526. return "", ContextError(err)
  527. }
  528. return etag, nil
  529. }
  530. // GetSplitTunnelRoutesData retrieves the cached routes data
  531. // for the specified region. If not found, it returns a nil value.
  532. func GetSplitTunnelRoutesData(region string) (data []byte, err error) {
  533. checkInitDataStore()
  534. rows := singleton.db.QueryRow("select data from splitTunnelRoutes where region = ?;", region)
  535. err = rows.Scan(&data)
  536. if err == sql.ErrNoRows {
  537. return nil, nil
  538. }
  539. if err != nil {
  540. return nil, ContextError(err)
  541. }
  542. return data, nil
  543. }
  544. // SetKeyValue stores a key/value pair.
  545. func SetKeyValue(key, value string) error {
  546. return transactionWithRetry(func(transaction *sql.Tx) error {
  547. _, err := transaction.Exec(`
  548. insert or replace into keyValue (key, value)
  549. values (?, ?);
  550. `, key, value)
  551. if err != nil {
  552. // Note: ContextError() would break canRetry()
  553. return err
  554. }
  555. return nil
  556. })
  557. }
  558. // GetKeyValue retrieves the value for a given key. If not found,
  559. // it returns an empty string value.
  560. func GetKeyValue(key string) (value string, err error) {
  561. checkInitDataStore()
  562. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  563. err = rows.Scan(&value)
  564. if err == sql.ErrNoRows {
  565. return "", nil
  566. }
  567. if err != nil {
  568. return "", ContextError(err)
  569. }
  570. return value, nil
  571. }