dataStore.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. "path/filepath"
  26. "strings"
  27. "sync"
  28. "time"
  29. sqlite3 "github.com/Psiphon-Inc/go-sqlite3"
  30. )
  31. type dataStore struct {
  32. init sync.Once
  33. db *sql.DB
  34. }
  35. var singleton dataStore
  36. // InitDataStore initializes the singleton instance of dataStore. This
  37. // function uses a sync.Once and is safe for use by concurrent goroutines.
  38. // The underlying sql.DB connection pool is also safe.
  39. //
  40. // Note: the sync.Once was more useful when initDataStore was private and
  41. // called on-demand by the public functions below. Now we require an explicit
  42. // InitDataStore() call with the filename passed in. The on-demand calls
  43. // have been replaced by checkInitDataStore() to assert that Init was called.
  44. func InitDataStore(config *Config) (err error) {
  45. singleton.init.Do(func() {
  46. filename := filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)
  47. var db *sql.DB
  48. db, err = sql.Open(
  49. "sqlite3",
  50. fmt.Sprintf("file:%s?cache=private&mode=rwc", filename))
  51. if err != nil {
  52. // Note: intending to set the err return value for InitDataStore
  53. err = fmt.Errorf("initDataStore failed to open database: %s", err)
  54. return
  55. }
  56. initialization := "pragma journal_mode=WAL;\n"
  57. if config.DataStoreTempDirectory != "" {
  58. // On some platforms (e.g., Android), the standard temporary directories expected
  59. // by sqlite (see unixGetTempname in aggregate sqlite3.c) may not be present.
  60. // In that case, sqlite tries to use the current working directory; but this may
  61. // be "/" (again, on Android) which is not writable.
  62. // Instead of setting the process current working directory from this library,
  63. // use the deprecated temp_store_directory pragma to force use of a specified
  64. // temporary directory: https://www.sqlite.org/pragma.html#pragma_temp_store_directory.
  65. // TODO: is there another way to restrict writing of temporary files? E.g. temp_store=3?
  66. initialization += fmt.Sprintf(
  67. "pragma temp_store_directory=\"%s\";\n", config.DataStoreDirectory)
  68. }
  69. initialization += `
  70. create table if not exists serverEntry
  71. (id text not null primary key,
  72. rank integer not null unique,
  73. region text not null,
  74. data blob not null);
  75. create table if not exists serverEntryProtocol
  76. (serverEntryId text not null,
  77. protocol text not null,
  78. primary key (serverEntryId, protocol));
  79. create table if not exists keyValue
  80. (key text not null primary key,
  81. value text not null);
  82. `
  83. _, err = db.Exec(initialization)
  84. if err != nil {
  85. err = fmt.Errorf("initDataStore failed to initialize: %s", err)
  86. return
  87. }
  88. singleton.db = db
  89. })
  90. return err
  91. }
  92. func checkInitDataStore() {
  93. if singleton.db == nil {
  94. panic("checkInitDataStore: datastore not initialized")
  95. }
  96. }
  97. func canRetry(err error) bool {
  98. sqlError, ok := err.(sqlite3.Error)
  99. return ok && (sqlError.Code == sqlite3.ErrBusy ||
  100. sqlError.Code == sqlite3.ErrLocked ||
  101. sqlError.ExtendedCode == sqlite3.ErrLockedSharedCache ||
  102. sqlError.ExtendedCode == sqlite3.ErrBusySnapshot)
  103. }
  104. // transactionWithRetry will retry a write transaction if sqlite3
  105. // reports a table is locked by another writer.
  106. func transactionWithRetry(updater func(*sql.Tx) error) error {
  107. checkInitDataStore()
  108. for i := 0; i < 10; i++ {
  109. if i > 0 {
  110. // Delay on retry
  111. time.Sleep(100)
  112. }
  113. transaction, err := singleton.db.Begin()
  114. if err != nil {
  115. return ContextError(err)
  116. }
  117. err = updater(transaction)
  118. if err != nil {
  119. transaction.Rollback()
  120. if canRetry(err) {
  121. continue
  122. }
  123. return ContextError(err)
  124. }
  125. err = transaction.Commit()
  126. if err != nil {
  127. transaction.Rollback()
  128. if canRetry(err) {
  129. continue
  130. }
  131. return ContextError(err)
  132. }
  133. return nil
  134. }
  135. return ContextError(errors.New("retries exhausted"))
  136. }
  137. // serverEntryExists returns true if a serverEntry with the
  138. // given ipAddress id already exists.
  139. func serverEntryExists(transaction *sql.Tx, ipAddress string) (bool, error) {
  140. query := "select count(*) from serverEntry where id = ?;"
  141. var count int
  142. err := singleton.db.QueryRow(query, ipAddress).Scan(&count)
  143. if err != nil {
  144. return false, ContextError(err)
  145. }
  146. return count > 0, nil
  147. }
  148. // StoreServerEntry adds the server entry to the data store.
  149. // A newly stored (or re-stored) server entry is assigned the next-to-top
  150. // rank for iteration order (the previous top ranked entry is promoted). The
  151. // purpose of inserting at next-to-top is to keep the last selected server
  152. // as the top ranked server. Note, server candidates are iterated in decending
  153. // rank order, so the largest rank is top rank.
  154. // When replaceIfExists is true, an existing server entry record is
  155. // overwritten; otherwise, the existing record is unchanged.
  156. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  157. return transactionWithRetry(func(transaction *sql.Tx) error {
  158. serverEntryExists, err := serverEntryExists(transaction, serverEntry.IpAddress)
  159. if err != nil {
  160. return ContextError(err)
  161. }
  162. if serverEntryExists && !replaceIfExists {
  163. Notice(NOTICE_INFO, "ignored update for server %s", serverEntry.IpAddress)
  164. return nil
  165. }
  166. _, err = transaction.Exec(`
  167. update serverEntry set rank = rank + 1
  168. where id = (select id from serverEntry order by rank desc limit 1);
  169. `)
  170. if err != nil {
  171. // Note: ContextError() would break canRetry()
  172. return err
  173. }
  174. data, err := json.Marshal(serverEntry)
  175. if err != nil {
  176. return ContextError(err)
  177. }
  178. _, err = transaction.Exec(`
  179. insert or replace into serverEntry (id, rank, region, data)
  180. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  181. `, serverEntry.IpAddress, serverEntry.Region, data)
  182. if err != nil {
  183. return err
  184. }
  185. _, err = transaction.Exec(`
  186. delete from serverEntryProtocol where serverEntryId = ?;
  187. `, serverEntry.IpAddress)
  188. if err != nil {
  189. return err
  190. }
  191. for _, protocol := range SupportedTunnelProtocols {
  192. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  193. // and the additonal OSSH service is assumed to be available internally.
  194. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  195. if Contains(serverEntry.Capabilities, requiredCapability) {
  196. _, err = transaction.Exec(`
  197. insert into serverEntryProtocol (serverEntryId, protocol)
  198. values (?, ?);
  199. `, serverEntry.IpAddress, protocol)
  200. if err != nil {
  201. return err
  202. }
  203. }
  204. }
  205. // TODO: post notice after commit
  206. if !serverEntryExists {
  207. Notice(NOTICE_INFO, "updated server %s", serverEntry.IpAddress)
  208. }
  209. return nil
  210. })
  211. }
  212. // StoreServerEntries stores a list of server entries. This is simply a
  213. // helper which calls StoreServerEntry on each entry in the list -- so there
  214. // is an independent transaction for each entry -- and stops on first error.
  215. func StoreServerEntries(serverEntries []*ServerEntry, replaceIfExists bool) error {
  216. for _, serverEntry := range serverEntries {
  217. err := StoreServerEntry(serverEntry, replaceIfExists)
  218. if err != nil {
  219. return ContextError(err)
  220. }
  221. }
  222. return nil
  223. }
  224. // PromoteServerEntry assigns the top rank (one more than current
  225. // max rank) to the specified server entry. Server candidates are
  226. // iterated in decending rank order, so this server entry will be
  227. // the first candidate in a subsequent tunnel establishment.
  228. func PromoteServerEntry(ipAddress string) error {
  229. return transactionWithRetry(func(transaction *sql.Tx) error {
  230. _, err := transaction.Exec(`
  231. update serverEntry
  232. set rank = (select MAX(rank)+1 from serverEntry)
  233. where id = ?;
  234. `, ipAddress)
  235. if err != nil {
  236. // Note: ContextError() would break canRetry()
  237. return err
  238. }
  239. return nil
  240. })
  241. }
  242. // ServerEntryIterator is used to iterate over
  243. // stored server entries in rank order.
  244. type ServerEntryIterator struct {
  245. region string
  246. protocol string
  247. excludeIds []string
  248. transaction *sql.Tx
  249. cursor *sql.Rows
  250. }
  251. // NewServerEntryIterator creates a new NewServerEntryIterator
  252. func NewServerEntryIterator(region, protocol string) (iterator *ServerEntryIterator, err error) {
  253. checkInitDataStore()
  254. iterator = &ServerEntryIterator{
  255. region: region,
  256. protocol: protocol,
  257. }
  258. err = iterator.Reset()
  259. if err != nil {
  260. return nil, err
  261. }
  262. return iterator, nil
  263. }
  264. // Reset a NewServerEntryIterator to the start of its cycle. The next
  265. // call to Next will return the first server entry.
  266. func (iterator *ServerEntryIterator) Reset() error {
  267. iterator.Close()
  268. transaction, err := singleton.db.Begin()
  269. if err != nil {
  270. return ContextError(err)
  271. }
  272. var cursor *sql.Rows
  273. whereClause, whereParams := makeServerEntryWhereClause(
  274. iterator.region, iterator.protocol, nil)
  275. query := "select data from serverEntry" + whereClause + " order by rank desc;"
  276. cursor, err = transaction.Query(query, whereParams...)
  277. if err != nil {
  278. transaction.Rollback()
  279. return ContextError(err)
  280. }
  281. iterator.transaction = transaction
  282. iterator.cursor = cursor
  283. return nil
  284. }
  285. // Close cleans up resources associated with a ServerEntryIterator.
  286. func (iterator *ServerEntryIterator) Close() {
  287. if iterator.cursor != nil {
  288. iterator.cursor.Close()
  289. }
  290. iterator.cursor = nil
  291. if iterator.transaction != nil {
  292. iterator.transaction.Rollback()
  293. }
  294. iterator.transaction = nil
  295. }
  296. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  297. // Returns nil with no error when there is no next item.
  298. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  299. defer func() {
  300. if err != nil {
  301. iterator.Close()
  302. }
  303. }()
  304. if !iterator.cursor.Next() {
  305. err = iterator.cursor.Err()
  306. if err != nil {
  307. return nil, ContextError(err)
  308. }
  309. // There is no next item
  310. return nil, nil
  311. }
  312. var data []byte
  313. err = iterator.cursor.Scan(&data)
  314. if err != nil {
  315. return nil, ContextError(err)
  316. }
  317. serverEntry = new(ServerEntry)
  318. err = json.Unmarshal(data, serverEntry)
  319. if err != nil {
  320. return nil, ContextError(err)
  321. }
  322. return serverEntry, nil
  323. }
  324. func makeServerEntryWhereClause(
  325. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  326. whereClause = ""
  327. whereParams = make([]interface{}, 0)
  328. if region != "" {
  329. whereClause += " where region = ?"
  330. whereParams = append(whereParams, region)
  331. }
  332. if protocol != "" {
  333. if len(whereClause) > 0 {
  334. whereClause += " and"
  335. } else {
  336. whereClause += " where"
  337. }
  338. whereClause +=
  339. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  340. whereParams = append(whereParams, protocol)
  341. }
  342. if len(excludeIds) > 0 {
  343. if len(whereClause) > 0 {
  344. whereClause += " and"
  345. } else {
  346. whereClause += " where"
  347. }
  348. whereClause += " id in ("
  349. for index, id := range excludeIds {
  350. if index > 0 {
  351. whereClause += ", "
  352. }
  353. whereClause += "?"
  354. whereParams = append(whereParams, id)
  355. }
  356. whereClause += ")"
  357. }
  358. return whereClause, whereParams
  359. }
  360. // HasServerEntries returns true if the data store contains at
  361. // least one server entry (for the specified region and/or protocol,
  362. // when not blank).
  363. func HasServerEntries(region, protocol string) bool {
  364. checkInitDataStore()
  365. var count int
  366. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  367. query := "select count(*) from serverEntry" + whereClause
  368. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  369. if err != nil {
  370. Notice(NOTICE_ALERT, "HasServerEntries failed: %s", err)
  371. return false
  372. }
  373. if region == "" {
  374. region = "(any)"
  375. }
  376. if protocol == "" {
  377. protocol = "(any)"
  378. }
  379. Notice(NOTICE_INFO, "servers for region %s and protocol %s: %d",
  380. region, protocol, count)
  381. return count > 0
  382. }
  383. // GetServerEntryIpAddresses returns an array containing
  384. // all stored server IP addresses.
  385. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  386. checkInitDataStore()
  387. ipAddresses = make([]string, 0)
  388. rows, err := singleton.db.Query("select id from serverEntry;")
  389. if err != nil {
  390. return nil, ContextError(err)
  391. }
  392. defer rows.Close()
  393. for rows.Next() {
  394. var ipAddress string
  395. err = rows.Scan(&ipAddress)
  396. if err != nil {
  397. return nil, ContextError(err)
  398. }
  399. ipAddresses = append(ipAddresses, ipAddress)
  400. }
  401. if err = rows.Err(); err != nil {
  402. return nil, ContextError(err)
  403. }
  404. return ipAddresses, nil
  405. }
  406. // SetKeyValue stores a key/value pair.
  407. func SetKeyValue(key, value string) error {
  408. return transactionWithRetry(func(transaction *sql.Tx) error {
  409. _, err := transaction.Exec(`
  410. insert or replace into keyValue (key, value)
  411. values (?, ?);
  412. `, key, value)
  413. if err != nil {
  414. // Note: ContextError() would break canRetry()
  415. return err
  416. }
  417. return nil
  418. })
  419. }
  420. // GetKeyValue retrieves the value for a given key. If not found,
  421. // it returns an empty string value.
  422. func GetKeyValue(key string) (value string, err error) {
  423. checkInitDataStore()
  424. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  425. err = rows.Scan(&value)
  426. if err == sql.ErrNoRows {
  427. return "", nil
  428. }
  429. if err != nil {
  430. return "", ContextError(err)
  431. }
  432. return value, nil
  433. }