remoteServerList.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. "compress/zlib"
  22. "encoding/hex"
  23. "errors"
  24. "fmt"
  25. "io/ioutil"
  26. "os"
  27. "time"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  31. )
  32. type RemoteServerListFetcher func(
  33. config *Config, 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. config *Config,
  43. tunnel *Tunnel,
  44. untunneledDialConfig *DialConfig) error {
  45. NoticeInfo("fetching common remote server list")
  46. newETag, err := downloadRemoteServerListFile(
  47. config,
  48. tunnel,
  49. untunneledDialConfig,
  50. config.RemoteServerListUrl,
  51. config.RemoteServerListDownloadFilename)
  52. if err != nil {
  53. return fmt.Errorf("failed to download common remote server list: %s", common.ContextError(err))
  54. }
  55. // When the resource is unchanged, skip.
  56. if newETag == "" {
  57. return nil
  58. }
  59. serverListPayload, err := unpackRemoteServerListFile(config, config.RemoteServerListDownloadFilename)
  60. if err != nil {
  61. return fmt.Errorf("failed to unpack common remote server list: %s", common.ContextError(err))
  62. }
  63. err = storeServerEntries(serverListPayload)
  64. if err != nil {
  65. return fmt.Errorf("failed to store common remote server list: %s", common.ContextError(err))
  66. }
  67. // Now that the server entries are successfully imported, store the response
  68. // ETag so we won't re-download this same data again.
  69. err = SetUrlETag(config.RemoteServerListUrl, newETag)
  70. if err != nil {
  71. NoticeAlert("failed to set ETag for common remote server list: %s", common.ContextError(err))
  72. // This fetch is still reported as a success, even if we can't store the etag
  73. }
  74. return nil
  75. }
  76. // FetchObfuscatedServerLists downloads the obfuscated remote server lists
  77. // from config.ObfuscatedServerListRootURL.
  78. // It first downloads the OSL directory, and then downloads each seeded OSL
  79. // advertised in the directory. All downloads are resumable, ETags are used
  80. // to skip both an unchanged directory or unchanged OSL files, and when an
  81. // individual download fails, the fetch proceeds if it can.
  82. // Authenticated package digital signatures are validated using the
  83. // public key config.RemoteServerListSignaturePublicKey.
  84. // config.ObfuscatedServerListDownloadDirectory is the location to store the
  85. // downloaded files. As downloads are resumed after failure, this directory
  86. // must be unique and persistent.
  87. func FetchObfuscatedServerLists(
  88. config *Config,
  89. tunnel *Tunnel,
  90. untunneledDialConfig *DialConfig) error {
  91. NoticeInfo("fetching obfuscated remote server lists")
  92. downloadFilename := osl.GetOSLDirectoryFilename(config.ObfuscatedServerListDownloadDirectory)
  93. downloadURL := osl.GetOSLDirectoryURL(config.ObfuscatedServerListRootURL)
  94. // failed is set if any operation fails and should trigger a retry. When the OSL directory
  95. // fails to download, any cached directory is used instead; when any single OSL fails
  96. // to download, the overall operation proceeds. So this flag records whether to report
  97. // failure at the end when downloading has proceeded after a failure.
  98. // TODO: should disk-full conditions not trigger retries?
  99. var failed bool
  100. var oslDirectory *osl.Directory
  101. newETag, err := downloadRemoteServerListFile(
  102. config,
  103. tunnel,
  104. untunneledDialConfig,
  105. downloadURL,
  106. downloadFilename)
  107. if err != nil {
  108. failed = true
  109. NoticeAlert("failed to download obfuscated server list directory: %s", common.ContextError(err))
  110. } else if newETag != "" {
  111. fileContent, err := ioutil.ReadFile(downloadFilename)
  112. if err != nil {
  113. failed = true
  114. NoticeAlert("failed to read obfuscated server list directory: %s", common.ContextError(err))
  115. }
  116. var oslDirectoryJSON []byte
  117. if err == nil {
  118. oslDirectory, oslDirectoryJSON, err = osl.UnpackDirectory(
  119. fileContent, config.RemoteServerListSignaturePublicKey)
  120. if err != nil {
  121. failed = true
  122. NoticeAlert("failed to unpack obfuscated server list directory: %s", common.ContextError(err))
  123. }
  124. }
  125. if err == nil {
  126. err = SetKeyValue(DATA_STORE_OSL_DIRECTORY_KEY, string(oslDirectoryJSON))
  127. if err != nil {
  128. failed = true
  129. NoticeAlert("failed to set cached obfuscated server list directory: %s", common.ContextError(err))
  130. }
  131. }
  132. }
  133. if failed || newETag == "" {
  134. // Proceed with the cached OSL directory.
  135. oslDirectoryJSON, err := GetKeyValue(DATA_STORE_OSL_DIRECTORY_KEY)
  136. if err == nil && oslDirectoryJSON == "" {
  137. err = errors.New("not found")
  138. }
  139. if err != nil {
  140. return fmt.Errorf("failed to get cached obfuscated server list directory: %s", common.ContextError(err))
  141. }
  142. oslDirectory, err = osl.LoadDirectory([]byte(oslDirectoryJSON))
  143. if err != nil {
  144. return fmt.Errorf("failed to load obfuscated server list directory: %s", common.ContextError(err))
  145. }
  146. }
  147. // When a new directory is downloaded, validated, and parsed, store the
  148. // response ETag so we won't re-download this same data again.
  149. if !failed && newETag != "" {
  150. err = SetUrlETag(config.RemoteServerListUrl, newETag)
  151. if err != nil {
  152. NoticeAlert("failed to set ETag for obfuscated server list directory: %s", common.ContextError(err))
  153. // This fetch is still reported as a success, even if we can't store the etag
  154. }
  155. }
  156. // Note: we proceed to check individual OSLs even if the direcory is unchanged,
  157. // as the set of local SLOKs may have changed.
  158. lookupSLOKs := func(slokID []byte) []byte {
  159. // Lookup SLOKs in local datastore
  160. key, err := GetSLOK(slokID)
  161. if err != nil {
  162. NoticeAlert("GetSLOK failed: %s", err)
  163. }
  164. return key
  165. }
  166. oslIDs := oslDirectory.GetSeededOSLIDs(
  167. lookupSLOKs,
  168. func(err error) {
  169. NoticeAlert("GetSeededOSLIDs failed: %s", err)
  170. })
  171. for _, oslID := range oslIDs {
  172. downloadFilename := osl.GetOSLFilename(config.ObfuscatedServerListDownloadDirectory, oslID)
  173. downloadURL := osl.GetOSLFileURL(config.ObfuscatedServerListRootURL, oslID)
  174. hexID := hex.EncodeToString(oslID)
  175. // TODO: store ETags in OSL directory to enable skipping requests entirely
  176. newETag, err := downloadRemoteServerListFile(
  177. config,
  178. tunnel,
  179. untunneledDialConfig,
  180. downloadURL,
  181. downloadFilename)
  182. if err != nil {
  183. failed = true
  184. NoticeAlert("failed to download obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  185. continue
  186. }
  187. // When the resource is unchanged, skip.
  188. if newETag == "" {
  189. continue
  190. }
  191. fileContent, err := ioutil.ReadFile(downloadFilename)
  192. if err != nil {
  193. failed = true
  194. NoticeAlert("failed to read obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  195. continue
  196. }
  197. serverListPayload, err := oslDirectory.UnpackOSL(
  198. lookupSLOKs, oslID, fileContent, config.RemoteServerListSignaturePublicKey)
  199. if err != nil {
  200. failed = true
  201. NoticeAlert("failed to unpack obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  202. continue
  203. }
  204. err = storeServerEntries(serverListPayload)
  205. if err != nil {
  206. failed = true
  207. NoticeAlert("failed to store obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  208. continue
  209. }
  210. // Now that the server entries are successfully imported, store the response
  211. // ETag so we won't re-download this same data again.
  212. err = SetUrlETag(config.RemoteServerListUrl, newETag)
  213. if err != nil {
  214. failed = true
  215. NoticeAlert("failed to set Etag for obfuscated server list file (%s): %s", hexID, common.ContextError(err))
  216. continue
  217. // This fetch is still reported as a success, even if we can't store the etag
  218. }
  219. }
  220. if failed {
  221. return errors.New("failed to fetch obfuscated remote server lists")
  222. }
  223. return nil
  224. }
  225. // downloadRemoteServerListFile downloads the source URL to
  226. // the destination file, performing a resumable download. When
  227. // the download completes and the file content has changed, the
  228. // new resource ETag is returned. Otherwise, blank is returned.
  229. // The caller is responsible for calling SetUrlETag once the file
  230. // content has been validated.
  231. func downloadRemoteServerListFile(
  232. config *Config,
  233. tunnel *Tunnel,
  234. untunneledDialConfig *DialConfig,
  235. sourceURL, destinationFilename string) (string, error) {
  236. // MakeDownloadHttpClient will select either a tunneled
  237. // or untunneled configuration.
  238. httpClient, requestURL, err := MakeDownloadHttpClient(
  239. config,
  240. tunnel,
  241. untunneledDialConfig,
  242. sourceURL,
  243. time.Duration(*config.FetchRemoteServerListTimeoutSeconds)*time.Second)
  244. if err != nil {
  245. return "", common.ContextError(err)
  246. }
  247. lastETag, err := GetUrlETag(sourceURL)
  248. if err != nil {
  249. return "", common.ContextError(err)
  250. }
  251. n, responseETag, err := ResumeDownload(
  252. httpClient, requestURL, destinationFilename, lastETag)
  253. NoticeRemoteServerListResourceDownloadedBytes(sourceURL, n)
  254. if err != nil {
  255. return "", common.ContextError(err)
  256. }
  257. if responseETag == lastETag {
  258. return "", nil
  259. }
  260. NoticeRemoteServerListResourceDownloaded(sourceURL)
  261. RecordRemoteServerListStat(sourceURL, responseETag)
  262. return responseETag, nil
  263. }
  264. // unpackRemoteServerListFile reads a file that contains a
  265. // zlib compressed authenticated data package, validates
  266. // the package, and returns the payload.
  267. func unpackRemoteServerListFile(
  268. config *Config, filename string) (string, error) {
  269. fileReader, err := os.Open(filename)
  270. if err != nil {
  271. return "", common.ContextError(err)
  272. }
  273. defer fileReader.Close()
  274. zlibReader, err := zlib.NewReader(fileReader)
  275. if err != nil {
  276. return "", common.ContextError(err)
  277. }
  278. dataPackage, err := ioutil.ReadAll(zlibReader)
  279. zlibReader.Close()
  280. if err != nil {
  281. return "", common.ContextError(err)
  282. }
  283. payload, err := common.ReadAuthenticatedDataPackage(
  284. dataPackage, config.RemoteServerListSignaturePublicKey)
  285. if err != nil {
  286. return "", common.ContextError(err)
  287. }
  288. return payload, nil
  289. }
  290. func storeServerEntries(serverList string) error {
  291. serverEntries, err := DecodeAndValidateServerEntryList(
  292. serverList,
  293. common.GetCurrentTimestamp(),
  294. protocol.SERVER_ENTRY_SOURCE_REMOTE)
  295. if err != nil {
  296. return common.ContextError(err)
  297. }
  298. // TODO: record stats for newly discovered servers
  299. err = StoreServerEntries(serverEntries, true)
  300. if err != nil {
  301. return common.ContextError(err)
  302. }
  303. return nil
  304. }