migrateDataStore.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // TODO: Windows only build flag + runtime.GOOS check in datastore.go?
  2. /*
  3. * Copyright (c) 2015, Psiphon Inc.
  4. * All rights reserved.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package psiphon
  21. import (
  22. "database/sql"
  23. "encoding/json"
  24. "errors"
  25. "fmt"
  26. "os"
  27. "path/filepath"
  28. "strings"
  29. _ "github.com/Psiphon-Inc/go-sqlite3"
  30. )
  31. var legacyDb *sql.DB
  32. var migratableServerEntries []*ServerEntry
  33. func PrepareMigrationEntries(config *Config) ([]*ServerEntry, error) {
  34. if _, err := os.Stat(filepath.Join(config.DataStoreDirectory, LEGACY_DATA_STORE_FILENAME)); err == nil {
  35. if _, err := os.Stat(filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)); os.IsNotExist(err) {
  36. NoticeInfo("sqlite DB found, boltdb not found; preparing datastore migration")
  37. legacyDb, err = sql.Open("sqlite3", fmt.Sprintf("file:%s?cache=private&mode=rwc", filepath.Join(config.DataStoreDirectory, LEGACY_DATA_STORE_FILENAME)))
  38. if err != nil {
  39. return migratableServerEntries, err
  40. }
  41. initialization := "pragma journal_mode=WAL;\n"
  42. _, err = legacyDb.Exec(initialization)
  43. if err != nil {
  44. return migratableServerEntries, err
  45. }
  46. iterator, err := NewLegacyServerEntryIterator(config)
  47. if err != nil {
  48. return migratableServerEntries, err
  49. }
  50. defer iterator.Close()
  51. for {
  52. serverEntry, err := iterator.Next()
  53. if err != nil {
  54. err = fmt.Errorf("Failed to iterate legacy server entries: %s", err)
  55. break
  56. }
  57. if serverEntry == nil {
  58. break
  59. }
  60. NoticeInfo("Server entry (%s) prepped for migration", serverEntry.IpAddress)
  61. migratableServerEntries = append(migratableServerEntries, serverEntry)
  62. }
  63. NoticeInfo("All entries prepped")
  64. }
  65. }
  66. return migratableServerEntries, nil
  67. }
  68. func MigrateEntries(serverEntries []*ServerEntry) error {
  69. err := StoreServerEntries(serverEntries, false)
  70. if err != nil {
  71. return err
  72. }
  73. return nil
  74. }
  75. // This code is copied from the dataStore.go code used to operate the legacy
  76. // SQLite datastore. The word "Legacy" was added to all of the method names to avoid
  77. // namespace conflicts with the methods used to operate the BoltDB datastore
  78. // LegacyServerEntryIterator is used to iterate over
  79. // stored server entries in rank order.
  80. type LegacyServerEntryIterator struct {
  81. region string
  82. protocol string
  83. shuffleHeadLength int
  84. transaction *sql.Tx
  85. cursor *sql.Rows
  86. isTargetServerEntryIterator bool
  87. hasNextTargetServerEntry bool
  88. targetServerEntry *ServerEntry
  89. }
  90. // NewLegacyServerEntryIterator creates a new NewLegacyServerEntryIterator
  91. func NewLegacyServerEntryIterator(config *Config) (iterator *LegacyServerEntryIterator, err error) {
  92. // When configured, this target server entry is the only candidate
  93. if config.TargetServerEntry != "" {
  94. return newLegacyTargetServerEntryIterator(config)
  95. }
  96. iterator = &LegacyServerEntryIterator{
  97. region: config.EgressRegion,
  98. protocol: config.TunnelProtocol,
  99. shuffleHeadLength: config.TunnelPoolSize,
  100. isTargetServerEntryIterator: false,
  101. }
  102. err = iterator.Reset()
  103. if err != nil {
  104. return nil, err
  105. }
  106. return iterator, nil
  107. }
  108. // newLegacyTargetServerEntryIterator is a helper for initializing the LegacyTargetServerEntry case
  109. func newLegacyTargetServerEntryIterator(config *Config) (iterator *LegacyServerEntryIterator, err error) {
  110. serverEntry, err := DecodeServerEntry(config.TargetServerEntry)
  111. if err != nil {
  112. return nil, err
  113. }
  114. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  115. return nil, errors.New("TargetServerEntry does not support EgressRegion")
  116. }
  117. if config.TunnelProtocol != "" {
  118. // Note: same capability/protocol mapping as in StoreServerEntry
  119. requiredCapability := strings.TrimSuffix(config.TunnelProtocol, "-OSSH")
  120. if !Contains(serverEntry.Capabilities, requiredCapability) {
  121. return nil, errors.New("TargetServerEntry does not support TunnelProtocol")
  122. }
  123. }
  124. iterator = &LegacyServerEntryIterator{
  125. isTargetServerEntryIterator: true,
  126. hasNextTargetServerEntry: true,
  127. targetServerEntry: serverEntry,
  128. }
  129. NoticeInfo("using TargetServerEntry: %s", serverEntry.IpAddress)
  130. return iterator, nil
  131. }
  132. // Close cleans up resources associated with a LegacyServerEntryIterator.
  133. func (iterator *LegacyServerEntryIterator) Close() {
  134. if iterator.cursor != nil {
  135. iterator.cursor.Close()
  136. }
  137. iterator.cursor = nil
  138. if iterator.transaction != nil {
  139. iterator.transaction.Rollback()
  140. }
  141. iterator.transaction = nil
  142. }
  143. // Next returns the next server entry, by rank, for a LegacyServerEntryIterator.
  144. // Returns nil with no error when there is no next item.
  145. func (iterator *LegacyServerEntryIterator) Next() (serverEntry *ServerEntry, err error) {
  146. defer func() {
  147. if err != nil {
  148. iterator.Close()
  149. }
  150. }()
  151. if iterator.isTargetServerEntryIterator {
  152. if iterator.hasNextTargetServerEntry {
  153. iterator.hasNextTargetServerEntry = false
  154. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  155. }
  156. return nil, nil
  157. }
  158. if !iterator.cursor.Next() {
  159. err = iterator.cursor.Err()
  160. if err != nil {
  161. return nil, ContextError(err)
  162. }
  163. // There is no next item
  164. return nil, nil
  165. }
  166. var data []byte
  167. err = iterator.cursor.Scan(&data)
  168. if err != nil {
  169. return nil, ContextError(err)
  170. }
  171. serverEntry = new(ServerEntry)
  172. err = json.Unmarshal(data, serverEntry)
  173. if err != nil {
  174. return nil, ContextError(err)
  175. }
  176. return MakeCompatibleServerEntry(serverEntry), nil
  177. }
  178. // Reset a NewLegacyServerEntryIterator to the start of its cycle. The next
  179. // call to Next will return the first server entry.
  180. func (iterator *LegacyServerEntryIterator) Reset() error {
  181. iterator.Close()
  182. if iterator.isTargetServerEntryIterator {
  183. iterator.hasNextTargetServerEntry = true
  184. return nil
  185. }
  186. count := CountLegacyServerEntries(iterator.region, iterator.protocol)
  187. NoticeCandidateServers(iterator.region, iterator.protocol, count)
  188. transaction, err := legacyDb.Begin()
  189. if err != nil {
  190. return ContextError(err)
  191. }
  192. var cursor *sql.Rows
  193. // This query implements the Psiphon server candidate selection
  194. // algorithm: the first TunnelPoolSize server candidates are in rank
  195. // (priority) order, to favor previously successful servers; then the
  196. // remaining long tail is shuffled to raise up less recent candidates.
  197. whereClause, whereParams := makeServerEntryWhereClause(
  198. iterator.region, iterator.protocol, nil)
  199. headLength := iterator.shuffleHeadLength
  200. queryFormat := `
  201. select data from serverEntry %s
  202. order by case
  203. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  204. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  205. end desc;`
  206. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  207. params := make([]interface{}, 0)
  208. params = append(params, whereParams...)
  209. params = append(params, whereParams...)
  210. params = append(params, headLength)
  211. params = append(params, whereParams...)
  212. params = append(params, headLength)
  213. cursor, err = transaction.Query(query, params...)
  214. if err != nil {
  215. transaction.Rollback()
  216. return ContextError(err)
  217. }
  218. iterator.transaction = transaction
  219. iterator.cursor = cursor
  220. return nil
  221. }
  222. func makeServerEntryWhereClause(
  223. region, protocol string, excludeIds []string) (whereClause string, whereParams []interface{}) {
  224. whereClause = ""
  225. whereParams = make([]interface{}, 0)
  226. if region != "" {
  227. whereClause += " where region = ?"
  228. whereParams = append(whereParams, region)
  229. }
  230. if protocol != "" {
  231. if len(whereClause) > 0 {
  232. whereClause += " and"
  233. } else {
  234. whereClause += " where"
  235. }
  236. whereClause +=
  237. " exists (select 1 from serverEntryProtocol where protocol = ? and serverEntryId = serverEntry.id)"
  238. whereParams = append(whereParams, protocol)
  239. }
  240. if len(excludeIds) > 0 {
  241. if len(whereClause) > 0 {
  242. whereClause += " and"
  243. } else {
  244. whereClause += " where"
  245. }
  246. whereClause += " id in ("
  247. for index, id := range excludeIds {
  248. if index > 0 {
  249. whereClause += ", "
  250. }
  251. whereClause += "?"
  252. whereParams = append(whereParams, id)
  253. }
  254. whereClause += ")"
  255. }
  256. return whereClause, whereParams
  257. }
  258. // CountLegacyServerEntries returns a count of stored servers for the
  259. // specified region and protocol.
  260. func CountLegacyServerEntries(region, protocol string) int {
  261. var count int
  262. whereClause, whereParams := makeServerEntryWhereClause(region, protocol, nil)
  263. query := "select count(*) from serverEntry" + whereClause
  264. err := legacyDb.QueryRow(query, whereParams...).Scan(&count)
  265. if err != nil {
  266. NoticeAlert("CountLegacyServerEntries failed: %s", err)
  267. return 0
  268. }
  269. if region == "" {
  270. region = "(any)"
  271. }
  272. if protocol == "" {
  273. protocol = "(any)"
  274. }
  275. NoticeInfo("servers for region %s and protocol %s: %d",
  276. region, protocol, count)
  277. return count
  278. }