remoteServerList.go 12 KB

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