serverEntry.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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 protocol
  20. import (
  21. "bufio"
  22. "bytes"
  23. "crypto/hmac"
  24. "crypto/rand"
  25. "crypto/sha256"
  26. "encoding/base64"
  27. "encoding/hex"
  28. "encoding/json"
  29. "errors"
  30. "fmt"
  31. "io"
  32. "net"
  33. "strings"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ed25519"
  37. )
  38. // ServerEntry represents a Psiphon server. It contains information
  39. // about how to establish a tunnel connection to the server through
  40. // several protocols. Server entries are JSON records downloaded from
  41. // various sources.
  42. type ServerEntry struct {
  43. Tag string `json:"tag"`
  44. IpAddress string `json:"ipAddress"`
  45. WebServerPort string `json:"webServerPort"` // not an int
  46. WebServerSecret string `json:"webServerSecret"`
  47. WebServerCertificate string `json:"webServerCertificate"`
  48. SshPort int `json:"sshPort"`
  49. SshUsername string `json:"sshUsername"`
  50. SshPassword string `json:"sshPassword"`
  51. SshHostKey string `json:"sshHostKey"`
  52. SshObfuscatedPort int `json:"sshObfuscatedPort"`
  53. SshObfuscatedQUICPort int `json:"sshObfuscatedQUICPort"`
  54. SshObfuscatedTapdancePort int `json:"sshObfuscatedTapdancePort"`
  55. SshObfuscatedKey string `json:"sshObfuscatedKey"`
  56. Capabilities []string `json:"capabilities"`
  57. Region string `json:"region"`
  58. MeekServerPort int `json:"meekServerPort"`
  59. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey"`
  60. MeekObfuscatedKey string `json:"meekObfuscatedKey"`
  61. MeekFrontingHost string `json:"meekFrontingHost"`
  62. MeekFrontingHosts []string `json:"meekFrontingHosts"`
  63. MeekFrontingDomain string `json:"meekFrontingDomain"`
  64. MeekFrontingAddresses []string `json:"meekFrontingAddresses"`
  65. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex"`
  66. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI"`
  67. TacticsRequestPublicKey string `json:"tacticsRequestPublicKey"`
  68. TacticsRequestObfuscatedKey string `json:"tacticsRequestObfuscatedKey"`
  69. MarionetteFormat string `json:"marionetteFormat"`
  70. ConfigurationVersion int `json:"configurationVersion"`
  71. Signature string `json:"signature"`
  72. // These local fields are not expected to be present in downloaded server
  73. // entries. They are added by the client to record and report stats about
  74. // how and when server entries are obtained.
  75. // All local fields should be included the list of fields in RemoveUnsignedFields.
  76. LocalSource string `json:"localSource,omitempty"`
  77. LocalTimestamp string `json:"localTimestamp,omitempty"`
  78. IsLocalDerivedTag bool `json:"isLocalDerivedTag,omitempty"`
  79. }
  80. // ServerEntryFields is an alternate representation of ServerEntry which
  81. // enables future compatibility when unmarshaling and persisting new server
  82. // entries which may contain new, unrecognized fields not in the ServerEntry
  83. // type for a particular client version.
  84. //
  85. // When new JSON server entries with new fields are unmarshaled to ServerEntry
  86. // types, unrecognized fields are discarded. When unmarshaled to
  87. // ServerEntryFields, unrecognized fields are retained and may be persisted
  88. // and available when the client is upgraded and unmarshals to an updated
  89. // ServerEntry type.
  90. type ServerEntryFields map[string]interface{}
  91. // GetServerEntry converts a ServerEntryFields into a ServerEntry.
  92. func (fields ServerEntryFields) GetServerEntry() (*ServerEntry, error) {
  93. marshaledServerEntry, err := json.Marshal(fields)
  94. if err != nil {
  95. return nil, common.ContextError(err)
  96. }
  97. var serverEntry *ServerEntry
  98. err = json.Unmarshal(marshaledServerEntry, &serverEntry)
  99. if err != nil {
  100. return nil, common.ContextError(err)
  101. }
  102. return serverEntry, nil
  103. }
  104. func (fields ServerEntryFields) GetTag() string {
  105. tag, ok := fields["tag"]
  106. if !ok {
  107. return ""
  108. }
  109. tagStr, ok := tag.(string)
  110. if !ok {
  111. return ""
  112. }
  113. return tagStr
  114. }
  115. // SetTag sets a local, derived server entry tag. A tag is an identifier used
  116. // in server entry pruning and potentially other use cases. An explict tag,
  117. // set by the Psiphon Network, may be present in a server entry that is
  118. // imported; otherwise, the client will set a derived tag. The tag should be
  119. // generated using GenerateServerEntryTag. When SetTag finds a explicit tag,
  120. // the new, derived tag is ignored. The isLocalTag local field is set to
  121. // distinguish explict and derived tags and is used in signature verification
  122. // to determine if the tag field is part of the signature.
  123. func (fields ServerEntryFields) SetTag(tag string) {
  124. // Don't replace explicit tag
  125. if tag, ok := fields["tag"]; ok {
  126. tagStr, ok := tag.(string)
  127. if ok && tagStr != "" {
  128. isLocalDerivedTag, ok := fields["isLocalDerivedTag"]
  129. if !ok {
  130. return
  131. }
  132. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  133. if ok && !isLocalDerivedTagBool {
  134. return
  135. }
  136. }
  137. }
  138. fields["tag"] = tag
  139. // Mark this tag as local
  140. fields["isLocalDerivedTag"] = true
  141. }
  142. func (fields ServerEntryFields) GetIPAddress() string {
  143. ipAddress, ok := fields["ipAddress"]
  144. if !ok {
  145. return ""
  146. }
  147. ipAddressStr, ok := ipAddress.(string)
  148. if !ok {
  149. return ""
  150. }
  151. return ipAddressStr
  152. }
  153. func (fields ServerEntryFields) GetWebServerSecret() string {
  154. webServerSecret, ok := fields["webServerSecret"]
  155. if !ok {
  156. return ""
  157. }
  158. webServerSecretStr, ok := webServerSecret.(string)
  159. if !ok {
  160. return ""
  161. }
  162. return webServerSecretStr
  163. }
  164. func (fields ServerEntryFields) GetConfigurationVersion() int {
  165. configurationVersion, ok := fields["configurationVersion"]
  166. if !ok {
  167. return 0
  168. }
  169. configurationVersionInt, ok := configurationVersion.(int)
  170. if !ok {
  171. return 0
  172. }
  173. return configurationVersionInt
  174. }
  175. func (fields ServerEntryFields) GetLocalSource() string {
  176. localSource, ok := fields["localSource"]
  177. if !ok {
  178. return ""
  179. }
  180. localSourceStr, ok := localSource.(string)
  181. if !ok {
  182. return ""
  183. }
  184. return localSourceStr
  185. }
  186. func (fields ServerEntryFields) SetLocalSource(source string) {
  187. fields["localSource"] = source
  188. }
  189. func (fields ServerEntryFields) GetLocalTimestamp() string {
  190. localTimestamp, ok := fields["localTimestamp"]
  191. if !ok {
  192. return ""
  193. }
  194. localTimestampStr, ok := localTimestamp.(string)
  195. if !ok {
  196. return ""
  197. }
  198. return localTimestampStr
  199. }
  200. func (fields ServerEntryFields) SetLocalTimestamp(timestamp string) {
  201. fields["localTimestamp"] = timestamp
  202. }
  203. func (fields ServerEntryFields) HasSignature() bool {
  204. signature, ok := fields["signature"]
  205. if !ok {
  206. return false
  207. }
  208. signatureStr, ok := signature.(string)
  209. if !ok {
  210. return false
  211. }
  212. return signatureStr != ""
  213. }
  214. const signaturePublicKeyDigestSize = 8
  215. // AddSignature signs a server entry and attaches a new field containing the
  216. // signature. Any existing "signature" field will be replaced.
  217. //
  218. // The signature incudes a public key ID that is derived from a digest of the
  219. // public key value. This ID is intended for future use when multiple signing
  220. // keys may be deployed.
  221. func (fields ServerEntryFields) AddSignature(publicKey, privateKey string) error {
  222. // Make a copy so that removing unsigned fields will have no side effects
  223. copyFields := make(ServerEntryFields)
  224. for k, v := range fields {
  225. copyFields[k] = v
  226. }
  227. copyFields.RemoveUnsignedFields()
  228. delete(copyFields, "signature")
  229. marshaledFields, err := json.Marshal(copyFields)
  230. if err != nil {
  231. return common.ContextError(err)
  232. }
  233. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  234. if err != nil {
  235. return common.ContextError(err)
  236. }
  237. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  238. publicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  239. decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
  240. if err != nil {
  241. return common.ContextError(err)
  242. }
  243. signature := ed25519.Sign(decodedPrivateKey, marshaledFields)
  244. fields["signature"] = base64.StdEncoding.EncodeToString(
  245. append(publicKeyID, signature...))
  246. return nil
  247. }
  248. // VerifySignature verifies the signature set by AddSignature.
  249. //
  250. // VerifySignature must be called before using any server entry that is
  251. // imported from an untrusted source, such as client-to-client exchange.
  252. func (fields ServerEntryFields) VerifySignature(publicKey string) error {
  253. // Make a copy so that removing unsigned fields will have no side effects
  254. copyFields := make(ServerEntryFields)
  255. for k, v := range fields {
  256. copyFields[k] = v
  257. }
  258. signatureField, ok := copyFields["signature"]
  259. if !ok {
  260. return common.ContextError(errors.New("missing signature field"))
  261. }
  262. signatureFieldStr, ok := signatureField.(string)
  263. if !ok {
  264. return common.ContextError(errors.New("invalid signature field"))
  265. }
  266. decodedSignatureField, err := base64.StdEncoding.DecodeString(signatureFieldStr)
  267. if err != nil {
  268. return common.ContextError(err)
  269. }
  270. if len(decodedSignatureField) < signaturePublicKeyDigestSize {
  271. return common.ContextError(errors.New("invalid signature field length"))
  272. }
  273. publicKeyID := decodedSignatureField[:signaturePublicKeyDigestSize]
  274. signature := decodedSignatureField[signaturePublicKeyDigestSize:]
  275. if len(signature) != ed25519.SignatureSize {
  276. return common.ContextError(errors.New("invalid signature length"))
  277. }
  278. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  279. if err != nil {
  280. return common.ContextError(err)
  281. }
  282. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  283. expectedPublicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  284. if bytes.Compare(expectedPublicKeyID, publicKeyID) != 0 {
  285. return common.ContextError(errors.New("unexpected public key ID"))
  286. }
  287. copyFields.RemoveUnsignedFields()
  288. delete(copyFields, "signature")
  289. marshaledFields, err := json.Marshal(copyFields)
  290. if err != nil {
  291. return common.ContextError(err)
  292. }
  293. if !ed25519.Verify(decodedPublicKey, marshaledFields, signature) {
  294. return common.ContextError(errors.New("invalid signature"))
  295. }
  296. return nil
  297. }
  298. // RemoveUnsignedFields prepares a server entry for signing or signature
  299. // verification by removing unsigned fields. The JSON marshalling of the
  300. // remaining fields is the data that is signed.
  301. func (fields ServerEntryFields) RemoveUnsignedFields() {
  302. delete(fields, "localSource")
  303. delete(fields, "localTimestamp")
  304. // Only non-local, explicit tags are part of the signature
  305. isLocalDerivedTag, _ := fields["isLocalDerivedTag"]
  306. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  307. if ok && isLocalDerivedTagBool {
  308. delete(fields, "tag")
  309. }
  310. delete(fields, "isLocalDerivedTag")
  311. }
  312. // NewServerEntrySignatureKeyPair creates an ed25519 key pair for use in
  313. // server entry signing and verification.
  314. func NewServerEntrySignatureKeyPair() (string, string, error) {
  315. publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
  316. if err != nil {
  317. return "", "", common.ContextError(err)
  318. }
  319. return base64.StdEncoding.EncodeToString(publicKey),
  320. base64.StdEncoding.EncodeToString(privateKey),
  321. nil
  322. }
  323. // GetCapability returns the server capability corresponding
  324. // to the tunnel protocol.
  325. func GetCapability(protocol string) string {
  326. return strings.TrimSuffix(protocol, "-OSSH")
  327. }
  328. // GetTacticsCapability returns the server tactics capability
  329. // corresponding to the tunnel protocol.
  330. func GetTacticsCapability(protocol string) string {
  331. return GetCapability(protocol) + "-TACTICS"
  332. }
  333. // SupportsProtocol returns true if and only if the ServerEntry has
  334. // the necessary capability to support the specified tunnel protocol.
  335. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  336. requiredCapability := GetCapability(protocol)
  337. return common.Contains(serverEntry.Capabilities, requiredCapability)
  338. }
  339. // GetSupportedProtocols returns a list of tunnel protocols supported
  340. // by the ServerEntry's capabilities.
  341. func (serverEntry *ServerEntry) GetSupportedProtocols(
  342. useUpstreamProxy bool,
  343. limitTunnelProtocols []string,
  344. excludeIntensive bool) []string {
  345. supportedProtocols := make([]string, 0)
  346. for _, protocol := range SupportedTunnelProtocols {
  347. // TODO: Marionette UDP formats are incompatible with
  348. // useUpstreamProxy, but not currently supported
  349. if useUpstreamProxy && TunnelProtocolUsesQUIC(protocol) {
  350. continue
  351. }
  352. if len(limitTunnelProtocols) > 0 {
  353. if !common.Contains(limitTunnelProtocols, protocol) {
  354. continue
  355. }
  356. } else {
  357. if common.Contains(DefaultDisabledTunnelProtocols, protocol) {
  358. continue
  359. }
  360. }
  361. if excludeIntensive && TunnelProtocolIsResourceIntensive(protocol) {
  362. continue
  363. }
  364. if serverEntry.SupportsProtocol(protocol) {
  365. supportedProtocols = append(supportedProtocols, protocol)
  366. }
  367. }
  368. return supportedProtocols
  369. }
  370. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  371. // supported by the ServerEntry's capabilities, that may be used
  372. // for tactics requests.
  373. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  374. supportedProtocols := make([]string, 0)
  375. for _, protocol := range SupportedTunnelProtocols {
  376. if !TunnelProtocolUsesMeek(protocol) {
  377. continue
  378. }
  379. requiredCapability := GetTacticsCapability(protocol)
  380. if !common.Contains(serverEntry.Capabilities, requiredCapability) {
  381. continue
  382. }
  383. supportedProtocols = append(supportedProtocols, protocol)
  384. }
  385. return supportedProtocols
  386. }
  387. // SupportsSSHAPIRequests returns true when the server supports
  388. // SSH API requests.
  389. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  390. return common.Contains(serverEntry.Capabilities, CAPABILITY_SSH_API_REQUESTS)
  391. }
  392. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  393. ports := make([]string, 0)
  394. if common.Contains(serverEntry.Capabilities, CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  395. // Server-side configuration quirk: there's a port forward from
  396. // port 443 to the web server, which we can try, except on servers
  397. // running FRONTED_MEEK, which listens on port 443.
  398. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  399. ports = append(ports, "443")
  400. }
  401. ports = append(ports, serverEntry.WebServerPort)
  402. }
  403. return ports
  404. }
  405. func (serverEntry *ServerEntry) HasSignature() bool {
  406. return serverEntry.Signature != ""
  407. }
  408. // GenerateServerEntryTag creates a server entry tag value that is
  409. // cryptographically derived from the IP address and web server secret in a
  410. // way that is difficult to reverse the IP address value from the tag or
  411. // compute the tag without having the web server secret, a 256-bit random
  412. // value which is unique per server, in addition to the IP address. A database
  413. // consisting only of server entry tags should be resistent to an attack that
  414. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  415. // or some subset of the web server secrets.
  416. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  417. h := hmac.New(sha256.New, []byte(webServerSecret))
  418. h.Write([]byte(ipAddress))
  419. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  420. }
  421. // EncodeServerEntry returns a string containing the encoding of
  422. // a ServerEntry following Psiphon conventions.
  423. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  424. serverEntryContents, err := json.Marshal(serverEntry)
  425. if err != nil {
  426. return "", common.ContextError(err)
  427. }
  428. return hex.EncodeToString([]byte(fmt.Sprintf(
  429. "%s %s %s %s %s",
  430. serverEntry.IpAddress,
  431. serverEntry.WebServerPort,
  432. serverEntry.WebServerSecret,
  433. serverEntry.WebServerCertificate,
  434. serverEntryContents))), nil
  435. }
  436. // DecodeServerEntry extracts a server entry from the encoding
  437. // used by remote server lists and Psiphon server handshake requests.
  438. //
  439. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  440. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  441. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  442. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  443. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  444. // should be a RFC 3339 formatted string. These local fields are stored with the
  445. // server entry and reported to the server as stats (a coarse granularity timestamp
  446. // is reported).
  447. func DecodeServerEntry(
  448. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  449. serverEntry := new(ServerEntry)
  450. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  451. if err != nil {
  452. return nil, common.ContextError(err)
  453. }
  454. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  455. serverEntry.LocalSource = serverEntrySource
  456. serverEntry.LocalTimestamp = timestamp
  457. return serverEntry, nil
  458. }
  459. // DecodeServerEntryFields extracts an encoded server entry into a
  460. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  461. // not in ServerEntry are retained in the ServerEntryFields.
  462. func DecodeServerEntryFields(
  463. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  464. serverEntryFields := make(ServerEntryFields)
  465. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  466. if err != nil {
  467. return nil, common.ContextError(err)
  468. }
  469. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  470. serverEntryFields.SetLocalSource(serverEntrySource)
  471. serverEntryFields.SetLocalTimestamp(timestamp)
  472. return serverEntryFields, nil
  473. }
  474. func decodeServerEntry(
  475. encodedServerEntry, timestamp, serverEntrySource string,
  476. target interface{}) error {
  477. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  478. if err != nil {
  479. return common.ContextError(err)
  480. }
  481. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  482. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  483. if len(fields) != 5 {
  484. return common.ContextError(errors.New("invalid encoded server entry"))
  485. }
  486. err = json.Unmarshal(fields[4], target)
  487. if err != nil {
  488. return common.ContextError(err)
  489. }
  490. return nil
  491. }
  492. // ValidateServerEntryFields checks for malformed server entries.
  493. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  494. // Checks for a valid ipAddress. This is important since the IP
  495. // address is the key used to store/lookup the server entry.
  496. ipAddress := serverEntryFields.GetIPAddress()
  497. if net.ParseIP(ipAddress) == nil {
  498. return common.ContextError(
  499. fmt.Errorf("server entry has invalid ipAddress: %s", ipAddress))
  500. }
  501. // TODO: validate more fields?
  502. // Ensure locally initialized fields have been set.
  503. source := serverEntryFields.GetLocalSource()
  504. if !common.Contains(
  505. SupportedServerEntrySources, source) {
  506. return common.ContextError(
  507. fmt.Errorf("server entry has invalid source: %s", source))
  508. }
  509. timestamp := serverEntryFields.GetLocalTimestamp()
  510. _, err := time.Parse(time.RFC3339, timestamp)
  511. if err != nil {
  512. return common.ContextError(
  513. fmt.Errorf("server entry has invalid timestamp: %s", err))
  514. }
  515. return nil
  516. }
  517. // DecodeServerEntryList extracts server entries from the list encoding
  518. // used by remote server lists and Psiphon server handshake requests.
  519. // Each server entry is validated and invalid entries are skipped.
  520. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  521. func DecodeServerEntryList(
  522. encodedServerEntryList, timestamp,
  523. serverEntrySource string) ([]ServerEntryFields, error) {
  524. serverEntries := make([]ServerEntryFields, 0)
  525. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  526. if len(encodedServerEntry) == 0 {
  527. continue
  528. }
  529. // TODO: skip this entry and continue if can't decode?
  530. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  531. if err != nil {
  532. return nil, common.ContextError(err)
  533. }
  534. if ValidateServerEntryFields(serverEntryFields) != nil {
  535. // Skip this entry and continue with the next one
  536. // TODO: invoke a logging callback
  537. continue
  538. }
  539. serverEntries = append(serverEntries, serverEntryFields)
  540. }
  541. return serverEntries, nil
  542. }
  543. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  544. // operation, loading only one server entry into memory at a time.
  545. type StreamingServerEntryDecoder struct {
  546. scanner *bufio.Scanner
  547. timestamp string
  548. serverEntrySource string
  549. }
  550. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  551. func NewStreamingServerEntryDecoder(
  552. encodedServerEntryListReader io.Reader,
  553. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  554. return &StreamingServerEntryDecoder{
  555. scanner: bufio.NewScanner(encodedServerEntryListReader),
  556. timestamp: timestamp,
  557. serverEntrySource: serverEntrySource,
  558. }
  559. }
  560. // Next reads and decodes, and validates the next server entry from the
  561. // input stream, returning a nil server entry when the stream is complete.
  562. //
  563. // Limitations:
  564. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  565. // the default buffer size which this decoder uses. This is 64K.
  566. // - DecodeServerEntry is called on each encoded server entry line, which
  567. // will allocate memory to hex decode and JSON deserialze the server
  568. // entry. As this is not presently reusing a fixed buffer, each call
  569. // will allocate additional memory; garbage collection is necessary to
  570. // reclaim that memory for reuse for the next server entry.
  571. //
  572. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  573. for {
  574. if !decoder.scanner.Scan() {
  575. return nil, common.ContextError(decoder.scanner.Err())
  576. }
  577. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  578. // TODO: skip this entry and continue if can't decode?
  579. serverEntryFields, err := DecodeServerEntryFields(
  580. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  581. if err != nil {
  582. return nil, common.ContextError(err)
  583. }
  584. if ValidateServerEntryFields(serverEntryFields) != nil {
  585. // Skip this entry and continue with the next one
  586. // TODO: invoke a logging callback
  587. continue
  588. }
  589. return serverEntryFields, nil
  590. }
  591. }