remoteServerList.go 12 KB

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