dataStore.go 12 KB

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