remoteServerList.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. // If the cached registry is not present, we need to download or resume downloading
  118. // the registry, so clear the ETag to ensure that always happens.
  119. _, err := os.Stat(cachedFilename)
  120. if os.IsNotExist(err) {
  121. SetUrlETag(canonicalURL, "")
  122. }
  123. // failed is set if any operation fails and should trigger a retry. When the OSL registry
  124. // fails to download, any cached registry is used instead; when any single OSL fails
  125. // to download, the overall operation proceeds. So this flag records whether to report
  126. // failure at the end when downloading has proceeded after a failure.
  127. // TODO: should disk-full conditions not trigger retries?
  128. var failed bool
  129. // updateCache is set when modifed registry content is downloaded. Both the cached
  130. // file and the persisted ETag will be updated in this case. The update is deferred
  131. // until after the registry has been authenticated.
  132. updateCache := false
  133. registryFilename := cachedFilename
  134. newETag, err := downloadRemoteServerListFile(
  135. ctx,
  136. config,
  137. tunnel,
  138. untunneledDialConfig,
  139. downloadURL,
  140. canonicalURL,
  141. skipVerify,
  142. "",
  143. downloadFilename)
  144. if err != nil {
  145. failed = true
  146. NoticeAlert("failed to download obfuscated server list registry: %s", common.ContextError(err))
  147. // Proceed with any existing cached OSL registry.
  148. } else if newETag != "" {
  149. updateCache = true
  150. registryFilename = downloadFilename
  151. }
  152. lookupSLOKs := func(slokID []byte) []byte {
  153. // Lookup SLOKs in local datastore
  154. key, err := GetSLOK(slokID)
  155. if err != nil {
  156. NoticeAlert("GetSLOK failed: %s", err)
  157. }
  158. return key
  159. }
  160. registryFile, err := os.Open(registryFilename)
  161. if err != nil {
  162. return fmt.Errorf("failed to read obfuscated server list registry: %s", common.ContextError(err))
  163. }
  164. defer registryFile.Close()
  165. registryStreamer, err := osl.NewRegistryStreamer(
  166. registryFile,
  167. config.RemoteServerListSignaturePublicKey,
  168. lookupSLOKs)
  169. if err != nil {
  170. // TODO: delete file? redownload if corrupt?
  171. return fmt.Errorf("failed to read obfuscated server list registry: %s", common.ContextError(err))
  172. }
  173. // NewRegistryStreamer authenticates the downloaded registry, so now it would be
  174. // ok to update the cache. However, we defer that until after processing so we
  175. // can close the file first before copying it, avoiding related complications on
  176. // platforms such as Windows.
  177. // Note: we proceed to check individual OSLs even if the directory is unchanged,
  178. // as the set of local SLOKs may have changed.
  179. for {
  180. oslFileSpec, err := registryStreamer.Next()
  181. if err != nil {
  182. failed = true
  183. NoticeAlert("failed to stream obfuscated server list registry: %s", common.ContextError(err))
  184. break
  185. }
  186. if oslFileSpec == nil {
  187. break
  188. }
  189. downloadFilename := osl.GetOSLFilename(
  190. config.ObfuscatedServerListDownloadDirectory, oslFileSpec.ID)
  191. downloadURL := osl.GetOSLFileURL(rootURL, oslFileSpec.ID)
  192. canonicalURL := osl.GetOSLFileURL(canonicalRootURL, oslFileSpec.ID)
  193. hexID := hex.EncodeToString(oslFileSpec.ID)
  194. // Note: the MD5 checksum step assumes the remote server list host's ETag uses MD5
  195. // with a hex encoding. If this is not the case, the sourceETag should be left blank.
  196. sourceETag := fmt.Sprintf("\"%s\"", hex.EncodeToString(oslFileSpec.MD5Sum))
  197. newETag, err := downloadRemoteServerListFile(
  198. ctx,
  199. config,
  200. tunnel,
  201. untunneledDialConfig,
  202. downloadURL,
  203. canonicalURL,
  204. skipVerify,
  205. sourceETag,
  206. downloadFilename)
  207. if err != nil {
  208. failed = true
  209. NoticeAlert("failed to download obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  210. continue
  211. }
  212. // When the resource is unchanged, skip.
  213. if newETag == "" {
  214. continue
  215. }
  216. file, err := os.Open(downloadFilename)
  217. if err != nil {
  218. failed = true
  219. NoticeAlert("failed to open obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  220. continue
  221. }
  222. // Note: don't defer file.Close() since we're in a loop
  223. serverListPayloadReader, err := osl.NewOSLReader(
  224. file,
  225. oslFileSpec,
  226. lookupSLOKs,
  227. config.RemoteServerListSignaturePublicKey)
  228. if err != nil {
  229. file.Close()
  230. failed = true
  231. NoticeAlert("failed to read obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  232. continue
  233. }
  234. err = StreamingStoreServerEntries(
  235. protocol.NewStreamingServerEntryDecoder(
  236. serverListPayloadReader,
  237. common.GetCurrentTimestamp(),
  238. protocol.SERVER_ENTRY_SOURCE_OBFUSCATED),
  239. true)
  240. if err != nil {
  241. file.Close()
  242. failed = true
  243. NoticeAlert("failed to store obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  244. continue
  245. }
  246. // Now that the server entries are successfully imported, store the response
  247. // ETag so we won't re-download this same data again.
  248. err = SetUrlETag(canonicalURL, newETag)
  249. if err != nil {
  250. file.Close()
  251. NoticeAlert("failed to set ETag for obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  252. continue
  253. // This fetch is still reported as a success, even if we can't store the ETag
  254. }
  255. file.Close()
  256. // Clear the reference to this OSL file streamer and immediately run
  257. // a garbage collection to reclaim its memory before processing the
  258. // next file.
  259. serverListPayloadReader = nil
  260. defaultGarbageCollection()
  261. }
  262. // Now that a new registry is downloaded, validated, and parsed, store
  263. // the response ETag so we won't re-download this same data again. First
  264. // close the file to avoid complications on platforms such as Windows.
  265. if updateCache {
  266. registryFile.Close()
  267. err := os.Rename(downloadFilename, cachedFilename)
  268. if err != nil {
  269. NoticeAlert("failed to set cached obfuscated server list registry: %s", common.ContextError(err))
  270. // This fetch is still reported as a success, even if we can't update the cache
  271. }
  272. err = SetUrlETag(canonicalURL, newETag)
  273. if err != nil {
  274. NoticeAlert("failed to set ETag for obfuscated server list registry: %s", common.ContextError(err))
  275. // This fetch is still reported as a success, even if we can't store the ETag
  276. }
  277. }
  278. if failed {
  279. return errors.New("one or more operations failed")
  280. }
  281. return nil
  282. }
  283. // downloadRemoteServerListFile downloads the source URL to
  284. // the destination file, performing a resumable download. When
  285. // the download completes and the file content has changed, the
  286. // new resource ETag is returned. Otherwise, blank is returned.
  287. // The caller is responsible for calling SetUrlETag once the file
  288. // content has been validated.
  289. func downloadRemoteServerListFile(
  290. ctx context.Context,
  291. config *Config,
  292. tunnel *Tunnel,
  293. untunneledDialConfig *DialConfig,
  294. sourceURL string,
  295. canonicalURL string,
  296. skipVerify bool,
  297. sourceETag string,
  298. destinationFilename string) (string, error) {
  299. // All download URLs with the same canonicalURL
  300. // must have the same entity and ETag.
  301. lastETag, err := GetUrlETag(canonicalURL)
  302. if err != nil {
  303. return "", common.ContextError(err)
  304. }
  305. // sourceETag, when specified, is prior knowledge of the
  306. // remote ETag that can be used to skip the request entirely.
  307. // This will be set in the case of OSL files, from the MD5Sum
  308. // values stored in the registry.
  309. if lastETag != "" && sourceETag == lastETag {
  310. // TODO: notice?
  311. return "", nil
  312. }
  313. if *config.FetchRemoteServerListTimeoutSeconds > 0 {
  314. var cancelFunc context.CancelFunc
  315. ctx, cancelFunc = context.WithTimeout(
  316. ctx, time.Duration(*config.FetchRemoteServerListTimeoutSeconds)*time.Second)
  317. defer cancelFunc()
  318. }
  319. // MakeDownloadHttpClient will select either a tunneled
  320. // or untunneled configuration.
  321. httpClient, err := MakeDownloadHTTPClient(
  322. ctx,
  323. config,
  324. tunnel,
  325. untunneledDialConfig,
  326. skipVerify)
  327. if err != nil {
  328. return "", common.ContextError(err)
  329. }
  330. n, responseETag, err := ResumeDownload(
  331. ctx,
  332. httpClient,
  333. sourceURL,
  334. MakePsiphonUserAgent(config),
  335. destinationFilename,
  336. lastETag)
  337. NoticeRemoteServerListResourceDownloadedBytes(sourceURL, n)
  338. if err != nil {
  339. return "", common.ContextError(err)
  340. }
  341. if responseETag == lastETag {
  342. return "", nil
  343. }
  344. NoticeRemoteServerListResourceDownloaded(sourceURL)
  345. RecordRemoteServerListStat(sourceURL, responseETag)
  346. return responseETag, nil
  347. }