remoteServerList.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. "encoding/hex"
  22. "errors"
  23. "fmt"
  24. "io/ioutil"
  25. "time"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  29. )
  30. type RemoteServerListFetcher func(
  31. config *Config, attempt int, tunnel *Tunnel, untunneledDialConfig *DialConfig) error
  32. // FetchCommonRemoteServerList downloads the common remote server list from
  33. // config.RemoteServerListUrl. It validates its digital signature using the
  34. // public key config.RemoteServerListSignaturePublicKey and parses the
  35. // data field into ServerEntry records.
  36. // config.RemoteServerListDownloadFilename is the location to store the
  37. // download. As the download is resumed after failure, this filename must
  38. // be unique and persistent.
  39. func FetchCommonRemoteServerList(
  40. config *Config,
  41. attempt int,
  42. tunnel *Tunnel,
  43. untunneledDialConfig *DialConfig) error {
  44. NoticeInfo("fetching common remote server list")
  45. downloadURL, canonicalURL, skipVerify := selectDownloadURL(attempt, config.RemoteServerListURLs)
  46. newETag, err := downloadRemoteServerListFile(
  47. config,
  48. tunnel,
  49. untunneledDialConfig,
  50. downloadURL,
  51. canonicalURL,
  52. skipVerify,
  53. "",
  54. config.RemoteServerListDownloadFilename)
  55. if err != nil {
  56. return fmt.Errorf("failed to download common remote server list: %s", common.ContextError(err))
  57. }
  58. // When the resource is unchanged, skip.
  59. if newETag == "" {
  60. return nil
  61. }
  62. serverListPayload, err := common.StreamingReadAuthenticatedDataPackage(
  63. config.RemoteServerListDownloadFilename,
  64. config.RemoteServerListSignaturePublicKey)
  65. if err != nil {
  66. return fmt.Errorf("failed to read remote server list: %s", common.ContextError(err))
  67. }
  68. defer serverListPayload.Close()
  69. err = StreamingStoreServerEntries(
  70. protocol.NewStreamingServerEntryDecoder(
  71. serverListPayload,
  72. common.GetCurrentTimestamp(),
  73. protocol.SERVER_ENTRY_SOURCE_REMOTE),
  74. true)
  75. if err != nil {
  76. return fmt.Errorf("failed to store common remote server list: %s", common.ContextError(err))
  77. }
  78. // Now that the server entries are successfully imported, store the response
  79. // ETag so we won't re-download this same data again.
  80. err = SetUrlETag(canonicalURL, newETag)
  81. if err != nil {
  82. NoticeAlert("failed to set ETag for common remote server list: %s", common.ContextError(err))
  83. // This fetch is still reported as a success, even if we can't store the etag
  84. }
  85. return nil
  86. }
  87. // FetchObfuscatedServerLists downloads the obfuscated remote server lists
  88. // from config.ObfuscatedServerListRootURL.
  89. // It first downloads the OSL registry, and then downloads each seeded OSL
  90. // advertised in the registry. All downloads are resumable, ETags are used
  91. // to skip both an unchanged registry or unchanged OSL files, and when an
  92. // individual download fails, the fetch proceeds if it can.
  93. // Authenticated package digital signatures are validated using the
  94. // public key config.RemoteServerListSignaturePublicKey.
  95. // config.ObfuscatedServerListDownloadDirectory is the location to store the
  96. // downloaded files. As downloads are resumed after failure, this directory
  97. // must be unique and persistent.
  98. func FetchObfuscatedServerLists(
  99. config *Config,
  100. attempt int,
  101. tunnel *Tunnel,
  102. untunneledDialConfig *DialConfig) error {
  103. NoticeInfo("fetching obfuscated remote server lists")
  104. downloadFilename := osl.GetOSLRegistryFilename(config.ObfuscatedServerListDownloadDirectory)
  105. rootURL, canonicalRootURL, skipVerify := selectDownloadURL(attempt, config.ObfuscatedServerListRootURLs)
  106. downloadURL := osl.GetOSLRegistryURL(rootURL)
  107. canonicalURL := osl.GetOSLRegistryURL(canonicalRootURL)
  108. // failed is set if any operation fails and should trigger a retry. When the OSL registry
  109. // fails to download, any cached registry is used instead; when any single OSL fails
  110. // to download, the overall operation proceeds. So this flag records whether to report
  111. // failure at the end when downloading has proceeded after a failure.
  112. // TODO: should disk-full conditions not trigger retries?
  113. var failed bool
  114. var oslRegistry *osl.Registry
  115. newETag, err := downloadRemoteServerListFile(
  116. config,
  117. tunnel,
  118. untunneledDialConfig,
  119. downloadURL,
  120. canonicalURL,
  121. skipVerify,
  122. "",
  123. downloadFilename)
  124. if err != nil {
  125. failed = true
  126. NoticeAlert("failed to download obfuscated server list registry: %s", common.ContextError(err))
  127. } else if newETag != "" {
  128. fileContent, err := ioutil.ReadFile(downloadFilename)
  129. if err != nil {
  130. failed = true
  131. NoticeAlert("failed to read obfuscated server list registry: %s", common.ContextError(err))
  132. }
  133. var oslRegistryJSON []byte
  134. if err == nil {
  135. oslRegistry, oslRegistryJSON, err = osl.UnpackRegistry(
  136. fileContent, config.RemoteServerListSignaturePublicKey)
  137. if err != nil {
  138. failed = true
  139. NoticeAlert("failed to unpack obfuscated server list registry: %s", common.ContextError(err))
  140. }
  141. }
  142. if err == nil {
  143. err = SetKeyValue(DATA_STORE_OSL_REGISTRY_KEY, string(oslRegistryJSON))
  144. if err != nil {
  145. failed = true
  146. NoticeAlert("failed to set cached obfuscated server list registry: %s", common.ContextError(err))
  147. }
  148. }
  149. }
  150. if failed || newETag == "" {
  151. // Proceed with the cached OSL registry.
  152. oslRegistryJSON, err := GetKeyValue(DATA_STORE_OSL_REGISTRY_KEY)
  153. if err == nil && oslRegistryJSON == "" {
  154. err = errors.New("not found")
  155. }
  156. if err != nil {
  157. return fmt.Errorf("failed to get cached obfuscated server list registry: %s", common.ContextError(err))
  158. }
  159. oslRegistry, err = osl.LoadRegistry([]byte(oslRegistryJSON))
  160. if err != nil {
  161. return fmt.Errorf("failed to load obfuscated server list registry: %s", common.ContextError(err))
  162. }
  163. }
  164. // When a new registry is downloaded, validated, and parsed, store the
  165. // response ETag so we won't re-download this same data again.
  166. if !failed && newETag != "" {
  167. err = SetUrlETag(canonicalURL, newETag)
  168. if err != nil {
  169. NoticeAlert("failed to set ETag for obfuscated server list registry: %s", common.ContextError(err))
  170. // This fetch is still reported as a success, even if we can't store the etag
  171. }
  172. }
  173. // Note: we proceed to check individual OSLs even if the direcory is unchanged,
  174. // as the set of local SLOKs may have changed.
  175. lookupSLOKs := func(slokID []byte) []byte {
  176. // Lookup SLOKs in local datastore
  177. key, err := GetSLOK(slokID)
  178. if err != nil {
  179. NoticeAlert("GetSLOK failed: %s", err)
  180. }
  181. return key
  182. }
  183. oslIDs := oslRegistry.GetSeededOSLIDs(
  184. lookupSLOKs,
  185. func(err error) {
  186. NoticeAlert("GetSeededOSLIDs failed: %s", err)
  187. })
  188. for _, oslID := range oslIDs {
  189. downloadFilename := osl.GetOSLFilename(config.ObfuscatedServerListDownloadDirectory, oslID)
  190. downloadURL := osl.GetOSLFileURL(rootURL, oslID)
  191. canonicalURL := osl.GetOSLFileURL(canonicalRootURL, oslID)
  192. hexID := hex.EncodeToString(oslID)
  193. // Note: the MD5 checksum step assumes the remote server list host's ETag uses MD5
  194. // with a hex encoding. If this is not the case, the sourceETag should be left blank.
  195. sourceETag := ""
  196. md5sum, err := oslRegistry.GetOSLMD5Sum(oslID)
  197. if err == nil {
  198. sourceETag = fmt.Sprintf("\"%s\"", hex.EncodeToString(md5sum))
  199. }
  200. // TODO: store ETags in OSL registry to enable skipping requests entirely
  201. newETag, err := downloadRemoteServerListFile(
  202. config,
  203. tunnel,
  204. untunneledDialConfig,
  205. downloadURL,
  206. canonicalURL,
  207. skipVerify,
  208. sourceETag,
  209. downloadFilename)
  210. if err != nil {
  211. failed = true
  212. NoticeAlert("failed to download obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  213. continue
  214. }
  215. // When the resource is unchanged, skip.
  216. if newETag == "" {
  217. continue
  218. }
  219. fileContent, err := ioutil.ReadFile(downloadFilename)
  220. if err != nil {
  221. failed = true
  222. NoticeAlert("failed to read obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  223. continue
  224. }
  225. serverListPayload, err := oslRegistry.UnpackOSL(
  226. lookupSLOKs, oslID, fileContent, config.RemoteServerListSignaturePublicKey)
  227. if err != nil {
  228. failed = true
  229. NoticeAlert("failed to unpack obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  230. continue
  231. }
  232. err = storeServerEntries(serverListPayload, protocol.SERVER_ENTRY_SOURCE_OBFUSCATED)
  233. if err != nil {
  234. failed = true
  235. NoticeAlert("failed to store obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  236. continue
  237. }
  238. // Now that the server entries are successfully imported, store the response
  239. // ETag so we won't re-download this same data again.
  240. err = SetUrlETag(canonicalURL, newETag)
  241. if err != nil {
  242. failed = true
  243. NoticeAlert("failed to set Etag for obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  244. continue
  245. // This fetch is still reported as a success, even if we can't store the etag
  246. }
  247. }
  248. if failed {
  249. return errors.New("one or more operations failed")
  250. }
  251. return nil
  252. }
  253. // downloadRemoteServerListFile downloads the source URL to
  254. // the destination file, performing a resumable download. When
  255. // the download completes and the file content has changed, the
  256. // new resource ETag is returned. Otherwise, blank is returned.
  257. // The caller is responsible for calling SetUrlETag once the file
  258. // content has been validated.
  259. func downloadRemoteServerListFile(
  260. config *Config,
  261. tunnel *Tunnel,
  262. untunneledDialConfig *DialConfig,
  263. sourceURL string,
  264. canonicalURL string,
  265. skipVerify bool,
  266. sourceETag string,
  267. destinationFilename string) (string, error) {
  268. // All download URLs with the same canonicalURL
  269. // must have the same entity and ETag.
  270. lastETag, err := GetUrlETag(canonicalURL)
  271. if err != nil {
  272. return "", common.ContextError(err)
  273. }
  274. // sourceETag, when specified, is prior knowledge of the
  275. // remote ETag that can be used to skip the request entirely.
  276. // This will be set in the case of OSL files, from the MD5Sum
  277. // values stored in the registry.
  278. if lastETag != "" && sourceETag == lastETag {
  279. // TODO: notice?
  280. return "", nil
  281. }
  282. // MakeDownloadHttpClient will select either a tunneled
  283. // or untunneled configuration.
  284. httpClient, requestURL, err := MakeDownloadHttpClient(
  285. config,
  286. tunnel,
  287. untunneledDialConfig,
  288. sourceURL,
  289. skipVerify,
  290. time.Duration(*config.FetchRemoteServerListTimeoutSeconds)*time.Second)
  291. if err != nil {
  292. return "", common.ContextError(err)
  293. }
  294. n, responseETag, err := ResumeDownload(
  295. httpClient,
  296. requestURL,
  297. MakePsiphonUserAgent(config),
  298. destinationFilename,
  299. lastETag)
  300. NoticeRemoteServerListResourceDownloadedBytes(sourceURL, n)
  301. if err != nil {
  302. return "", common.ContextError(err)
  303. }
  304. if responseETag == lastETag {
  305. return "", nil
  306. }
  307. NoticeRemoteServerListResourceDownloaded(sourceURL)
  308. RecordRemoteServerListStat(sourceURL, responseETag)
  309. return responseETag, nil
  310. }
  311. func storeServerEntries(serverList, serverEntrySource string) error {
  312. serverEntries, err := protocol.DecodeServerEntryList(
  313. serverList,
  314. common.GetCurrentTimestamp(),
  315. serverEntrySource)
  316. if err != nil {
  317. return common.ContextError(err)
  318. }
  319. err = StoreServerEntries(serverEntries, true)
  320. if err != nil {
  321. return common.ContextError(err)
  322. }
  323. return nil
  324. }