dataStore.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 keyValue
  81. (key text not null primary key,
  82. value text not null);
  83. `
  84. _, err = db.Exec(initialization)
  85. if err != nil {
  86. err = fmt.Errorf("initDataStore failed to initialize: %s", err)
  87. return
  88. }
  89. singleton.db = db
  90. })
  91. return err
  92. }
  93. func checkInitDataStore() {
  94. if singleton.db == nil {
  95. panic("checkInitDataStore: datastore not initialized")
  96. }
  97. }
  98. func canRetry(err error) bool {
  99. sqlError, ok := err.(sqlite3.Error)
  100. return ok && (sqlError.Code == sqlite3.ErrBusy ||
  101. sqlError.Code == sqlite3.ErrLocked ||
  102. sqlError.ExtendedCode == sqlite3.ErrLockedSharedCache ||
  103. sqlError.ExtendedCode == sqlite3.ErrBusySnapshot)
  104. }
  105. // transactionWithRetry will retry a write transaction if sqlite3
  106. // reports a table is locked by another writer.
  107. func transactionWithRetry(updater func(*sql.Tx) error) error {
  108. checkInitDataStore()
  109. for i := 0; i < 10; i++ {
  110. if i > 0 {
  111. // Delay on retry
  112. time.Sleep(100)
  113. }
  114. transaction, err := singleton.db.Begin()
  115. if err != nil {
  116. return ContextError(err)
  117. }
  118. err = updater(transaction)
  119. if err != nil {
  120. transaction.Rollback()
  121. if canRetry(err) {
  122. continue
  123. }
  124. return ContextError(err)
  125. }
  126. err = transaction.Commit()
  127. if err != nil {
  128. transaction.Rollback()
  129. if canRetry(err) {
  130. continue
  131. }
  132. return ContextError(err)
  133. }
  134. return nil
  135. }
  136. return ContextError(errors.New("retries exhausted"))
  137. }
  138. // serverEntryExists returns true if a serverEntry with the
  139. // given ipAddress id already exists.
  140. func serverEntryExists(transaction *sql.Tx, ipAddress string) (bool, error) {
  141. query := "select count(*) from serverEntry where id = ?;"
  142. var count int
  143. err := singleton.db.QueryRow(query, ipAddress).Scan(&count)
  144. if err != nil {
  145. return false, ContextError(err)
  146. }
  147. return count > 0, nil
  148. }
  149. // StoreServerEntry adds the server entry to the data store.
  150. // A newly stored (or re-stored) server entry is assigned the next-to-top
  151. // rank for iteration order (the previous top ranked entry is promoted). The
  152. // purpose of inserting at next-to-top is to keep the last selected server
  153. // as the top ranked server. Note, server candidates are iterated in decending
  154. // rank order, so the largest rank is top rank.
  155. // When replaceIfExists is true, an existing server entry record is
  156. // overwritten; otherwise, the existing record is unchanged.
  157. // If the server entry data is malformed, an alert notice is issued and
  158. // the entry is skipped; no error is returned.
  159. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  160. // Server entries should already be validated before this point,
  161. // so instead of skipping we fail with an error.
  162. err := ValidateServerEntry(serverEntry)
  163. if err != nil {
  164. return ContextError(errors.New("invalid server entry"))
  165. }
  166. return transactionWithRetry(func(transaction *sql.Tx) error {
  167. serverEntryExists, err := serverEntryExists(transaction, serverEntry.IpAddress)
  168. if err != nil {
  169. return ContextError(err)
  170. }
  171. if serverEntryExists && !replaceIfExists {
  172. NoticeInfo("ignored update for server %s", serverEntry.IpAddress)
  173. return nil
  174. }
  175. _, err = transaction.Exec(`
  176. update serverEntry set rank = rank + 1
  177. where id = (select id from serverEntry order by rank desc limit 1);
  178. `)
  179. if err != nil {
  180. // Note: ContextError() would break canRetry()
  181. return err
  182. }
  183. data, err := json.Marshal(serverEntry)
  184. if err != nil {
  185. return ContextError(err)
  186. }
  187. _, err = transaction.Exec(`
  188. insert or replace into serverEntry (id, rank, region, data)
  189. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  190. `, serverEntry.IpAddress, serverEntry.Region, data)
  191. if err != nil {
  192. return err
  193. }
  194. _, err = transaction.Exec(`
  195. delete from serverEntryProtocol where serverEntryId = ?;
  196. `, serverEntry.IpAddress)
  197. if err != nil {
  198. return err
  199. }
  200. for _, protocol := range SupportedTunnelProtocols {
  201. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  202. // and the additonal OSSH service is assumed to be available internally.
  203. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  204. if Contains(serverEntry.Capabilities, requiredCapability) {
  205. _, err = transaction.Exec(`
  206. insert into serverEntryProtocol (serverEntryId, protocol)
  207. values (?, ?);
  208. `, serverEntry.IpAddress, protocol)
  209. if err != nil {
  210. return err
  211. }
  212. }
  213. }
  214. // TODO: post notice after commit
  215. if !serverEntryExists {
  216. NoticeInfo("updated server %s", serverEntry.IpAddress)
  217. }
  218. return nil
  219. })
  220. }
  221. // StoreServerEntries shuffles and stores a list of server entries.
  222. // Shuffling is performed on imported server entrues as part of client-side
  223. // load balancing.
  224. // There is an independent transaction for each entry insert/update.
  225. func StoreServerEntries(serverEntries []*ServerEntry, replaceIfExists bool) error {
  226. for index := len(serverEntries) - 1; index > 0; index-- {
  227. swapIndex := rand.Intn(index + 1)
  228. serverEntries[index], serverEntries[swapIndex] = serverEntries[swapIndex], serverEntries[index]
  229. }
  230. for _, serverEntry := range serverEntries {
  231. err := StoreServerEntry(serverEntry, replaceIfExists)
  232. if err != nil {
  233. return ContextError(err)
  234. }
  235. }
  236. return nil
  237. }
  238. // PromoteServerEntry assigns the top rank (one more than current
  239. // max rank) to the specified server entry. Server candidates are
  240. // iterated in decending rank order, so this server entry will be
  241. // the first candidate in a subsequent tunnel establishment.
  242. func PromoteServerEntry(ipAddress string) error {
  243. return transactionWithRetry(func(transaction *sql.Tx) error {
  244. _, err := transaction.Exec(`
  245. update serverEntry
  246. set rank = (select MAX(rank)+1 from serverEntry)
  247. where id = ?;
  248. `, ipAddress)
  249. if err != nil {
  250. // Note: ContextError() would break canRetry()
  251. return err
  252. }
  253. return nil
  254. })
  255. }
  256. // ServerEntryIterator is used to iterate over
  257. // stored server entries in rank order.
  258. type ServerEntryIterator struct {
  259. region string
  260. protocol string
  261. shuffleHeadLength int
  262. transaction *sql.Tx
  263. cursor *sql.Rows
  264. isTargetServerEntryIterator bool
  265. hasNextTargetServerEntry bool
  266. targetServerEntry *ServerEntry
  267. }
  268. // NewServerEntryIterator creates a new NewServerEntryIterator
  269. func NewServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  270. // When configured, this target server entry is the only candidate
  271. if config.TargetServerEntry != "" {
  272. return newTargetServerEntryIterator(config)
  273. }
  274. checkInitDataStore()
  275. iterator = &ServerEntryIterator{
  276. region: config.EgressRegion,
  277. protocol: config.TunnelProtocol,
  278. shuffleHeadLength: config.TunnelPoolSize,
  279. isTargetServerEntryIterator: false,
  280. }
  281. err = iterator.Reset()
  282. if err != nil {
  283. return nil, err
  284. }
  285. return iterator, nil
  286. }
  287. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  288. func newTargetServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  289. serverEntry, err := DecodeServerEntry(config.TargetServerEntry)
  290. if err != nil {
  291. return nil, err
  292. }
  293. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  294. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  295. }
  296. if config.TunnelProtocol != "" {
  297. // Note: same capability/protocol mapping as in StoreServerEntry
  298. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  299. if !Contains(serverEntry.Capabilities, requiredCapability) {
  300. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  301. }
  302. }
  303. iterator = &ServerEntryIterator{
  304. isTargetServerEntryIterator: true,
  305. hasNextTargetServerEntry: true,
  306. targetServerEntry: serverEntry,
  307. }
  308. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  309. return iterator, nil
  310. }
  311. // Reset a NewServerEntryIterator to the start of its cycle. The next
  312. // call to Next will return the first server entry.
  313. func (iterator *ServerEntryIterator) Reset() error {
  314. iterator.Close()
  315. if iterator.isTargetServerEntryIterator {
  316. iterator.hasNextTargetServerEntry = true
  317. return nil
  318. }
  319. count := CountServerEntries(iterator.region, iterator.protocol)
  320. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  321. transaction, err := singleton.db.Begin()
  322. if err != nil {
  323. return ContextError(err)
  324. }
  325. var cursor *sql.Rows
  326. // This query implements the Psiphon server candidate selection
  327. // algorithm: the first TunnelPoolSize server candidates are in rank
  328. // (priority) order, to favor previously successful servers; then the
  329. // remaining long tail is shuffled to raise up less recent candidates.
  330. whereClause, whereParams := makeServerEntryWhereClause(
  331. iterator.region, iterator.protocol, nil)
  332. headLength := iterator.shuffleHeadLength
  333. queryFormat := `
  334. select data from serverEntry %s
  335. order by case
  336. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  337. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  338. end desc;`
  339. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  340. params := make([]interface{}, 0)
  341. params = append(params, whereParams...)
  342. params = append(params, whereParams...)
  343. params = append(params, headLength)
  344. params = append(params, whereParams...)
  345. params = append(params, headLength)
  346. cursor, err = transaction.Query(query, params...)
  347. if err != nil {
  348. transaction.Rollback()
  349. return ContextError(err)
  350. }
  351. iterator.transaction = transaction
  352. iterator.cursor = cursor
  353. return nil
  354. }
  355. // Close cleans up resources associated with a ServerEntryIterator.
  356. func (iterator *ServerEntryIterator) Close() {
  357. if iterator.cursor != nil {
  358. iterator.cursor.Close()
  359. }
  360. iterator.cursor = nil
  361. if iterator.transaction != nil {
  362. iterator.transaction.Rollback()
  363. }
  364. iterator.transaction = nil
  365. }
  366. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  367. // Returns nil with no error when there is no next item.
  368. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  369. defer func() {
  370. if err != nil {
  371. iterator.Close()
  372. }
  373. }()
  374. if iterator.isTargetServerEntryIterator {
  375. if iterator.hasNextTargetServerEntry {
  376. iterator.hasNextTargetServerEntry = false
  377. return iterator.targetServerEntry, nil
  378. }
  379. return nil, nil
  380. }
  381. if !iterator.cursor.Next() {
  382. err = iterator.cursor.Err()
  383. if err != nil {
  384. return nil, ContextError(err)
  385. }
  386. // There is no next item
  387. return nil, nil
  388. }
  389. var data []byte
  390. err = iterator.cursor.Scan(&data)
  391. if err != nil {
  392. return nil, ContextError(err)
  393. }
  394. serverEntry = new(ServerEntry)
  395. err = json.Unmarshal(data, serverEntry)
  396. if err != nil {
  397. return nil, ContextError(err)
  398. }
  399. return serverEntry, nil
  400. }
  401. func makeServerEntryWhereClause(
  402. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  403. whereClause = ""
  404. whereParams = make([]interface{}, 0)
  405. if region != "" {
  406. whereClause += " where region = ?"
  407. whereParams = append(whereParams, region)
  408. }
  409. if protocol != "" {
  410. if len(whereClause) > 0 {
  411. whereClause += " and"
  412. } else {
  413. whereClause += " where"
  414. }
  415. whereClause +=
  416. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  417. whereParams = append(whereParams, protocol)
  418. }
  419. if len(excludeIds) > 0 {
  420. if len(whereClause) > 0 {
  421. whereClause += " and"
  422. } else {
  423. whereClause += " where"
  424. }
  425. whereClause += " id in ("
  426. for index, id := range excludeIds {
  427. if index > 0 {
  428. whereClause += ", "
  429. }
  430. whereClause += "?"
  431. whereParams = append(whereParams, id)
  432. }
  433. whereClause += ")"
  434. }
  435. return whereClause, whereParams
  436. }
  437. // CountServerEntries returns a count of stored servers for the
  438. // specified region and protocol.
  439. func CountServerEntries(region, protocol string) int {
  440. checkInitDataStore()
  441. var count int
  442. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  443. query := "select count(*) from serverEntry" + whereClause
  444. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  445. if err != nil {
  446. NoticeAlert("CountServerEntries failed: %s", err)
  447. return 0
  448. }
  449. if region == "" {
  450. region = "(any)"
  451. }
  452. if protocol == "" {
  453. protocol = "(any)"
  454. }
  455. NoticeInfo("servers for region %s and protocol %s: %d",
  456. region, protocol, count)
  457. return count
  458. }
  459. // GetServerEntryIpAddresses returns an array containing
  460. // all stored server IP addresses.
  461. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  462. checkInitDataStore()
  463. ipAddresses = make([]string, 0)
  464. rows, err := singleton.db.Query("select id from serverEntry;")
  465. if err != nil {
  466. return nil, ContextError(err)
  467. }
  468. defer rows.Close()
  469. for rows.Next() {
  470. var ipAddress string
  471. err = rows.Scan(&ipAddress)
  472. if err != nil {
  473. return nil, ContextError(err)
  474. }
  475. ipAddresses = append(ipAddresses, ipAddress)
  476. }
  477. if err = rows.Err(); err != nil {
  478. return nil, ContextError(err)
  479. }
  480. return ipAddresses, nil
  481. }
  482. // SetKeyValue stores a key/value pair.
  483. func SetKeyValue(key, value string) error {
  484. return transactionWithRetry(func(transaction *sql.Tx) error {
  485. _, err := transaction.Exec(`
  486. insert or replace into keyValue (key, value)
  487. values (?, ?);
  488. `, key, value)
  489. if err != nil {
  490. // Note: ContextError() would break canRetry()
  491. return err
  492. }
  493. return nil
  494. })
  495. }
  496. // GetKeyValue retrieves the value for a given key. If not found,
  497. // it returns an empty string value.
  498. func GetKeyValue(key string) (value string, err error) {
  499. checkInitDataStore()
  500. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  501. err = rows.Scan(&value)
  502. if err == sql.ErrNoRows {
  503. return "", nil
  504. }
  505. if err != nil {
  506. return "", ContextError(err)
  507. }
  508. return value, nil
  509. }