dataStore.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  158. return transactionWithRetry(func(transaction *sql.Tx) error {
  159. serverEntryExists, err := serverEntryExists(transaction, serverEntry.IpAddress)
  160. if err != nil {
  161. return ContextError(err)
  162. }
  163. if serverEntryExists && !replaceIfExists {
  164. Notice(NOTICE_INFO, "ignored update for server %s", serverEntry.IpAddress)
  165. return nil
  166. }
  167. _, err = transaction.Exec(`
  168. update serverEntry set rank = rank + 1
  169. where id = (select id from serverEntry order by rank desc limit 1);
  170. `)
  171. if err != nil {
  172. // Note: ContextError() would break canRetry()
  173. return err
  174. }
  175. data, err := json.Marshal(serverEntry)
  176. if err != nil {
  177. return ContextError(err)
  178. }
  179. _, err = transaction.Exec(`
  180. insert or replace into serverEntry (id, rank, region, data)
  181. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  182. `, serverEntry.IpAddress, serverEntry.Region, data)
  183. if err != nil {
  184. return err
  185. }
  186. _, err = transaction.Exec(`
  187. delete from serverEntryProtocol where serverEntryId = ?;
  188. `, serverEntry.IpAddress)
  189. if err != nil {
  190. return err
  191. }
  192. for _, protocol := range SupportedTunnelProtocols {
  193. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  194. // and the additonal OSSH service is assumed to be available internally.
  195. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  196. if Contains(serverEntry.Capabilities, requiredCapability) {
  197. _, err = transaction.Exec(`
  198. insert into serverEntryProtocol (serverEntryId, protocol)
  199. values (?, ?);
  200. `, serverEntry.IpAddress, protocol)
  201. if err != nil {
  202. return err
  203. }
  204. }
  205. }
  206. // TODO: post notice after commit
  207. if !serverEntryExists {
  208. Notice(NOTICE_INFO, "updated server %s", serverEntry.IpAddress)
  209. }
  210. return nil
  211. })
  212. }
  213. // StoreServerEntries shuffles and stores a list of server entries.
  214. // Shuffling is performed on imported server entrues as part of client-side
  215. // load balancing.
  216. // There is an independent transaction for each entry insert/update.
  217. func StoreServerEntries(serverEntries []*ServerEntry, replaceIfExists bool) error {
  218. for index := len(serverEntries) - 1; index > 0; index-- {
  219. swapIndex := rand.Intn(index + 1)
  220. serverEntries[index], serverEntries[swapIndex] = serverEntries[swapIndex], serverEntries[index]
  221. }
  222. for _, serverEntry := range serverEntries {
  223. err := StoreServerEntry(serverEntry, replaceIfExists)
  224. if err != nil {
  225. return ContextError(err)
  226. }
  227. }
  228. return nil
  229. }
  230. // PromoteServerEntry assigns the top rank (one more than current
  231. // max rank) to the specified server entry. Server candidates are
  232. // iterated in decending rank order, so this server entry will be
  233. // the first candidate in a subsequent tunnel establishment.
  234. func PromoteServerEntry(ipAddress string) error {
  235. return transactionWithRetry(func(transaction *sql.Tx) error {
  236. _, err := transaction.Exec(`
  237. update serverEntry
  238. set rank = (select MAX(rank)+1 from serverEntry)
  239. where id = ?;
  240. `, ipAddress)
  241. if err != nil {
  242. // Note: ContextError() would break canRetry()
  243. return err
  244. }
  245. return nil
  246. })
  247. }
  248. // ServerEntryIterator is used to iterate over
  249. // stored server entries in rank order.
  250. type ServerEntryIterator struct {
  251. region string
  252. protocol string
  253. excludeIds []string
  254. transaction *sql.Tx
  255. cursor *sql.Rows
  256. }
  257. // NewServerEntryIterator creates a new NewServerEntryIterator
  258. func NewServerEntryIterator(region, protocol string) (iterator *ServerEntryIterator, err error) {
  259. checkInitDataStore()
  260. iterator = &ServerEntryIterator{
  261. region: region,
  262. protocol: protocol,
  263. }
  264. err = iterator.Reset()
  265. if err != nil {
  266. return nil, err
  267. }
  268. return iterator, nil
  269. }
  270. // Reset a NewServerEntryIterator to the start of its cycle. The next
  271. // call to Next will return the first server entry.
  272. func (iterator *ServerEntryIterator) Reset() error {
  273. iterator.Close()
  274. transaction, err := singleton.db.Begin()
  275. if err != nil {
  276. return ContextError(err)
  277. }
  278. var cursor *sql.Rows
  279. // This query implements the Psiphon server candidate selection
  280. // algorithm: the first set of server candidates are in rank (priority)
  281. // order, to favor previously successful servers; then the remaining
  282. // long tail is shuffled to raise up less recent candidates.
  283. whereClause, whereParams := makeServerEntryWhereClause(
  284. iterator.region, iterator.protocol, nil)
  285. headLength := CONNECTION_WORKER_POOL_SIZE
  286. queryFormat := `
  287. select data from serverEntry %s
  288. order by case
  289. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  290. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  291. end desc;`
  292. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  293. params := make([]interface{}, 0)
  294. params = append(params, whereParams...)
  295. params = append(params, whereParams...)
  296. params = append(params, headLength)
  297. params = append(params, whereParams...)
  298. params = append(params, headLength)
  299. cursor, err = transaction.Query(query, params...)
  300. if err != nil {
  301. transaction.Rollback()
  302. return ContextError(err)
  303. }
  304. iterator.transaction = transaction
  305. iterator.cursor = cursor
  306. return nil
  307. }
  308. // Close cleans up resources associated with a ServerEntryIterator.
  309. func (iterator *ServerEntryIterator) Close() {
  310. if iterator.cursor != nil {
  311. iterator.cursor.Close()
  312. }
  313. iterator.cursor = nil
  314. if iterator.transaction != nil {
  315. iterator.transaction.Rollback()
  316. }
  317. iterator.transaction = nil
  318. }
  319. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  320. // Returns nil with no error when there is no next item.
  321. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  322. defer func() {
  323. if err != nil {
  324. iterator.Close()
  325. }
  326. }()
  327. if !iterator.cursor.Next() {
  328. err = iterator.cursor.Err()
  329. if err != nil {
  330. return nil, ContextError(err)
  331. }
  332. // There is no next item
  333. return nil, nil
  334. }
  335. var data []byte
  336. err = iterator.cursor.Scan(&data)
  337. if err != nil {
  338. return nil, ContextError(err)
  339. }
  340. serverEntry = new(ServerEntry)
  341. err = json.Unmarshal(data, serverEntry)
  342. if err != nil {
  343. return nil, ContextError(err)
  344. }
  345. return serverEntry, nil
  346. }
  347. func makeServerEntryWhereClause(
  348. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  349. whereClause = ""
  350. whereParams = make([]interface{}, 0)
  351. if region != "" {
  352. whereClause += " where region = ?"
  353. whereParams = append(whereParams, region)
  354. }
  355. if protocol != "" {
  356. if len(whereClause) > 0 {
  357. whereClause += " and"
  358. } else {
  359. whereClause += " where"
  360. }
  361. whereClause +=
  362. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  363. whereParams = append(whereParams, protocol)
  364. }
  365. if len(excludeIds) > 0 {
  366. if len(whereClause) > 0 {
  367. whereClause += " and"
  368. } else {
  369. whereClause += " where"
  370. }
  371. whereClause += " id in ("
  372. for index, id := range excludeIds {
  373. if index > 0 {
  374. whereClause += ", "
  375. }
  376. whereClause += "?"
  377. whereParams = append(whereParams, id)
  378. }
  379. whereClause += ")"
  380. }
  381. return whereClause, whereParams
  382. }
  383. // HasServerEntries returns true if the data store contains at
  384. // least one server entry (for the specified region and/or protocol,
  385. // when not blank).
  386. func HasServerEntries(region, protocol string) bool {
  387. checkInitDataStore()
  388. var count int
  389. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  390. query := "select count(*) from serverEntry" + whereClause
  391. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  392. if err != nil {
  393. Notice(NOTICE_ALERT, "HasServerEntries failed: %s", err)
  394. return false
  395. }
  396. if region == "" {
  397. region = "(any)"
  398. }
  399. if protocol == "" {
  400. protocol = "(any)"
  401. }
  402. Notice(NOTICE_INFO, "servers for region %s and protocol %s: %d",
  403. region, protocol, count)
  404. return count > 0
  405. }
  406. // GetServerEntryIpAddresses returns an array containing
  407. // all stored server IP addresses.
  408. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  409. checkInitDataStore()
  410. ipAddresses = make([]string, 0)
  411. rows, err := singleton.db.Query("select id from serverEntry;")
  412. if err != nil {
  413. return nil, ContextError(err)
  414. }
  415. defer rows.Close()
  416. for rows.Next() {
  417. var ipAddress string
  418. err = rows.Scan(&ipAddress)
  419. if err != nil {
  420. return nil, ContextError(err)
  421. }
  422. ipAddresses = append(ipAddresses, ipAddress)
  423. }
  424. if err = rows.Err(); err != nil {
  425. return nil, ContextError(err)
  426. }
  427. return ipAddresses, nil
  428. }
  429. // SetKeyValue stores a key/value pair.
  430. func SetKeyValue(key, value string) error {
  431. return transactionWithRetry(func(transaction *sql.Tx) error {
  432. _, err := transaction.Exec(`
  433. insert or replace into keyValue (key, value)
  434. values (?, ?);
  435. `, key, value)
  436. if err != nil {
  437. // Note: ContextError() would break canRetry()
  438. return err
  439. }
  440. return nil
  441. })
  442. }
  443. // GetKeyValue retrieves the value for a given key. If not found,
  444. // it returns an empty string value.
  445. func GetKeyValue(key string) (value string, err error) {
  446. checkInitDataStore()
  447. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  448. err = rows.Scan(&value)
  449. if err == sql.ErrNoRows {
  450. return "", nil
  451. }
  452. if err != nil {
  453. return "", ContextError(err)
  454. }
  455. return value, nil
  456. }