dataStore.go 11 KB

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