dataStore.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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(
  196. region, protocol string,
  197. excludeServerEntries []*ServerEntry) (iterator *ServerEntryIterator, err error) {
  198. initDataStore()
  199. excludeIds := make([]string, len(excludeServerEntries))
  200. for index, serverEntry := range excludeServerEntries {
  201. excludeIds[index] = serverEntry.IpAddress
  202. }
  203. iterator = &ServerEntryIterator{
  204. region: region,
  205. protocol: protocol,
  206. excludeIds: excludeIds,
  207. }
  208. err = iterator.Reset()
  209. if err != nil {
  210. return nil, err
  211. }
  212. return iterator, nil
  213. }
  214. // Reset a NewServerEntryIterator to the start of its cycle. The next
  215. // call to Next will return the first server entry.
  216. func (iterator *ServerEntryIterator) Reset() error {
  217. iterator.Close()
  218. transaction, err := singleton.db.Begin()
  219. if err != nil {
  220. return ContextError(err)
  221. }
  222. var cursor *sql.Rows
  223. whereClause, whereParams := makeServerEntryWhereClause(
  224. iterator.region, iterator.protocol, iterator.excludeIds)
  225. query := "select data from serverEntry" + whereClause + " order by rank desc;"
  226. cursor, err = transaction.Query(query, whereParams...)
  227. if err != nil {
  228. transaction.Rollback()
  229. return ContextError(err)
  230. }
  231. iterator.transaction = transaction
  232. iterator.cursor = cursor
  233. return nil
  234. }
  235. // Close cleans up resources associated with a ServerEntryIterator.
  236. func (iterator *ServerEntryIterator) Close() {
  237. if iterator.cursor != nil {
  238. iterator.cursor.Close()
  239. }
  240. iterator.cursor = nil
  241. if iterator.transaction != nil {
  242. iterator.transaction.Rollback()
  243. }
  244. iterator.transaction = nil
  245. }
  246. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  247. // Returns nil with no error when there is no next item.
  248. func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  249. defer func() {
  250. if err != nil {
  251. iterator.Close()
  252. }
  253. }()
  254. if !iterator.cursor.Next() {
  255. err = iterator.cursor.Err()
  256. if err != nil {
  257. return nil, ContextError(err)
  258. }
  259. // There is no next item
  260. return nil, nil
  261. }
  262. var data []byte
  263. err = iterator.cursor.Scan(&data)
  264. if err != nil {
  265. return nil, ContextError(err)
  266. }
  267. serverEntry = new(ServerEntry)
  268. err = json.Unmarshal(data, serverEntry)
  269. if err != nil {
  270. return nil, ContextError(err)
  271. }
  272. return serverEntry, nil
  273. }
  274. func makeServerEntryWhereClause(
  275. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  276. whereClause = ""
  277. whereParams = make([]interface{}, 0)
  278. if region != "" {
  279. whereClause += " where region = ?"
  280. whereParams = append(whereParams, region)
  281. }
  282. if protocol != "" {
  283. if len(whereClause) > 0 {
  284. whereClause += " and"
  285. } else {
  286. whereClause += " where"
  287. }
  288. whereClause +=
  289. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  290. whereParams = append(whereParams, protocol)
  291. }
  292. if len(excludeIds) > 0 {
  293. if len(whereClause) > 0 {
  294. whereClause += " and"
  295. } else {
  296. whereClause += " where"
  297. }
  298. whereClause += " id in ("
  299. for index, id := range excludeIds {
  300. if index > 0 {
  301. whereClause += ", "
  302. }
  303. whereClause += "?"
  304. whereParams = append(whereParams, id)
  305. }
  306. whereClause += ")"
  307. }
  308. return whereClause, whereParams
  309. }
  310. // HasServerEntries returns true if the data store contains at
  311. // least one server entry (for the specified region and/or protocol,
  312. // when not blank).
  313. func HasServerEntries(region, protocol string) bool {
  314. initDataStore()
  315. var count int
  316. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  317. query := "select count(*) from serverEntry" + whereClause
  318. err := singleton.db.QueryRow(query, whereParams...).Scan(&count)
  319. if region == "" {
  320. region = "(any)"
  321. }
  322. if protocol == "" {
  323. protocol = "(any)"
  324. }
  325. Notice(NOTICE_INFO, "servers for region %s and protocol %s: %d",
  326. region, protocol, count)
  327. return err == nil && count > 0
  328. }
  329. // GetServerEntryIpAddresses returns an array containing
  330. // all stored server IP addresses.
  331. func GetServerEntryIpAddresses() (ipAddresses []string, err error) {
  332. initDataStore()
  333. ipAddresses = make([]string, 0)
  334. rows, err := singleton.db.Query("select id from serverEntry;")
  335. if err != nil {
  336. return nil, ContextError(err)
  337. }
  338. defer rows.Close()
  339. for rows.Next() {
  340. var ipAddress string
  341. err = rows.Scan(&ipAddress)
  342. if err != nil {
  343. return nil, ContextError(err)
  344. }
  345. ipAddresses = append(ipAddresses, ipAddress)
  346. }
  347. if err = rows.Err(); err != nil {
  348. return nil, ContextError(err)
  349. }
  350. return ipAddresses, nil
  351. }
  352. // SetKeyValue stores a key/value pair.
  353. func SetKeyValue(key, value string) error {
  354. return transactionWithRetry(func(transaction *sql.Tx) error {
  355. _, err := transaction.Exec(`
  356. insert or replace into keyValue (key, value)
  357. values (?, ?);
  358. `, key, value)
  359. if err != nil {
  360. // Note: ContextError() would break canRetry()
  361. return err
  362. }
  363. return nil
  364. })
  365. }
  366. // GetLastConnected retrieves a key/value pair. If not found,
  367. // it returns an empty string value.
  368. func GetKeyValue(key string) (value string, err error) {
  369. initDataStore()
  370. rows := singleton.db.QueryRow("select value from keyValue where key = ?;", key)
  371. err = rows.Scan(&value)
  372. if err == sql.ErrNoRows {
  373. return "", nil
  374. }
  375. if err != nil {
  376. return "", ContextError(err)
  377. }
  378. return value, nil
  379. }