dataStore.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright (c) 2014, 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. // Nothing more to do
  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, "stored server %s", serverEntry.IpAddress)
  208. }
  209. return nil
  210. })
  211. }
  212. // PromoteServerEntry assigns the top rank (one more than current
  213. // max rank) to the specified server entry. Server candidates are
  214. // iterated in decending rank order, so this server entry will be
  215. // the first candidate in a subsequent tunnel establishment.
  216. func PromoteServerEntry(ipAddress string) error {
  217. return transactionWithRetry(func(transaction *sql.Tx) error {
  218. _, err := transaction.Exec(`
  219. update serverEntry
  220. set rank = (select MAX(rank)+1 from serverEntry)
  221. where id = ?;
  222. `, ipAddress)
  223. if err != nil {
  224. // Note: ContextError() would break canRetry()
  225. return err
  226. }
  227. return nil
  228. })
  229. }
  230. // ServerEntryIterator is used to iterate over
  231. // stored server entries in rank order.
  232. type ServerEntryIterator struct {
  233. region string
  234. protocol string
  235. excludeIds []string
  236. transaction *sql.Tx
  237. cursor *sql.Rows
  238. }
  239. // NewServerEntryIterator creates a new NewServerEntryIterator
  240. func NewServerEntryIterator(region, protocol string) (iterator *ServerEntryIterator, err error) {
  241. checkInitDataStore()
  242. iterator = &ServerEntryIterator{
  243. region: region,
  244. protocol: protocol,
  245. }
  246. err = iterator.Reset()
  247. if err != nil {
  248. return nil, err
  249. }
  250. return iterator, nil
  251. }
  252. // Reset a NewServerEntryIterator to the start of its cycle. The next
  253. // call to Next will return the first server entry.
  254. func (iterator *ServerEntryIterator) Reset() error {
  255. iterator.Close()
  256. transaction, err := singleton.db.Begin()
  257. if err != nil {
  258. return ContextError(err)
  259. }
  260. var cursor *sql.Rows
  261. whereClause, whereParams := makeServerEntryWhereClause(
  262. iterator.region, iterator.protocol, nil)
  263. query := "select data from serverEntry" + whereClause + " order by rank desc;"
  264. cursor, err = transaction.Query(query, whereParams...)
  265. if err != nil {
  266. transaction.Rollback()
  267. return ContextError(err)
  268. }
  269. iterator.transaction = transaction
  270. iterator.cursor = cursor
  271. return nil
  272. }
  273. // Close cleans up resources associated with a ServerEntryIterator.
  274. func (iterator *ServerEntryIterator) Close() {
  275. if iterator.cursor != nil {
  276. iterator.cursor.Close()
  277. }
  278. iterator.cursor = nil
  279. if iterator.transaction != nil {
  280. iterator.transaction.Rollback()
  281. }
  282. iterator.transaction = nil
  283. }
  284. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  285. // Returns nil with no error when there is no next item.
  286. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  287. defer func() {
  288. if err != nil {
  289. iterator.Close()
  290. }
  291. }()
  292. if !iterator.cursor.Next() {
  293. err = iterator.cursor.Err()
  294. if err != nil {
  295. return nil, ContextError(err)
  296. }
  297. // There is no next item
  298. return nil, nil
  299. }
  300. var data []byte
  301. err = iterator.cursor.Scan(&data)
  302. if err != nil {
  303. return nil, ContextError(err)
  304. }
  305. serverEntry = new(ServerEntry)
  306. err = json.Unmarshal(data, serverEntry)
  307. if err != nil {
  308. return nil, ContextError(err)
  309. }
  310. return serverEntry, nil
  311. }
  312. func makeServerEntryWhereClause(
  313. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  314. whereClause = ""
  315. whereParams = make([]interface{}, 0)
  316. if region != "" {
  317. whereClause += " where region = ?"
  318. whereParams = append(whereParams, region)
  319. }
  320. if protocol != "" {
  321. if len(whereClause) > 0 {
  322. whereClause += " and"
  323. } else {
  324. whereClause += " where"
  325. }
  326. whereClause +=
  327. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  328. whereParams = append(whereParams, protocol)
  329. }
  330. if len(excludeIds) > 0 {
  331. if len(whereClause) > 0 {
  332. whereClause += " and"
  333. } else {
  334. whereClause += " where"
  335. }
  336. whereClause += " id in ("
  337. for index, id := range excludeIds {
  338. if index > 0 {
  339. whereClause += ", "
  340. }
  341. whereClause += "?"
  342. whereParams = append(whereParams, id)
  343. }
  344. whereClause += ")"
  345. }
  346. return whereClause, whereParams
  347. }
  348. // HasServerEntries returns true if the data store contains at
  349. // least one server entry (for the specified region and/or protocol,
  350. // when not blank).
  351. func HasServerEntries(region, protocol string) bool {
  352. checkInitDataStore()
  353. var count int
  354. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  355. query := "select count(*) from serverEntry" + whereClause
  356. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  357. if err != nil {
  358. Notice(NOTICE_ALERT, "HasServerEntries failed: %s", err)
  359. return false
  360. }
  361. if region == "" {
  362. region = "(any)"
  363. }
  364. if protocol == "" {
  365. protocol = "(any)"
  366. }
  367. Notice(NOTICE_INFO, "servers for region %s and protocol %s: %d",
  368. region, protocol, count)
  369. return count > 0
  370. }
  371. // GetServerEntryIpAddresses returns an array containing
  372. // all stored server IP addresses.
  373. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  374. checkInitDataStore()
  375. ipAddresses = make([]string, 0)
  376. rows, err := singleton.db.Query("select id from serverEntry;")
  377. if err != nil {
  378. return nil, ContextError(err)
  379. }
  380. defer rows.Close()
  381. for rows.Next() {
  382. var ipAddress string
  383. err = rows.Scan(&ipAddress)
  384. if err != nil {
  385. return nil, ContextError(err)
  386. }
  387. ipAddresses = append(ipAddresses, ipAddress)
  388. }
  389. if err = rows.Err(); err != nil {
  390. return nil, ContextError(err)
  391. }
  392. return ipAddresses, nil
  393. }
  394. // SetKeyValue stores a key/value pair.
  395. func SetKeyValue(key, value string) error {
  396. return transactionWithRetry(func(transaction *sql.Tx) error {
  397. _, err := transaction.Exec(`
  398. insert or replace into keyValue (key, value)
  399. values (?, ?);
  400. `, key, value)
  401. if err != nil {
  402. // Note: ContextError() would break canRetry()
  403. return err
  404. }
  405. return nil
  406. })
  407. }
  408. // GetKeyValue retrieves the value for a given key. If not found,
  409. // it returns an empty string value.
  410. func GetKeyValue(key string) (value string, err error) {
  411. checkInitDataStore()
  412. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  413. err = rows.Scan(&value)
  414. if err == sql.ErrNoRows {
  415. return "", nil
  416. }
  417. if err != nil {
  418. return "", ContextError(err)
  419. }
  420. return value, nil
  421. }