remoteServerList.go 13 KB

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