remoteServerList.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. "io"
  25. "io/ioutil"
  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. 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. config *Config,
  42. attempt int,
  43. tunnel *Tunnel,
  44. untunneledDialConfig *DialConfig) error {
  45. NoticeInfo("fetching common remote server list")
  46. downloadURL, canonicalURL, skipVerify := selectDownloadURL(attempt, config.RemoteServerListURLs)
  47. newETag, err := downloadRemoteServerListFile(
  48. config,
  49. tunnel,
  50. untunneledDialConfig,
  51. downloadURL,
  52. canonicalURL,
  53. skipVerify,
  54. "",
  55. config.RemoteServerListDownloadFilename)
  56. if err != nil {
  57. return fmt.Errorf("failed to download common remote server list: %s", common.ContextError(err))
  58. }
  59. // When the resource is unchanged, skip.
  60. if newETag == "" {
  61. return nil
  62. }
  63. serverListPayload, err := common.StreamingReadAuthenticatedDataPackage(
  64. config.RemoteServerListDownloadFilename,
  65. config.RemoteServerListSignaturePublicKey)
  66. if err != nil {
  67. return fmt.Errorf("failed to read remote server list: %s", common.ContextError(err))
  68. }
  69. defer serverListPayload.Close()
  70. err = streamingStoreServerEntries(serverListPayload, protocol.SERVER_ENTRY_SOURCE_REMOTE)
  71. if err != nil {
  72. return fmt.Errorf("failed to store common remote server list: %s", common.ContextError(err))
  73. }
  74. // Now that the server entries are successfully imported, store the response
  75. // ETag so we won't re-download this same data again.
  76. err = SetUrlETag(canonicalURL, newETag)
  77. if err != nil {
  78. NoticeAlert("failed to set ETag for common remote server list: %s", common.ContextError(err))
  79. // This fetch is still reported as a success, even if we can't store the etag
  80. }
  81. return nil
  82. }
  83. // FetchObfuscatedServerLists downloads the obfuscated remote server lists
  84. // from config.ObfuscatedServerListRootURL.
  85. // It first downloads the OSL registry, and then downloads each seeded OSL
  86. // advertised in the registry. All downloads are resumable, ETags are used
  87. // to skip both an unchanged registry or unchanged OSL files, and when an
  88. // individual download fails, the fetch proceeds if it can.
  89. // Authenticated package digital signatures are validated using the
  90. // public key config.RemoteServerListSignaturePublicKey.
  91. // config.ObfuscatedServerListDownloadDirectory is the location to store the
  92. // downloaded files. As downloads are resumed after failure, this directory
  93. // must be unique and persistent.
  94. func FetchObfuscatedServerLists(
  95. config *Config,
  96. attempt int,
  97. tunnel *Tunnel,
  98. untunneledDialConfig *DialConfig) error {
  99. NoticeInfo("fetching obfuscated remote server lists")
  100. downloadFilename := osl.GetOSLRegistryFilename(config.ObfuscatedServerListDownloadDirectory)
  101. rootURL, canonicalRootURL, skipVerify := selectDownloadURL(attempt, config.ObfuscatedServerListRootURLs)
  102. downloadURL := osl.GetOSLRegistryURL(rootURL)
  103. canonicalURL := osl.GetOSLRegistryURL(canonicalRootURL)
  104. // failed is set if any operation fails and should trigger a retry. When the OSL registry
  105. // fails to download, any cached registry is used instead; when any single OSL fails
  106. // to download, the overall operation proceeds. So this flag records whether to report
  107. // failure at the end when downloading has proceeded after a failure.
  108. // TODO: should disk-full conditions not trigger retries?
  109. var failed bool
  110. var oslRegistry *osl.Registry
  111. newETag, err := downloadRemoteServerListFile(
  112. config,
  113. tunnel,
  114. untunneledDialConfig,
  115. downloadURL,
  116. canonicalURL,
  117. skipVerify,
  118. "",
  119. downloadFilename)
  120. if err != nil {
  121. failed = true
  122. NoticeAlert("failed to download obfuscated server list registry: %s", common.ContextError(err))
  123. } else if newETag != "" {
  124. fileContent, err := ioutil.ReadFile(downloadFilename)
  125. if err != nil {
  126. failed = true
  127. NoticeAlert("failed to read obfuscated server list registry: %s", common.ContextError(err))
  128. }
  129. var oslRegistryJSON []byte
  130. if err == nil {
  131. oslRegistry, oslRegistryJSON, err = osl.UnpackRegistry(
  132. fileContent, config.RemoteServerListSignaturePublicKey)
  133. if err != nil {
  134. failed = true
  135. NoticeAlert("failed to unpack obfuscated server list registry: %s", common.ContextError(err))
  136. }
  137. }
  138. if err == nil {
  139. err = SetKeyValue(DATA_STORE_OSL_REGISTRY_KEY, string(oslRegistryJSON))
  140. if err != nil {
  141. failed = true
  142. NoticeAlert("failed to set cached obfuscated server list registry: %s", common.ContextError(err))
  143. }
  144. }
  145. }
  146. if failed || newETag == "" {
  147. // Proceed with the cached OSL registry.
  148. oslRegistryJSON, err := GetKeyValue(DATA_STORE_OSL_REGISTRY_KEY)
  149. if err == nil && oslRegistryJSON == "" {
  150. err = errors.New("not found")
  151. }
  152. if err != nil {
  153. return fmt.Errorf("failed to get cached obfuscated server list registry: %s", common.ContextError(err))
  154. }
  155. oslRegistry, err = osl.LoadRegistry([]byte(oslRegistryJSON))
  156. if err != nil {
  157. return fmt.Errorf("failed to load obfuscated server list registry: %s", common.ContextError(err))
  158. }
  159. }
  160. // When a new registry is downloaded, validated, and parsed, store the
  161. // response ETag so we won't re-download this same data again.
  162. if !failed && newETag != "" {
  163. err = SetUrlETag(canonicalURL, newETag)
  164. if err != nil {
  165. NoticeAlert("failed to set ETag for obfuscated server list registry: %s", common.ContextError(err))
  166. // This fetch is still reported as a success, even if we can't store the etag
  167. }
  168. }
  169. // Note: we proceed to check individual OSLs even if the direcory is unchanged,
  170. // as the set of local SLOKs may have changed.
  171. lookupSLOKs := func(slokID []byte) []byte {
  172. // Lookup SLOKs in local datastore
  173. key, err := GetSLOK(slokID)
  174. if err != nil {
  175. NoticeAlert("GetSLOK failed: %s", err)
  176. }
  177. return key
  178. }
  179. oslIDs := oslRegistry.GetSeededOSLIDs(
  180. lookupSLOKs,
  181. func(err error) {
  182. NoticeAlert("GetSeededOSLIDs failed: %s", err)
  183. })
  184. for _, oslID := range oslIDs {
  185. downloadFilename := osl.GetOSLFilename(config.ObfuscatedServerListDownloadDirectory, oslID)
  186. downloadURL := osl.GetOSLFileURL(rootURL, oslID)
  187. canonicalURL := osl.GetOSLFileURL(canonicalRootURL, oslID)
  188. hexID := hex.EncodeToString(oslID)
  189. // Note: the MD5 checksum step assumes the remote server list host's ETag uses MD5
  190. // with a hex encoding. If this is not the case, the sourceETag should be left blank.
  191. sourceETag := ""
  192. md5sum, err := oslRegistry.GetOSLMD5Sum(oslID)
  193. if err == nil {
  194. sourceETag = fmt.Sprintf("\"%s\"", hex.EncodeToString(md5sum))
  195. }
  196. // TODO: store ETags in OSL registry to enable skipping requests entirely
  197. newETag, err := downloadRemoteServerListFile(
  198. config,
  199. tunnel,
  200. untunneledDialConfig,
  201. downloadURL,
  202. canonicalURL,
  203. skipVerify,
  204. sourceETag,
  205. downloadFilename)
  206. if err != nil {
  207. failed = true
  208. NoticeAlert("failed to download obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  209. continue
  210. }
  211. // When the resource is unchanged, skip.
  212. if newETag == "" {
  213. continue
  214. }
  215. fileContent, err := ioutil.ReadFile(downloadFilename)
  216. if err != nil {
  217. failed = true
  218. NoticeAlert("failed to read obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  219. continue
  220. }
  221. serverListPayload, err := oslRegistry.UnpackOSL(
  222. lookupSLOKs, oslID, fileContent, config.RemoteServerListSignaturePublicKey)
  223. if err != nil {
  224. failed = true
  225. NoticeAlert("failed to unpack obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  226. continue
  227. }
  228. err = storeServerEntries(serverListPayload, protocol.SERVER_ENTRY_SOURCE_OBFUSCATED)
  229. if err != nil {
  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. failed = true
  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. }
  244. if failed {
  245. return errors.New("one or more operations failed")
  246. }
  247. return nil
  248. }
  249. // downloadRemoteServerListFile downloads the source URL to
  250. // the destination file, performing a resumable download. When
  251. // the download completes and the file content has changed, the
  252. // new resource ETag is returned. Otherwise, blank is returned.
  253. // The caller is responsible for calling SetUrlETag once the file
  254. // content has been validated.
  255. func downloadRemoteServerListFile(
  256. config *Config,
  257. tunnel *Tunnel,
  258. untunneledDialConfig *DialConfig,
  259. sourceURL string,
  260. canonicalURL string,
  261. skipVerify bool,
  262. sourceETag string,
  263. destinationFilename string) (string, error) {
  264. // All download URLs with the same canonicalURL
  265. // must have the same entity and ETag.
  266. lastETag, err := GetUrlETag(canonicalURL)
  267. if err != nil {
  268. return "", common.ContextError(err)
  269. }
  270. // sourceETag, when specified, is prior knowledge of the
  271. // remote ETag that can be used to skip the request entirely.
  272. // This will be set in the case of OSL files, from the MD5Sum
  273. // values stored in the registry.
  274. if lastETag != "" && sourceETag == lastETag {
  275. // TODO: notice?
  276. return "", nil
  277. }
  278. // MakeDownloadHttpClient will select either a tunneled
  279. // or untunneled configuration.
  280. httpClient, requestURL, err := MakeDownloadHttpClient(
  281. config,
  282. tunnel,
  283. untunneledDialConfig,
  284. sourceURL,
  285. skipVerify,
  286. time.Duration(*config.FetchRemoteServerListTimeoutSeconds)*time.Second)
  287. if err != nil {
  288. return "", common.ContextError(err)
  289. }
  290. n, responseETag, err := ResumeDownload(
  291. httpClient,
  292. requestURL,
  293. MakePsiphonUserAgent(config),
  294. destinationFilename,
  295. lastETag)
  296. NoticeRemoteServerListResourceDownloadedBytes(sourceURL, n)
  297. if err != nil {
  298. return "", common.ContextError(err)
  299. }
  300. if responseETag == lastETag {
  301. return "", nil
  302. }
  303. NoticeRemoteServerListResourceDownloaded(sourceURL)
  304. RecordRemoteServerListStat(sourceURL, responseETag)
  305. return responseETag, nil
  306. }
  307. func storeServerEntries(serverList, serverEntrySource string) error {
  308. serverEntries, err := protocol.DecodeServerEntryList(
  309. serverList,
  310. common.GetCurrentTimestamp(),
  311. serverEntrySource)
  312. if err != nil {
  313. return common.ContextError(err)
  314. }
  315. // TODO: record stats for newly discovered servers
  316. err = StoreServerEntries(serverEntries, true)
  317. if err != nil {
  318. return common.ContextError(err)
  319. }
  320. return nil
  321. }
  322. func streamingStoreServerEntries(serverListReader io.Reader, serverEntrySource string) error {
  323. serverEntries := protocol.NewStreamingServerEntryDecoder(
  324. serverListReader,
  325. common.GetCurrentTimestamp(),
  326. serverEntrySource)
  327. // TODO: record stats for newly discovered servers
  328. err := StreamingStoreServerEntries(serverEntries, true)
  329. if err != nil {
  330. return common.ContextError(err)
  331. }
  332. return nil
  333. }