migrateDataStore_windows.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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-Inc/go-sqlite3"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  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(serverEntries []*protocol.ServerEntry, legacyDataStoreFilename string) {
  75. checkInitDataStore()
  76. err := StoreServerEntries(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. err = PromoteServerEntry(serverEntries[0].IpAddress)
  84. if err != nil {
  85. NoticeAlert("migrateEntries: PromoteServerEntry failed: %s", err)
  86. }
  87. NoticeAlert("%d server entries successfully migrated to new data store", len(serverEntries))
  88. }
  89. err = os.Remove(legacyDataStoreFilename)
  90. if err != nil {
  91. NoticeAlert("migrateEntries: failed to delete legacy data store file '%s': %s", legacyDataStoreFilename, err)
  92. }
  93. return
  94. }
  95. // This code is copied from the dataStore.go code used to operate the legacy
  96. // SQLite datastore. The word "legacy" was added to all of the method names to avoid
  97. // namespace conflicts with the methods used to operate the BoltDB datastore
  98. // legacyServerEntryIterator is used to iterate over
  99. // stored server entries in rank order.
  100. type legacyServerEntryIterator struct {
  101. shuffleHeadLength int
  102. transaction *sql.Tx
  103. cursor *sql.Rows
  104. }
  105. // newLegacyServerEntryIterator creates a new legacyServerEntryIterator
  106. func newlegacyServerEntryIterator(config *Config) (iterator *legacyServerEntryIterator, err error) {
  107. iterator = &legacyServerEntryIterator{
  108. shuffleHeadLength: config.TunnelPoolSize,
  109. }
  110. err = iterator.Reset()
  111. if err != nil {
  112. return nil, err
  113. }
  114. return iterator, nil
  115. }
  116. // Close cleans up resources associated with a legacyServerEntryIterator.
  117. func (iterator *legacyServerEntryIterator) Close() {
  118. if iterator.cursor != nil {
  119. iterator.cursor.Close()
  120. }
  121. iterator.cursor = nil
  122. if iterator.transaction != nil {
  123. iterator.transaction.Rollback()
  124. }
  125. iterator.transaction = nil
  126. }
  127. // Next returns the next server entry, by rank, for a legacyServerEntryIterator.
  128. // Returns nil with no error when there is no next item.
  129. func (iterator *legacyServerEntryIterator) Next() (serverEntry *protocol.ServerEntry, err error) {
  130. defer func() {
  131. if err != nil {
  132. iterator.Close()
  133. }
  134. }()
  135. if !iterator.cursor.Next() {
  136. err = iterator.cursor.Err()
  137. if err != nil {
  138. return nil, common.ContextError(err)
  139. }
  140. // There is no next item
  141. return nil, nil
  142. }
  143. var data []byte
  144. err = iterator.cursor.Scan(&data)
  145. if err != nil {
  146. return nil, common.ContextError(err)
  147. }
  148. serverEntry = new(protocol.ServerEntry)
  149. err = json.Unmarshal(data, serverEntry)
  150. if err != nil {
  151. return nil, common.ContextError(err)
  152. }
  153. return MakeCompatibleServerEntry(serverEntry), nil
  154. }
  155. // Reset a NewlegacyServerEntryIterator to the start of its cycle. The next
  156. // call to Next will return the first server entry.
  157. func (iterator *legacyServerEntryIterator) Reset() error {
  158. iterator.Close()
  159. transaction, err := legacyDb.Begin()
  160. if err != nil {
  161. return common.ContextError(err)
  162. }
  163. var cursor *sql.Rows
  164. // This query implements the Psiphon server candidate selection
  165. // algorithm: the first TunnelPoolSize server candidates are in rank
  166. // (priority) order, to favor previously successful servers; then the
  167. // remaining long tail is shuffled to raise up less recent candidates.
  168. whereClause, whereParams := makeServerEntryWhereClause(nil)
  169. headLength := iterator.shuffleHeadLength
  170. queryFormat := `
  171. select data from serverEntry %s
  172. order by case
  173. when rank > coalesce((select rank from serverEntry %s order by rank desc limit ?, 1), -1) then rank
  174. else abs(random())%%((select rank from serverEntry %s order by rank desc limit ?, 1))
  175. end desc;`
  176. query := fmt.Sprintf(queryFormat, whereClause, whereClause, whereClause)
  177. params := make([]interface{}, 0)
  178. params = append(params, whereParams...)
  179. params = append(params, whereParams...)
  180. params = append(params, headLength)
  181. params = append(params, whereParams...)
  182. params = append(params, headLength)
  183. cursor, err = transaction.Query(query, params...)
  184. if err != nil {
  185. transaction.Rollback()
  186. return common.ContextError(err)
  187. }
  188. iterator.transaction = transaction
  189. iterator.cursor = cursor
  190. return nil
  191. }
  192. func makeServerEntryWhereClause(excludeIds []string) (whereClause string, whereParams []interface{}) {
  193. whereClause = ""
  194. whereParams = make([]interface{}, 0)
  195. if len(excludeIds) > 0 {
  196. if len(whereClause) > 0 {
  197. whereClause += " and"
  198. } else {
  199. whereClause += " where"
  200. }
  201. whereClause += " id in ("
  202. for index, id := range excludeIds {
  203. if index > 0 {
  204. whereClause += ", "
  205. }
  206. whereClause += "?"
  207. whereParams = append(whereParams, id)
  208. }
  209. whereClause += ")"
  210. }
  211. return whereClause, whereParams
  212. }