remoteServerList.go 13 KB

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