dataStore.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. NoticeInfo("ignored update for server %s", serverEntry.IpAddress)
  177. return nil
  178. }
  179. _, err = transaction.Exec(`
  180. update serverEntry set rank = rank + 1
  181. where id = (select id from serverEntry order by rank desc limit 1);
  182. `)
  183. if err != nil {
  184. // Note: ContextError() would break canRetry()
  185. return err
  186. }
  187. data, err := json.Marshal(serverEntry)
  188. if err != nil {
  189. return ContextError(err)
  190. }
  191. _, err = transaction.Exec(`
  192. insert or replace into serverEntry (id, rank, region, data)
  193. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  194. `, serverEntry.IpAddress, serverEntry.Region, data)
  195. if err != nil {
  196. return err
  197. }
  198. _, err = transaction.Exec(`
  199. delete from serverEntryProtocol where serverEntryId = ?;
  200. `, serverEntry.IpAddress)
  201. if err != nil {
  202. return err
  203. }
  204. for _, protocol := range SupportedTunnelProtocols {
  205. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  206. // and the additonal OSSH service is assumed to be available internally.
  207. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  208. if Contains(serverEntry.Capabilities, requiredCapability) {
  209. _, err = transaction.Exec(`
  210. insert into serverEntryProtocol (serverEntryId, protocol)
  211. values (?, ?);
  212. `, serverEntry.IpAddress, protocol)
  213. if err != nil {
  214. return err
  215. }
  216. }
  217. }
  218. // TODO: post notice after commit
  219. if !serverEntryExists {
  220. NoticeInfo("updated server %s", serverEntry.IpAddress)
  221. }
  222. return nil
  223. })
  224. }
  225. // StoreServerEntries shuffles and stores a list of server entries.
  226. // Shuffling is performed on imported server entrues as part of client-side
  227. // load balancing.
  228. // There is an independent transaction for each entry insert/update.
  229. func StoreServerEntries(serverEntries []*ServerEntry, replaceIfExists bool) error {
  230. for index := len(serverEntries) - 1; index > 0; index-- {
  231. swapIndex := rand.Intn(index + 1)
  232. serverEntries[index], serverEntries[swapIndex] = serverEntries[swapIndex], serverEntries[index]
  233. }
  234. for _, serverEntry := range serverEntries {
  235. err := StoreServerEntry(serverEntry, replaceIfExists)
  236. if err != nil {
  237. return ContextError(err)
  238. }
  239. }
  240. return nil
  241. }
  242. // PromoteServerEntry assigns the top rank (one more than current
  243. // max rank) to the specified server entry. Server candidates are
  244. // iterated in decending rank order, so this server entry will be
  245. // the first candidate in a subsequent tunnel establishment.
  246. func PromoteServerEntry(ipAddress string) error {
  247. return transactionWithRetry(func(transaction *sql.Tx) error {
  248. _, err := transaction.Exec(`
  249. update serverEntry
  250. set rank = (select MAX(rank)+1 from serverEntry)
  251. where id = ?;
  252. `, ipAddress)
  253. if err != nil {
  254. // Note: ContextError() would break canRetry()
  255. return err
  256. }
  257. return nil
  258. })
  259. }
  260. // ServerEntryIterator is used to iterate over
  261. // stored server entries in rank order.
  262. type ServerEntryIterator struct {
  263. region string
  264. protocol string
  265. shuffleHeadLength int
  266. transaction *sql.Tx
  267. cursor *sql.Rows
  268. isTargetServerEntryIterator bool
  269. hasNextTargetServerEntry bool
  270. targetServerEntry *ServerEntry
  271. }
  272. // NewServerEntryIterator creates a new NewServerEntryIterator
  273. func NewServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  274. // When configured, this target server entry is the only candidate
  275. if config.TargetServerEntry != "" {
  276. return newTargetServerEntryIterator(config)
  277. }
  278. checkInitDataStore()
  279. iterator = &ServerEntryIterator{
  280. region: config.EgressRegion,
  281. protocol: config.TunnelProtocol,
  282. shuffleHeadLength: config.TunnelPoolSize,
  283. isTargetServerEntryIterator: false,
  284. }
  285. err = iterator.Reset()
  286. if err != nil {
  287. return nil, err
  288. }
  289. return iterator, nil
  290. }
  291. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  292. func newTargetServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  293. serverEntry, err := DecodeServerEntry(config.TargetServerEntry)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  298. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  299. }
  300. if config.TunnelProtocol != "" {
  301. // Note: same capability/protocol mapping as in StoreServerEntry
  302. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  303. if !Contains(serverEntry.Capabilities, requiredCapability) {
  304. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  305. }
  306. }
  307. iterator = &ServerEntryIterator{
  308. isTargetServerEntryIterator: true,
  309. hasNextTargetServerEntry: true,
  310. targetServerEntry: serverEntry,
  311. }
  312. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  313. return iterator, nil
  314. }
  315. // Reset a NewServerEntryIterator to the start of its cycle. The next
  316. // call to Next will return the first server entry.
  317. func (iterator *ServerEntryIterator) Reset() error {
  318. iterator.Close()
  319. if iterator.isTargetServerEntryIterator {
  320. iterator.hasNextTargetServerEntry = true
  321. return nil
  322. }
  323. count := CountServerEntries(iterator.region, iterator.protocol)
  324. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  325. transaction, err := singleton.db.Begin()
  326. if err != nil {
  327. return ContextError(err)
  328. }
  329. var cursor *sql.Rows
  330. // This query implements the Psiphon server candidate selection
  331. // algorithm: the first TunnelPoolSize server candidates are in rank
  332. // (priority) order, to favor previously successful servers; then the
  333. // remaining long tail is shuffled to raise up less recent candidates.
  334. whereClause, whereParams := makeServerEntryWhereClause(
  335. iterator.region, iterator.protocol, nil)
  336. headLength := iterator.shuffleHeadLength
  337. queryFormat := `
  338. select data from serverEntry %s
  339. order by case
  340. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  341. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  342. end desc;`
  343. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  344. params := make([]interface{}, 0)
  345. params = append(params, whereParams...)
  346. params = append(params, whereParams...)
  347. params = append(params, headLength)
  348. params = append(params, whereParams...)
  349. params = append(params, headLength)
  350. cursor, err = transaction.Query(query, params...)
  351. if err != nil {
  352. transaction.Rollback()
  353. return ContextError(err)
  354. }
  355. iterator.transaction = transaction
  356. iterator.cursor = cursor
  357. return nil
  358. }
  359. // Close cleans up resources associated with a ServerEntryIterator.
  360. func (iterator *ServerEntryIterator) Close() {
  361. if iterator.cursor != nil {
  362. iterator.cursor.Close()
  363. }
  364. iterator.cursor = nil
  365. if iterator.transaction != nil {
  366. iterator.transaction.Rollback()
  367. }
  368. iterator.transaction = nil
  369. }
  370. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  371. // Returns nil with no error when there is no next item.
  372. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  373. defer func() {
  374. if err != nil {
  375. iterator.Close()
  376. }
  377. }()
  378. if iterator.isTargetServerEntryIterator {
  379. if iterator.hasNextTargetServerEntry {
  380. iterator.hasNextTargetServerEntry = false
  381. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  382. }
  383. return nil, nil
  384. }
  385. if !iterator.cursor.Next() {
  386. err = iterator.cursor.Err()
  387. if err != nil {
  388. return nil, ContextError(err)
  389. }
  390. // There is no next item
  391. return nil, nil
  392. }
  393. var data []byte
  394. err = iterator.cursor.Scan(&data)
  395. if err != nil {
  396. return nil, ContextError(err)
  397. }
  398. serverEntry = new(ServerEntry)
  399. err = json.Unmarshal(data, serverEntry)
  400. if err != nil {
  401. return nil, ContextError(err)
  402. }
  403. return MakeCompatibleServerEntry(serverEntry), nil
  404. }
  405. // MakeCompatibleServerEntry provides backwards compatibility with old server entries
  406. // which have a single meekFrontingDomain and not a meekFrontingAddresses array.
  407. // By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
  408. // uses that single value as legacy clients do.
  409. func MakeCompatibleServerEntry(serverEntry *ServerEntry) *ServerEntry {
  410. if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
  411. serverEntry.MeekFrontingAddresses =
  412. append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
  413. }
  414. return serverEntry
  415. }
  416. func makeServerEntryWhereClause(
  417. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  418. whereClause = ""
  419. whereParams = make([]interface{}, 0)
  420. if region != "" {
  421. whereClause += " where region = ?"
  422. whereParams = append(whereParams, region)
  423. }
  424. if protocol != "" {
  425. if len(whereClause) > 0 {
  426. whereClause += " and"
  427. } else {
  428. whereClause += " where"
  429. }
  430. whereClause +=
  431. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  432. whereParams = append(whereParams, protocol)
  433. }
  434. if len(excludeIds) > 0 {
  435. if len(whereClause) > 0 {
  436. whereClause += " and"
  437. } else {
  438. whereClause += " where"
  439. }
  440. whereClause += " id in ("
  441. for index, id := range excludeIds {
  442. if index > 0 {
  443. whereClause += ", "
  444. }
  445. whereClause += "?"
  446. whereParams = append(whereParams, id)
  447. }
  448. whereClause += ")"
  449. }
  450. return whereClause, whereParams
  451. }
  452. // CountServerEntries returns a count of stored servers for the
  453. // specified region and protocol.
  454. func CountServerEntries(region, protocol string) int {
  455. checkInitDataStore()
  456. var count int
  457. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  458. query := "select count(*) from serverEntry" + whereClause
  459. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  460. if err != nil {
  461. NoticeAlert("CountServerEntries failed: %s", err)
  462. return 0
  463. }
  464. if region == "" {
  465. region = "(any)"
  466. }
  467. if protocol == "" {
  468. protocol = "(any)"
  469. }
  470. NoticeInfo("servers for region %s and protocol %s: %d",
  471. region, protocol, count)
  472. return count
  473. }
  474. // GetServerEntryIpAddresses returns an array containing
  475. // all stored server IP addresses.
  476. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  477. checkInitDataStore()
  478. ipAddresses = make([]string, 0)
  479. rows, err := singleton.db.Query("select id from serverEntry;")
  480. if err != nil {
  481. return nil, ContextError(err)
  482. }
  483. defer rows.Close()
  484. for rows.Next() {
  485. var ipAddress string
  486. err = rows.Scan(&ipAddress)
  487. if err != nil {
  488. return nil, ContextError(err)
  489. }
  490. ipAddresses = append(ipAddresses, ipAddress)
  491. }
  492. if err = rows.Err(); err != nil {
  493. return nil, ContextError(err)
  494. }
  495. return ipAddresses, nil
  496. }
  497. // SetSplitTunnelRoutes updates the cached routes data for
  498. // the given region. The associated etag is also stored and
  499. // used to make efficient web requests for updates to the data.
  500. func SetSplitTunnelRoutes(region, etag string, data []byte) error {
  501. return transactionWithRetry(func(transaction *sql.Tx) error {
  502. _, err := transaction.Exec(`
  503. insert or replace into splitTunnelRoutes (region, etag, data)
  504. values (?, ?, ?);
  505. `, region, etag, data)
  506. if err != nil {
  507. // Note: ContextError() would break canRetry()
  508. return err
  509. }
  510. return nil
  511. })
  512. }
  513. // GetSplitTunnelRoutesETag retrieves the etag for cached routes
  514. // data for the specified region. If not found, it returns an empty string value.
  515. func GetSplitTunnelRoutesETag(region string) (etag string, err error) {
  516. checkInitDataStore()
  517. rows := singleton.db.QueryRow("select etag from splitTunnelRoutes where region = ?;", region)
  518. err = rows.Scan(&etag)
  519. if err == sql.ErrNoRows {
  520. return "", nil
  521. }
  522. if err != nil {
  523. return "", ContextError(err)
  524. }
  525. return etag, nil
  526. }
  527. // GetSplitTunnelRoutesData retrieves the cached routes data
  528. // for the specified region. If not found, it returns a nil value.
  529. func GetSplitTunnelRoutesData(region string) (data []byte, err error) {
  530. checkInitDataStore()
  531. rows := singleton.db.QueryRow("select data from splitTunnelRoutes where region = ?;", region)
  532. err = rows.Scan(&data)
  533. if err == sql.ErrNoRows {
  534. return nil, nil
  535. }
  536. if err != nil {
  537. return nil, ContextError(err)
  538. }
  539. return data, nil
  540. }
  541. // SetKeyValue stores a key/value pair.
  542. func SetKeyValue(key, value string) error {
  543. return transactionWithRetry(func(transaction *sql.Tx) error {
  544. _, err := transaction.Exec(`
  545. insert or replace into keyValue (key, value)
  546. values (?, ?);
  547. `, key, value)
  548. if err != nil {
  549. // Note: ContextError() would break canRetry()
  550. return err
  551. }
  552. return nil
  553. })
  554. }
  555. // GetKeyValue retrieves the value for a given key. If not found,
  556. // it returns an empty string value.
  557. func GetKeyValue(key string) (value string, err error) {
  558. checkInitDataStore()
  559. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  560. err = rows.Scan(&value)
  561. if err == sql.ErrNoRows {
  562. return "", nil
  563. }
  564. if err != nil {
  565. return "", ContextError(err)
  566. }
  567. return value, nil
  568. }