dataStore.go 11 KB

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