dataStore.go 12 KB

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