dataStore.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. primary key (serverEntryId, protocol));
  50. create table if not exists keyValue
  51. (key text not null primary key,
  52. value text not null);
  53. pragma journal_mode=WAL;
  54. `
  55. db, err := sql.Open(
  56. "sqlite3",
  57. fmt.Sprintf("file:%s?cache=private&mode=rwc", DATA_STORE_FILENAME))
  58. if err != nil {
  59. Fatal("initDataStore failed to open database: %s", err)
  60. }
  61. _, err = db.Exec(schema)
  62. if err != nil {
  63. Fatal("initDataStore failed to initialize schema: %s", err)
  64. }
  65. singleton.db = db
  66. })
  67. }
  68. func canRetry(err error) bool {
  69. sqlError, ok := err.(sqlite3.Error)
  70. return ok && (sqlError.Code == sqlite3.ErrBusy ||
  71. sqlError.Code == sqlite3.ErrLocked ||
  72. sqlError.ExtendedCode == sqlite3.ErrLockedSharedCache ||
  73. sqlError.ExtendedCode == sqlite3.ErrBusySnapshot)
  74. }
  75. // transactionWithRetry will retry a write transaction if sqlite3
  76. // reports a table is locked by another writer.
  77. func transactionWithRetry(updater func(*sql.Tx) error) error {
  78. initDataStore()
  79. for i := 0; i < 10; i++ {
  80. if i > 0 {
  81. // Delay on retry
  82. time.Sleep(100)
  83. }
  84. transaction, err := singleton.db.Begin()
  85. if err != nil {
  86. return ContextError(err)
  87. }
  88. err = updater(transaction)
  89. if err != nil {
  90. transaction.Rollback()
  91. if canRetry(err) {
  92. continue
  93. }
  94. return ContextError(err)
  95. }
  96. err = transaction.Commit()
  97. if err != nil {
  98. transaction.Rollback()
  99. if canRetry(err) {
  100. continue
  101. }
  102. return ContextError(err)
  103. }
  104. return nil
  105. }
  106. return ContextError(errors.New("retries exhausted"))
  107. }
  108. // serverEntryExists returns true if a serverEntry with the
  109. // given ipAddress id already exists.
  110. func serverEntryExists(transaction *sql.Tx, ipAddress string) bool {
  111. query := "select count(*) from serverEntry where id = ?;"
  112. var count int
  113. err := singleton.db.QueryRow(query, ipAddress).Scan(&count)
  114. return err == nil && count > 0
  115. }
  116. // StoreServerEntry adds the server entry to the data store. A newly
  117. // stored (or re-stored) server entry is assigned the next-to-top rank
  118. // for cycle order (the previous top ranked entry is promoted). The
  119. // purpose of this is to keep the last selected server as the top
  120. // ranked server.
  121. // When replaceIfExists is true, an existing server entry record is
  122. // overwritten; otherwise, the existing record is unchanged.
  123. func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error {
  124. return transactionWithRetry(func(transaction *sql.Tx) error {
  125. serverEntryExists := serverEntryExists(transaction, serverEntry.IpAddress)
  126. if serverEntryExists && !replaceIfExists {
  127. return nil
  128. }
  129. _, err := transaction.Exec(`
  130. update serverEntry set rank = rank + 1
  131. where id = (select id from serverEntry order by rank desc limit 1);
  132. `)
  133. if err != nil {
  134. // Note: ContextError() would break canRetry()
  135. return err
  136. }
  137. data, err := json.Marshal(serverEntry)
  138. if err != nil {
  139. return ContextError(err)
  140. }
  141. _, err = transaction.Exec(`
  142. insert or replace into serverEntry (id, rank, region, data)
  143. values (?, (select coalesce(max(rank)-1, 0) from serverEntry), ?, ?);
  144. `, serverEntry.IpAddress, serverEntry.Region, data)
  145. if err != nil {
  146. return err
  147. }
  148. _, err = transaction.Exec(`
  149. delete from serverEntryProtocol where serverEntryId = ?;
  150. `, serverEntry.IpAddress)
  151. if err != nil {
  152. return err
  153. }
  154. for _, protocol := range SupportedTunnelProtocols {
  155. // Note: for meek, the capabilities are FRONTED-MEEK and UNFRONTED-MEEK
  156. // and the additonal OSSH service is assumed to be available internally.
  157. requiredCapability := strings.TrimSuffix(protocol, "-OSSH")
  158. if Contains(serverEntry.Capabilities, requiredCapability) {
  159. _, err = transaction.Exec(`
  160. insert into serverEntryProtocol (serverEntryId, protocol)
  161. values (?, ?);
  162. `, serverEntry.IpAddress, protocol)
  163. if err != nil {
  164. return err
  165. }
  166. }
  167. }
  168. // TODO: post notice after commit
  169. if !serverEntryExists {
  170. Notice(NOTICE_INFO, "stored server %s", serverEntry.IpAddress)
  171. }
  172. return nil
  173. })
  174. }
  175. // PromoteServerEntry assigns the top cycle rank to the specified
  176. // server entry. This server entry will be the first candidate in
  177. // a subsequent tunnel establishment.
  178. func PromoteServerEntry(ipAddress string) error {
  179. return transactionWithRetry(func(transaction *sql.Tx) error {
  180. _, err := transaction.Exec(`
  181. update serverEntry
  182. set rank = (select MAX(rank)+1 from serverEntry)
  183. where id = ?;
  184. `, ipAddress)
  185. if err != nil {
  186. // Note: ContextError() would break canRetry()
  187. return err
  188. }
  189. return nil
  190. })
  191. }
  192. // ServerEntryIterator is used to iterate over
  193. // stored server entries in rank order.
  194. type ServerEntryIterator struct {
  195. region string
  196. protocol string
  197. excludeIds []string
  198. transaction *sql.Tx
  199. cursor *sql.Rows
  200. }
  201. // NewServerEntryIterator creates a new NewServerEntryIterator
  202. func NewServerEntryIterator(region, protocol string) (iterator *ServerEntryIterator, err error) {
  203. initDataStore()
  204. iterator = &ServerEntryIterator{
  205. region: region,
  206. protocol: protocol,
  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, nil)
  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. }