dataStore.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. Notice(NOTICE_INFO, "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. Notice(NOTICE_INFO, "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. transaction *sql.Tx
  262. cursor *sql.Rows
  263. isTargetServerEntryIterator bool
  264. hasNextTargetServerEntry bool
  265. targetServerEntry *ServerEntry
  266. }
  267. // NewServerEntryIterator creates a new NewServerEntryIterator
  268. func NewServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  269. // When configured, this target server entry is the only candidate
  270. if config.TargetServerEntry != "" {
  271. return newTargetServerEntryIterator(config)
  272. }
  273. checkInitDataStore()
  274. iterator = &ServerEntryIterator{
  275. region: config.EgressRegion,
  276. protocol: config.TunnelProtocol,
  277. isTargetServerEntryIterator: false,
  278. }
  279. err = iterator.Reset()
  280. if err != nil {
  281. return nil, err
  282. }
  283. return iterator, nil
  284. }
  285. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  286. func newTargetServerEntryIterator(config *Config) (iterator *ServerEntryIterator, err error) {
  287. serverEntry, err := DecodeServerEntry(config.TargetServerEntry)
  288. if err != nil {
  289. return nil, err
  290. }
  291. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  292. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  293. }
  294. if config.TunnelProtocol != "" {
  295. // Note: same capability/protocol mapping as in StoreServerEntry
  296. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  297. if !Contains(serverEntry.Capabilities, requiredCapability) {
  298. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  299. }
  300. }
  301. iterator = &ServerEntryIterator{
  302. isTargetServerEntryIterator: true,
  303. hasNextTargetServerEntry: true,
  304. targetServerEntry: serverEntry,
  305. }
  306. Notice(NOTICE_INFO, "using TargetServerEntry: %s", serverEntry.IpAddress)
  307. return iterator, nil
  308. }
  309. // Reset a NewServerEntryIterator to the start of its cycle. The next
  310. // call to Next will return the first server entry.
  311. func (iterator *ServerEntryIterator) Reset() error {
  312. iterator.Close()
  313. if iterator.isTargetServerEntryIterator {
  314. iterator.hasNextTargetServerEntry = true
  315. return nil
  316. }
  317. transaction, err := singleton.db.Begin()
  318. if err != nil {
  319. return ContextError(err)
  320. }
  321. var cursor *sql.Rows
  322. // This query implements the Psiphon server candidate selection
  323. // algorithm: the first set of server candidates are in rank (priority)
  324. // order, to favor previously successful servers; then the remaining
  325. // long tail is shuffled to raise up less recent candidates.
  326. whereClause, whereParams := makeServerEntryWhereClause(
  327. iterator.region, iterator.protocol, nil)
  328. headLength := CONNECTION_WORKER_POOL_SIZE
  329. queryFormat := `
  330. select data from serverEntry %s
  331. order by case
  332. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  333. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  334. end desc;`
  335. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  336. params := make([]interface{}, 0)
  337. params = append(params, whereParams...)
  338. params = append(params, whereParams...)
  339. params = append(params, headLength)
  340. params = append(params, whereParams...)
  341. params = append(params, headLength)
  342. cursor, err = transaction.Query(query, params...)
  343. if err != nil {
  344. transaction.Rollback()
  345. return ContextError(err)
  346. }
  347. iterator.transaction = transaction
  348. iterator.cursor = cursor
  349. return nil
  350. }
  351. // Close cleans up resources associated with a ServerEntryIterator.
  352. func (iterator *ServerEntryIterator) Close() {
  353. if iterator.cursor != nil {
  354. iterator.cursor.Close()
  355. }
  356. iterator.cursor = nil
  357. if iterator.transaction != nil {
  358. iterator.transaction.Rollback()
  359. }
  360. iterator.transaction = nil
  361. }
  362. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  363. // Returns nil with no error when there is no next item.
  364. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  365. defer func() {
  366. if err != nil {
  367. iterator.Close()
  368. }
  369. }()
  370. if iterator.isTargetServerEntryIterator {
  371. if iterator.hasNextTargetServerEntry {
  372. iterator.hasNextTargetServerEntry = false
  373. return iterator.targetServerEntry, nil
  374. }
  375. return nil, nil
  376. }
  377. if !iterator.cursor.Next() {
  378. err = iterator.cursor.Err()
  379. if err != nil {
  380. return nil, ContextError(err)
  381. }
  382. // There is no next item
  383. return nil, nil
  384. }
  385. var data []byte
  386. err = iterator.cursor.Scan(&data)
  387. if err != nil {
  388. return nil, ContextError(err)
  389. }
  390. serverEntry = new(ServerEntry)
  391. err = json.Unmarshal(data, serverEntry)
  392. if err != nil {
  393. return nil, ContextError(err)
  394. }
  395. return serverEntry, nil
  396. }
  397. func makeServerEntryWhereClause(
  398. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  399. whereClause = ""
  400. whereParams = make([]interface{}, 0)
  401. if region != "" {
  402. whereClause += " where region = ?"
  403. whereParams = append(whereParams, region)
  404. }
  405. if protocol != "" {
  406. if len(whereClause) > 0 {
  407. whereClause += " and"
  408. } else {
  409. whereClause += " where"
  410. }
  411. whereClause +=
  412. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  413. whereParams = append(whereParams, protocol)
  414. }
  415. if len(excludeIds) > 0 {
  416. if len(whereClause) > 0 {
  417. whereClause += " and"
  418. } else {
  419. whereClause += " where"
  420. }
  421. whereClause += " id in ("
  422. for index, id := range excludeIds {
  423. if index > 0 {
  424. whereClause += ", "
  425. }
  426. whereClause += "?"
  427. whereParams = append(whereParams, id)
  428. }
  429. whereClause += ")"
  430. }
  431. return whereClause, whereParams
  432. }
  433. // CountServerEntries returns a count of stored servers for the
  434. // specified region and protocol.
  435. func CountServerEntries(region, protocol string) int {
  436. checkInitDataStore()
  437. var count int
  438. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  439. query := "select count(*) from serverEntry" + whereClause
  440. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  441. if err != nil {
  442. Notice(NOTICE_ALERT, "CountServerEntries failed: %s", err)
  443. return 0
  444. }
  445. if region == "" {
  446. region = "(any)"
  447. }
  448. if protocol == "" {
  449. protocol = "(any)"
  450. }
  451. Notice(NOTICE_INFO, "servers for region %s and protocol %s: %d",
  452. region, protocol, count)
  453. return count
  454. }
  455. // GetServerEntryIpAddresses returns an array containing
  456. // all stored server IP addresses.
  457. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  458. checkInitDataStore()
  459. ipAddresses = make([]string, 0)
  460. rows, err := singleton.db.Query("select id from serverEntry;")
  461. if err != nil {
  462. return nil, ContextError(err)
  463. }
  464. defer rows.Close()
  465. for rows.Next() {
  466. var ipAddress string
  467. err = rows.Scan(&ipAddress)
  468. if err != nil {
  469. return nil, ContextError(err)
  470. }
  471. ipAddresses = append(ipAddresses, ipAddress)
  472. }
  473. if err = rows.Err(); err != nil {
  474. return nil, ContextError(err)
  475. }
  476. return ipAddresses, nil
  477. }
  478. // SetKeyValue stores a key/value pair.
  479. func SetKeyValue(key, value string) error {
  480. return transactionWithRetry(func(transaction *sql.Tx) error {
  481. _, err := transaction.Exec(`
  482. insert or replace into keyValue (key, value)
  483. values (?, ?);
  484. `, key, value)
  485. if err != nil {
  486. // Note: ContextError() would break canRetry()
  487. return err
  488. }
  489. return nil
  490. })
  491. }
  492. // GetKeyValue retrieves the value for a given key. If not found,
  493. // it returns an empty string value.
  494. func GetKeyValue(key string) (value string, err error) {
  495. checkInitDataStore()
  496. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  497. err = rows.Scan(&value)
  498. if err == sql.ErrNoRows {
  499. return "", nil
  500. }
  501. if err != nil {
  502. return "", ContextError(err)
  503. }
  504. return value, nil
  505. }