migrateDataStore_windows.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. * Copyright (c) 2015, 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. "fmt"
  24. "os"
  25. "path/filepath"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  28. _ "github.com/mattn/go-sqlite3"
  29. )
  30. var legacyDb *sql.DB
  31. func prepareMigrationEntries(config *Config) []*protocol.ServerEntry {
  32. var migratableServerEntries []*protocol.ServerEntry
  33. // If DATA_STORE_FILENAME does not exist on disk
  34. if _, err := os.Stat(filepath.Join(config.DataStoreDirectory, DATA_STORE_FILENAME)); os.IsNotExist(err) {
  35. // If LEGACY_DATA_STORE_FILENAME exists on disk
  36. if _, err := os.Stat(filepath.Join(config.DataStoreDirectory, LEGACY_DATA_STORE_FILENAME)); err == nil {
  37. legacyDb, err = sql.Open("sqlite3", fmt.Sprintf("file:%s?cache=private&mode=rwc", filepath.Join(config.DataStoreDirectory, LEGACY_DATA_STORE_FILENAME)))
  38. defer legacyDb.Close()
  39. if err != nil {
  40. NoticeAlert("prepareMigrationEntries: sql.Open failed: %s", err)
  41. return nil
  42. }
  43. initialization := "pragma journal_mode=WAL;\n"
  44. _, err = legacyDb.Exec(initialization)
  45. if err != nil {
  46. NoticeAlert("prepareMigrationEntries: sql.DB.Exec failed: %s", err)
  47. return nil
  48. }
  49. iterator, err := newlegacyServerEntryIterator(config)
  50. if err != nil {
  51. NoticeAlert("prepareMigrationEntries: newlegacyServerEntryIterator failed: %s", err)
  52. return nil
  53. }
  54. defer iterator.Close()
  55. for {
  56. serverEntry, err := iterator.Next()
  57. if err != nil {
  58. NoticeAlert("prepareMigrationEntries: legacyServerEntryIterator.Next failed: %s", err)
  59. break
  60. }
  61. if serverEntry == nil {
  62. break
  63. }
  64. migratableServerEntries = append(migratableServerEntries, serverEntry)
  65. }
  66. NoticeInfo("%d server entries prepared for data store migration", len(migratableServerEntries))
  67. }
  68. }
  69. return migratableServerEntries
  70. }
  71. // migrateEntries calls the BoltDB data store method to shuffle
  72. // and store an array of server entries (StoreServerEntries)
  73. // Failing to migrate entries, or delete the legacy file is never fatal
  74. func migrateEntries(config *Config, serverEntries []*protocol.ServerEntry, legacyDataStoreFilename string) {
  75. checkInitDataStore()
  76. err := StoreServerEntries(config, serverEntries, false)
  77. if err != nil {
  78. NoticeAlert("migrateEntries: StoreServerEntries failed: %s", err)
  79. } else {
  80. // Retain server affinity from old datastore by taking the first
  81. // array element (previous top ranked server) and promoting it
  82. // to the top rank before the server selection process begins
  83. //
  84. // TODO: we don't know what server entry filters were in place
  85. // at the time when the legacy datastore was last updated.
  86. // PromoteServerEntry now records the server entry filter in
  87. // order to break server affinity when the filter changes.
  88. // For now, we promote with the current server entry filter
  89. // so the legacy server affinity is retained. This is the same
  90. // logic as was in place before we added recording the server
  91. // entry filter.
  92. err = PromoteServerEntry(config, serverEntries[0].IpAddress)
  93. if err != nil {
  94. NoticeAlert("migrateEntries: PromoteServerEntry failed: %s", err)
  95. }
  96. NoticeAlert("%d server entries successfully migrated to new data store", len(serverEntries))
  97. }
  98. err = os.Remove(legacyDataStoreFilename)
  99. if err != nil {
  100. NoticeAlert("migrateEntries: failed to delete legacy data store file '%s': %s", legacyDataStoreFilename, err)
  101. }
  102. return
  103. }
  104. // This code is copied from the dataStore.go code used to operate the legacy
  105. // SQLite datastore. The word "legacy" was added to all of the method names to avoid
  106. // namespace conflicts with the methods used to operate the BoltDB datastore
  107. // legacyServerEntryIterator is used to iterate over
  108. // stored server entries in rank order.
  109. type legacyServerEntryIterator struct {
  110. shuffleHeadLength int
  111. transaction *sql.Tx
  112. cursor *sql.Rows
  113. }
  114. // newLegacyServerEntryIterator creates a new legacyServerEntryIterator
  115. func newlegacyServerEntryIterator(config *Config) (iterator *legacyServerEntryIterator, err error) {
  116. iterator = &legacyServerEntryIterator{
  117. shuffleHeadLength: config.TunnelPoolSize,
  118. }
  119. err = iterator.Reset()
  120. if err != nil {
  121. return nil, err
  122. }
  123. return iterator, nil
  124. }
  125. // Close cleans up resources associated with a legacyServerEntryIterator.
  126. func (iterator *legacyServerEntryIterator) Close() {
  127. if iterator.cursor != nil {
  128. iterator.cursor.Close()
  129. }
  130. iterator.cursor = nil
  131. if iterator.transaction != nil {
  132. iterator.transaction.Rollback()
  133. }
  134. iterator.transaction = nil
  135. }
  136. // Next returns the next server entry, by rank, for a legacyServerEntryIterator.
  137. // Returns nil with no error when there is no next item.
  138. func (iterator *legacyServerEntryIterator) Next() (serverEntry *protocol.ServerEntry, err error) {
  139. defer func() {
  140. if err != nil {
  141. iterator.Close()
  142. }
  143. }()
  144. if !iterator.cursor.Next() {
  145. err = iterator.cursor.Err()
  146. if err != nil {
  147. return nil, common.ContextError(err)
  148. }
  149. // There is no next item
  150. return nil, nil
  151. }
  152. var data []byte
  153. err = iterator.cursor.Scan(&data)
  154. if err != nil {
  155. return nil, common.ContextError(err)
  156. }
  157. serverEntry = new(protocol.ServerEntry)
  158. err = json.Unmarshal(data, serverEntry)
  159. if err != nil {
  160. return nil, common.ContextError(err)
  161. }
  162. return MakeCompatibleServerEntry(serverEntry), nil
  163. }
  164. // Reset a NewlegacyServerEntryIterator to the start of its cycle. The next
  165. // call to Next will return the first server entry.
  166. func (iterator *legacyServerEntryIterator) Reset() error {
  167. iterator.Close()
  168. transaction, err := legacyDb.Begin()
  169. if err != nil {
  170. return common.ContextError(err)
  171. }
  172. var cursor *sql.Rows
  173. // This query implements the Psiphon server candidate selection
  174. // algorithm: the first TunnelPoolSize server candidates are in rank
  175. // (priority) order, to favor previously successful servers; then the
  176. // remaining long tail is shuffled to raise up less recent candidates.
  177. whereClause, whereParams := makeServerEntryWhereClause(nil)
  178. headLength := iterator.shuffleHeadLength
  179. queryFormat := `
  180. select data from serverEntry %s
  181. order by case
  182. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  183. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  184. end desc;`
  185. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  186. params := make([]interface{}, 0)
  187. params = append(params, whereParams...)
  188. params = append(params, whereParams...)
  189. params = append(params, headLength)
  190. params = append(params, whereParams...)
  191. params = append(params, headLength)
  192. cursor, err = transaction.Query(query, params...)
  193. if err != nil {
  194. transaction.Rollback()
  195. return common.ContextError(err)
  196. }
  197. iterator.transaction = transaction
  198. iterator.cursor = cursor
  199. return nil
  200. }
  201. func makeServerEntryWhereClause(excludeIds []string) (whereClause string, whereParams []interface{}) {
  202. whereClause = ""
  203. whereParams = make([]interface{}, 0)
  204. if len(excludeIds) > 0 {
  205. if len(whereClause) > 0 {
  206. whereClause += " and"
  207. } else {
  208. whereClause += " where"
  209. }
  210. whereClause += " id in ("
  211. for index, id := range excludeIds {
  212. if index > 0 {
  213. whereClause += ", "
  214. }
  215. whereClause += "?"
  216. whereParams = append(whereParams, id)
  217. }
  218. whereClause += ")"
  219. }
  220. return whereClause, whereParams
  221. }