serverEntry.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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/ed25519"
  24. "crypto/hmac"
  25. "crypto/rand"
  26. "crypto/sha256"
  27. "encoding/base64"
  28. "encoding/hex"
  29. "encoding/json"
  30. "fmt"
  31. "io"
  32. "net"
  33. "regexp"
  34. "strings"
  35. "sync/atomic"
  36. "time"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  39. )
  40. // ServerEntry represents a Psiphon server. It contains information
  41. // about how to establish a tunnel connection to the server through
  42. // several protocols. Server entries are JSON records downloaded from
  43. // various sources.
  44. type ServerEntry struct {
  45. Tag string `json:"tag,omitempty"`
  46. IpAddress string `json:"ipAddress,omitempty"`
  47. WebServerPort string `json:"webServerPort,omitempty"` // not an int
  48. WebServerSecret string `json:"webServerSecret,omitempty"`
  49. WebServerCertificate string `json:"webServerCertificate,omitempty"`
  50. SshPort int `json:"sshPort,omitempty"`
  51. SshUsername string `json:"sshUsername,omitempty"`
  52. SshPassword string `json:"sshPassword,omitempty"`
  53. SshHostKey string `json:"sshHostKey,omitempty"`
  54. SshObfuscatedPort int `json:"sshObfuscatedPort,omitempty"`
  55. SshObfuscatedQUICPort int `json:"sshObfuscatedQUICPort,omitempty"`
  56. LimitQUICVersions []string `json:"limitQUICVersions,omitempty"`
  57. SshObfuscatedTapDancePort int `json:"sshObfuscatedTapdancePort,omitempty"`
  58. SshObfuscatedConjurePort int `json:"sshObfuscatedConjurePort,omitempty"`
  59. SshObfuscatedKey string `json:"sshObfuscatedKey,omitempty"`
  60. Capabilities []string `json:"capabilities,omitempty"`
  61. Region string `json:"region,omitempty"`
  62. ProviderID string `json:"providerID,omitempty"`
  63. FrontingProviderID string `json:"frontingProviderID,omitempty"`
  64. TlsOSSHPort int `json:"tlsOSSHPort,omitempty"`
  65. MeekServerPort int `json:"meekServerPort,omitempty"`
  66. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey,omitempty"`
  67. MeekObfuscatedKey string `json:"meekObfuscatedKey,omitempty"`
  68. MeekFrontingHost string `json:"meekFrontingHost,omitempty"`
  69. MeekFrontingHosts []string `json:"meekFrontingHosts,omitempty"`
  70. MeekFrontingDomain string `json:"meekFrontingDomain,omitempty"`
  71. MeekFrontingAddresses []string `json:"meekFrontingAddresses,omitempty"`
  72. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex,omitempty"`
  73. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI,omitempty"`
  74. TacticsRequestPublicKey string `json:"tacticsRequestPublicKey,omitempty"`
  75. TacticsRequestObfuscatedKey string `json:"tacticsRequestObfuscatedKey,omitempty"`
  76. ConfigurationVersion int `json:"configurationVersion,omitempty"`
  77. Signature string `json:"signature,omitempty"`
  78. DisableHTTPTransforms bool `json:"disableHTTPTransforms,omitempty"`
  79. DisableObfuscatedQUICTransforms bool `json:"disableObfuscatedQUICTransforms,omitempty"`
  80. DisableOSSHTransforms bool `json:"disableOSSHTransforms,omitempty"`
  81. DisableOSSHPrefix bool `json:"disableOSSHPrefix,omitempty"`
  82. InproxySessionPublicKey string `json:"inproxySessionPublicKey,omitempty"`
  83. InproxySessionRootObfuscationSecret string `json:"inproxySessionRootObfuscationSecret,omitempty"`
  84. InproxySSHPort int `json:"inproxySSHPort,omitempty"`
  85. InproxyOSSHPort int `json:"inproxyOSSHPort,omitempty"`
  86. InproxyQUICPort int `json:"inproxyQUICPort,omitempty"`
  87. InproxyMeekPort int `json:"inproxyMeekPort,omitempty"`
  88. InproxyTlsOSSHPort int `json:"inproxyTlsOSSHPort,omitempty"`
  89. // These local fields are not expected to be present in downloaded server
  90. // entries. They are added by the client to record and report stats about
  91. // how and when server entries are obtained.
  92. // All local fields should be included the list of fields in RemoveUnsignedFields.
  93. LocalSource string `json:"localSource,omitempty"`
  94. LocalTimestamp string `json:"localTimestamp,omitempty"`
  95. IsLocalDerivedTag bool `json:"isLocalDerivedTag,omitempty"`
  96. }
  97. // ServerEntryFields is an alternate representation of ServerEntry which
  98. // enables future compatibility when unmarshaling and persisting new server
  99. // entries which may contain new, unrecognized fields not in the ServerEntry
  100. // type for a particular client version.
  101. //
  102. // When new JSON server entries with new fields are unmarshaled to ServerEntry
  103. // types, unrecognized fields are discarded. When unmarshaled to
  104. // ServerEntryFields, unrecognized fields are retained and may be persisted
  105. // and available when the client is upgraded and unmarshals to an updated
  106. // ServerEntry type.
  107. type ServerEntryFields map[string]interface{}
  108. // GetServerEntry converts a ServerEntryFields into a ServerEntry.
  109. func (fields ServerEntryFields) GetServerEntry() (*ServerEntry, error) {
  110. marshaledServerEntry, err := json.Marshal(fields)
  111. if err != nil {
  112. return nil, errors.Trace(err)
  113. }
  114. var serverEntry *ServerEntry
  115. err = json.Unmarshal(marshaledServerEntry, &serverEntry)
  116. if err != nil {
  117. return nil, errors.Trace(err)
  118. }
  119. return serverEntry, nil
  120. }
  121. func (fields ServerEntryFields) GetTag() string {
  122. tag, ok := fields["tag"]
  123. if !ok {
  124. return ""
  125. }
  126. tagStr, ok := tag.(string)
  127. if !ok {
  128. return ""
  129. }
  130. return tagStr
  131. }
  132. // SetTag sets a local, derived server entry tag. A tag is an identifier used
  133. // in server entry pruning and potentially other use cases. An explict tag,
  134. // set by the Psiphon Network, may be present in a server entry that is
  135. // imported; otherwise, the client will set a derived tag. The tag should be
  136. // generated using GenerateServerEntryTag. When SetTag finds a explicit tag,
  137. // the new, derived tag is ignored. The isLocalTag local field is set to
  138. // distinguish explict and derived tags and is used in signature verification
  139. // to determine if the tag field is part of the signature.
  140. func (fields ServerEntryFields) SetTag(tag string) {
  141. // Don't replace explicit tag
  142. if tag, ok := fields["tag"]; ok {
  143. tagStr, ok := tag.(string)
  144. if ok && tagStr != "" {
  145. isLocalDerivedTag, ok := fields["isLocalDerivedTag"]
  146. if !ok {
  147. return
  148. }
  149. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  150. if ok && !isLocalDerivedTagBool {
  151. return
  152. }
  153. }
  154. }
  155. fields["tag"] = tag
  156. // Mark this tag as local
  157. fields["isLocalDerivedTag"] = true
  158. }
  159. func (fields ServerEntryFields) GetDiagnosticID() string {
  160. tag, ok := fields["tag"]
  161. if !ok {
  162. return ""
  163. }
  164. tagStr, ok := tag.(string)
  165. if !ok {
  166. return ""
  167. }
  168. return TagToDiagnosticID(tagStr)
  169. }
  170. func (fields ServerEntryFields) GetIPAddress() string {
  171. ipAddress, ok := fields["ipAddress"]
  172. if !ok {
  173. return ""
  174. }
  175. ipAddressStr, ok := ipAddress.(string)
  176. if !ok {
  177. return ""
  178. }
  179. return ipAddressStr
  180. }
  181. func (fields ServerEntryFields) GetWebServerPort() string {
  182. webServerPort, ok := fields["webServerPort"]
  183. if !ok {
  184. return ""
  185. }
  186. webServerPortStr, ok := webServerPort.(string)
  187. if !ok {
  188. return ""
  189. }
  190. return webServerPortStr
  191. }
  192. func (fields ServerEntryFields) GetWebServerSecret() string {
  193. webServerSecret, ok := fields["webServerSecret"]
  194. if !ok {
  195. return ""
  196. }
  197. webServerSecretStr, ok := webServerSecret.(string)
  198. if !ok {
  199. return ""
  200. }
  201. return webServerSecretStr
  202. }
  203. func (fields ServerEntryFields) GetWebServerCertificate() string {
  204. webServerCertificate, ok := fields["webServerCertificate"]
  205. if !ok {
  206. return ""
  207. }
  208. webServerCertificateStr, ok := webServerCertificate.(string)
  209. if !ok {
  210. return ""
  211. }
  212. return webServerCertificateStr
  213. }
  214. func (fields ServerEntryFields) GetConfigurationVersion() int {
  215. configurationVersion, ok := fields["configurationVersion"]
  216. if !ok {
  217. return 0
  218. }
  219. configurationVersionFloat, ok := configurationVersion.(float64)
  220. if !ok {
  221. return 0
  222. }
  223. return int(configurationVersionFloat)
  224. }
  225. func (fields ServerEntryFields) GetLocalSource() string {
  226. localSource, ok := fields["localSource"]
  227. if !ok {
  228. return ""
  229. }
  230. localSourceStr, ok := localSource.(string)
  231. if !ok {
  232. return ""
  233. }
  234. return localSourceStr
  235. }
  236. func (fields ServerEntryFields) SetLocalSource(source string) {
  237. fields["localSource"] = source
  238. }
  239. func (fields ServerEntryFields) GetLocalTimestamp() string {
  240. localTimestamp, ok := fields["localTimestamp"]
  241. if !ok {
  242. return ""
  243. }
  244. localTimestampStr, ok := localTimestamp.(string)
  245. if !ok {
  246. return ""
  247. }
  248. return localTimestampStr
  249. }
  250. func (fields ServerEntryFields) SetLocalTimestamp(timestamp string) {
  251. fields["localTimestamp"] = timestamp
  252. }
  253. func (fields ServerEntryFields) HasSignature() bool {
  254. signature, ok := fields["signature"]
  255. if !ok {
  256. return false
  257. }
  258. signatureStr, ok := signature.(string)
  259. if !ok {
  260. return false
  261. }
  262. return signatureStr != ""
  263. }
  264. const signaturePublicKeyDigestSize = 8
  265. // AddSignature signs a server entry and attaches a new field containing the
  266. // signature. Any existing "signature" field will be replaced.
  267. //
  268. // The signature incudes a public key ID that is derived from a digest of the
  269. // public key value. This ID is intended for future use when multiple signing
  270. // keys may be deployed.
  271. func (fields ServerEntryFields) AddSignature(publicKey, privateKey string) error {
  272. // Make a copy so that removing unsigned fields will have no side effects
  273. copyFields := make(ServerEntryFields)
  274. for k, v := range fields {
  275. copyFields[k] = v
  276. }
  277. copyFields.RemoveUnsignedFields()
  278. delete(copyFields, "signature")
  279. // Best practise would be to sign the JSON encoded server entry bytes and
  280. // append the signature to those bytes. However, due to backwards
  281. // compatibility requirements, we must retain the outer server entry encoding
  282. // as-is and insert the signature.
  283. //
  284. // Limitation: since the verifyier must remarshal its server entry before
  285. // verifying, the JSON produced there must be a byte-for-byte match to the
  286. // JSON signed here. The precise output of the JSON encoder that is used,
  287. // "encoding/json", with default formatting, as of Go 1.11.5, is therefore
  288. // part of the signature protocol.
  289. //
  290. // TODO: use a standard, canonical encoding, such as JCS:
  291. // https://tools.ietf.org/id/draft-rundgren-json-canonicalization-scheme-05.html
  292. marshaledFields, err := json.Marshal(copyFields)
  293. if err != nil {
  294. return errors.Trace(err)
  295. }
  296. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  297. if err != nil {
  298. return errors.Trace(err)
  299. }
  300. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  301. publicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  302. decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
  303. if err != nil {
  304. return errors.Trace(err)
  305. }
  306. signature := ed25519.Sign(decodedPrivateKey, marshaledFields)
  307. fields["signature"] = base64.StdEncoding.EncodeToString(
  308. append(publicKeyID, signature...))
  309. return nil
  310. }
  311. // VerifySignature verifies the signature set by AddSignature.
  312. //
  313. // VerifySignature must be called before using any server entry that is
  314. // imported from an untrusted source, such as client-to-client exchange.
  315. func (fields ServerEntryFields) VerifySignature(publicKey string) error {
  316. if publicKey == "" {
  317. return errors.TraceNew("missing public key")
  318. }
  319. // Make a copy so that removing unsigned fields will have no side effects
  320. copyFields := make(ServerEntryFields)
  321. for k, v := range fields {
  322. copyFields[k] = v
  323. }
  324. signatureField, ok := copyFields["signature"]
  325. if !ok {
  326. return errors.TraceNew("missing signature field")
  327. }
  328. signatureFieldStr, ok := signatureField.(string)
  329. if !ok {
  330. return errors.TraceNew("invalid signature field")
  331. }
  332. decodedSignatureField, err := base64.StdEncoding.DecodeString(signatureFieldStr)
  333. if err != nil {
  334. return errors.Trace(err)
  335. }
  336. if len(decodedSignatureField) < signaturePublicKeyDigestSize {
  337. return errors.TraceNew("invalid signature field length")
  338. }
  339. publicKeyID := decodedSignatureField[:signaturePublicKeyDigestSize]
  340. signature := decodedSignatureField[signaturePublicKeyDigestSize:]
  341. if len(signature) != ed25519.SignatureSize {
  342. return errors.TraceNew("invalid signature length")
  343. }
  344. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  345. if err != nil {
  346. return errors.Trace(err)
  347. }
  348. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  349. expectedPublicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  350. if !bytes.Equal(expectedPublicKeyID, publicKeyID) {
  351. return errors.TraceNew("unexpected public key ID")
  352. }
  353. copyFields.RemoveUnsignedFields()
  354. delete(copyFields, "signature")
  355. marshaledFields, err := json.Marshal(copyFields)
  356. if err != nil {
  357. return errors.Trace(err)
  358. }
  359. if !ed25519.Verify(decodedPublicKey, marshaledFields, signature) {
  360. return errors.TraceNew("invalid signature")
  361. }
  362. return nil
  363. }
  364. // RemoveUnsignedFields prepares a server entry for signing or signature
  365. // verification by removing unsigned fields. The JSON marshalling of the
  366. // remaining fields is the data that is signed.
  367. func (fields ServerEntryFields) RemoveUnsignedFields() {
  368. delete(fields, "localSource")
  369. delete(fields, "localTimestamp")
  370. // Only non-local, explicit tags are part of the signature
  371. isLocalDerivedTag := fields["isLocalDerivedTag"]
  372. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  373. if ok && isLocalDerivedTagBool {
  374. delete(fields, "tag")
  375. }
  376. delete(fields, "isLocalDerivedTag")
  377. }
  378. // ToSignedFields checks for a signature and calls RemoveUnsignedFields.
  379. func (fields ServerEntryFields) ToSignedFields() error {
  380. if !fields.HasSignature() {
  381. return errors.TraceNew("missing signature field")
  382. }
  383. fields.RemoveUnsignedFields()
  384. return nil
  385. }
  386. // NewServerEntrySignatureKeyPair creates an ed25519 key pair for use in
  387. // server entry signing and verification.
  388. func NewServerEntrySignatureKeyPair() (string, string, error) {
  389. publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
  390. if err != nil {
  391. return "", "", errors.Trace(err)
  392. }
  393. return base64.StdEncoding.EncodeToString(publicKey),
  394. base64.StdEncoding.EncodeToString(privateKey),
  395. nil
  396. }
  397. // GetCapability returns the server capability corresponding
  398. // to the tunnel protocol.
  399. func GetCapability(protocol string) string {
  400. // The "-OSSH" suffix drop is for legacy compatibility. Newer protocols,
  401. // including in-proxy protocols, use the full protocol name as the
  402. // capability. This avoids ambiguities such as in the case
  403. // of "INPROXY-WEBRTC-OSSH", where a truncated "INPROXY-WEBRTC" is
  404. // ambiguous.
  405. if TunnelProtocolUsesInproxy(protocol) {
  406. return protocol
  407. }
  408. return strings.TrimSuffix(protocol, "-OSSH")
  409. }
  410. // GetTacticsCapability returns the server tactics capability
  411. // corresponding to the tunnel protocol.
  412. func GetTacticsCapability(protocol string) string {
  413. return GetCapability(protocol) + "-TACTICS"
  414. }
  415. // hasCapability indicates if the server entry has the specified capability.
  416. //
  417. // Any internal "PASSTHROUGH-v2 or "PASSTHROUGH" component in the server
  418. // entry's capabilities is ignored. These PASSTHROUGH components are used to
  419. // mask protocols which are running the passthrough mechanisms from older
  420. // clients which do not implement the passthrough messages. Older clients
  421. // will treat these capabilities as unknown protocols and skip them.
  422. //
  423. // Any "QUICv1" capability is treated as "QUIC". "QUICv1" is used to mask the
  424. // QUIC-OSSH capability from older clients to ensure that older clients do
  425. // not send gQUIC packets to second generation QUICv1-only QUIC-OSSH servers.
  426. // New clients must check SupportsOnlyQUICv1 before selecting a QUIC version;
  427. // for "QUICv1", this ensures that new clients also do not select gQUIC to
  428. // QUICv1-only servers.
  429. //
  430. // In-proxy tunnel protocols omit the "v1" and "PASSTHROUGH" suffixes. For
  431. // in-proxy QUIC, gQUIC is never used; and for in-proxy HTTPS/TLS, clients
  432. // always apply PASSTHROUGH-v2.
  433. func (serverEntry *ServerEntry) hasCapability(requiredCapability string) bool {
  434. for _, capability := range serverEntry.Capabilities {
  435. originalCapability := capability
  436. capability = strings.ReplaceAll(capability, "-PASSTHROUGH-v2", "")
  437. capability = strings.ReplaceAll(capability, "-PASSTHROUGH", "")
  438. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  439. if capability == quicCapability+"v1" {
  440. capability = quicCapability
  441. }
  442. if capability == requiredCapability {
  443. return true
  444. }
  445. // Special case: some capabilities may additionally support TLS-OSSH.
  446. // This does not apply to in-proxy TLS-OSSH.
  447. if requiredCapability == GetCapability(TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH) &&
  448. capabilitySupportsTLSOSSH(originalCapability) {
  449. return true
  450. }
  451. }
  452. return false
  453. }
  454. // capabilitySupportsTLSOSSH returns true if and only if the given capability
  455. // supports TLS-OSSH in addition to its primary protocol.
  456. func capabilitySupportsTLSOSSH(capability string) bool {
  457. tlsCapabilities := []string{
  458. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS),
  459. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET),
  460. }
  461. for _, tlsCapability := range tlsCapabilities {
  462. // The TLS capability is additionally supported by UNFRONTED-MEEK-HTTPS
  463. // and UNFRONTED-MEEK-SESSION-TICKET capabilities with passthrough.
  464. if capability == tlsCapability+"-PASSTHROUGH-v2" {
  465. return true
  466. }
  467. }
  468. return false
  469. }
  470. // SupportsProtocol returns true if and only if the ServerEntry has
  471. // the necessary capability to support the specified tunnel protocol.
  472. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  473. requiredCapability := GetCapability(protocol)
  474. return serverEntry.hasCapability(requiredCapability)
  475. }
  476. // ProtocolUsesLegacyPassthrough indicates whether the ServerEntry supports
  477. // the specified protocol using legacy passthrough messages.
  478. //
  479. // There is no corresponding check for v2 passthrough, as clients send v2
  480. // passthrough messages unconditionally, by default, for passthrough
  481. // protocols.
  482. func (serverEntry *ServerEntry) ProtocolUsesLegacyPassthrough(protocol string) bool {
  483. legacyCapability := GetCapability(protocol) + "-PASSTHROUGH"
  484. for _, capability := range serverEntry.Capabilities {
  485. if capability == legacyCapability {
  486. return true
  487. }
  488. }
  489. return false
  490. }
  491. // SupportsOnlyQUICv1 indicates that the QUIC-OSSH server supports only QUICv1
  492. // and gQUIC versions should not be selected, as they will fail to connect
  493. // while sending atypical traffic to the server.
  494. //
  495. // SupportsOnlyQUICv1 strictly applies to QUIC-OSSH and not the in-proxy
  496. // variant.
  497. func (serverEntry *ServerEntry) SupportsOnlyQUICv1() bool {
  498. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  499. return common.Contains(serverEntry.Capabilities, quicCapability+"v1") &&
  500. !common.Contains(serverEntry.Capabilities, quicCapability)
  501. }
  502. // ConditionallyEnabledComponents defines an interface which can be queried to
  503. // determine which conditionally compiled protocol components are present.
  504. type ConditionallyEnabledComponents interface {
  505. QUICEnabled() bool
  506. RefractionNetworkingEnabled() bool
  507. }
  508. // TunnelProtocolPortLists is a map from tunnel protocol names (or "All") to a
  509. // list of port number ranges.
  510. type TunnelProtocolPortLists map[string]*common.PortList
  511. // GetSupportedProtocols returns a list of tunnel protocols supported by the
  512. // ServerEntry's capabilities and allowed by various constraints.
  513. func (serverEntry *ServerEntry) GetSupportedProtocols(
  514. conditionallyEnabled ConditionallyEnabledComponents,
  515. useUpstreamProxy bool,
  516. limitTunnelProtocols TunnelProtocols,
  517. limitTunnelDialPortNumbers TunnelProtocolPortLists,
  518. limitQUICVersions QUICVersions,
  519. excludeIntensive bool,
  520. excludeInproxy bool) TunnelProtocols {
  521. supportedProtocols := make(TunnelProtocols, 0)
  522. for _, tunnelProtocol := range SupportedTunnelProtocols {
  523. if useUpstreamProxy && !TunnelProtocolSupportsUpstreamProxy(tunnelProtocol) {
  524. continue
  525. }
  526. if common.Contains(DisabledTunnelProtocols, tunnelProtocol) {
  527. continue
  528. }
  529. if len(limitTunnelProtocols) > 0 {
  530. if !common.Contains(limitTunnelProtocols, tunnelProtocol) {
  531. continue
  532. }
  533. } else {
  534. if common.Contains(DefaultDisabledTunnelProtocols, tunnelProtocol) {
  535. continue
  536. }
  537. }
  538. if excludeIntensive && TunnelProtocolIsResourceIntensive(tunnelProtocol) {
  539. continue
  540. }
  541. // While in-proxy protocols are TunnelProtocolIsResourceIntensive,
  542. // there's an additional use case for excluding in-proxy protocols as
  543. // controlled by InproxyTunnelProtocolSelectionProbability.
  544. if excludeInproxy && TunnelProtocolUsesInproxy(tunnelProtocol) {
  545. continue
  546. }
  547. if (TunnelProtocolUsesQUIC(tunnelProtocol) && !conditionallyEnabled.QUICEnabled()) ||
  548. (TunnelProtocolUsesRefractionNetworking(tunnelProtocol) &&
  549. !conditionallyEnabled.RefractionNetworkingEnabled()) {
  550. continue
  551. }
  552. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  553. continue
  554. }
  555. // If the server is limiting QUIC versions, at least one must be
  556. // supported. And if tactics is also limiting QUIC versions, there
  557. // must be a common version in both limit lists for this server entry
  558. // to support QUIC-OSSH.
  559. //
  560. // Limitation: to avoid additional complexity, we do not consider
  561. // DisableFrontingProviderQUICVersion here, as fronting providers are
  562. // expected to support QUICv1 and gQUIC is expected to become
  563. // obsolete in general.
  564. if TunnelProtocolUsesQUIC(tunnelProtocol) && len(serverEntry.LimitQUICVersions) > 0 {
  565. if !common.ContainsAny(serverEntry.LimitQUICVersions, SupportedQUICVersions) {
  566. continue
  567. }
  568. if len(limitQUICVersions) > 0 &&
  569. !common.ContainsAny(serverEntry.LimitQUICVersions, limitQUICVersions) {
  570. continue
  571. }
  572. }
  573. dialPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  574. if err != nil {
  575. continue
  576. }
  577. if len(limitTunnelDialPortNumbers) > 0 {
  578. if portList, ok := limitTunnelDialPortNumbers[tunnelProtocol]; ok {
  579. if !portList.Lookup(dialPortNumber) {
  580. continue
  581. }
  582. } else if portList, ok := limitTunnelDialPortNumbers[TUNNEL_PROTOCOLS_ALL]; ok {
  583. if !portList.Lookup(dialPortNumber) {
  584. continue
  585. }
  586. }
  587. }
  588. supportedProtocols = append(supportedProtocols, tunnelProtocol)
  589. }
  590. return supportedProtocols
  591. }
  592. var frontedMeekHTTPSDialPortNumber = int32(443)
  593. // SetFrontedMeekHTTPDialPortNumber sets the FRONTED-MEEK-OSSH dial port
  594. // number, which defaults to 443. Overriding the port number enables running
  595. // test servers where binding to port 443 is not possible.
  596. func SetFrontedMeekHTTPDialPortNumber(port int) {
  597. atomic.StoreInt32(&frontedMeekHTTPSDialPortNumber, int32(port))
  598. }
  599. func (serverEntry *ServerEntry) GetDialPortNumber(tunnelProtocol string) (int, error) {
  600. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  601. return 0, errors.TraceNew("protocol not supported")
  602. }
  603. if !TunnelProtocolUsesInproxy(tunnelProtocol) {
  604. switch tunnelProtocol {
  605. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  606. if serverEntry.TlsOSSHPort == 0 {
  607. // Special case: a server which supports UNFRONTED-MEEK-HTTPS-OSSH
  608. // or UNFRONTED-MEEK-SESSION-TICKET-OSSH also supports TLS-OSSH
  609. // over the same port.
  610. return serverEntry.MeekServerPort, nil
  611. }
  612. return serverEntry.TlsOSSHPort, nil
  613. case TUNNEL_PROTOCOL_SSH:
  614. return serverEntry.SshPort, nil
  615. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  616. return serverEntry.SshObfuscatedPort, nil
  617. case TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  618. return serverEntry.SshObfuscatedTapDancePort, nil
  619. case TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH:
  620. return serverEntry.SshObfuscatedConjurePort, nil
  621. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  622. return serverEntry.SshObfuscatedQUICPort, nil
  623. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  624. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  625. return int(atomic.LoadInt32(&frontedMeekHTTPSDialPortNumber)), nil
  626. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  627. return 80, nil
  628. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  629. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  630. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  631. return serverEntry.MeekServerPort, nil
  632. }
  633. } else {
  634. // Distinct dial/listening ports are used for tunnel protocols when
  635. // used as an in-proxy 2nd hop, as the server will require a relayed
  636. // in-proxy broker report for in-proxy 2nd hops.
  637. switch TunnelProtocolMinusInproxy(tunnelProtocol) {
  638. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  639. if serverEntry.InproxyTlsOSSHPort == 0 {
  640. return serverEntry.InproxyMeekPort, nil
  641. }
  642. return serverEntry.InproxyTlsOSSHPort, nil
  643. case TUNNEL_PROTOCOL_SSH:
  644. return serverEntry.InproxySSHPort, nil
  645. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  646. return serverEntry.InproxyOSSHPort, nil
  647. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  648. return serverEntry.InproxyQUICPort, nil
  649. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  650. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  651. return int(atomic.LoadInt32(&frontedMeekHTTPSDialPortNumber)), nil
  652. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  653. return 80, nil
  654. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  655. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  656. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  657. return serverEntry.InproxyMeekPort, nil
  658. }
  659. }
  660. return 0, errors.TraceNew("unknown protocol")
  661. }
  662. // IsValidInproxyDialAddress indicates whether the dial destination
  663. // network/host/port matches the dial parameters for any of the tunnel
  664. // protocols supported by the server entry.
  665. //
  666. // Limitations:
  667. // - TAPDANCE-OSSH and CONJURE-OSSH are not supported.
  668. // - The host header is not considered in the case of fronted protocols.
  669. func (serverEntry *ServerEntry) IsValidInproxyDialAddress(
  670. networkProtocol string, dialHost string, dialPortNumber int) bool {
  671. // The TapDance and Conjure destination addresses are not included
  672. // in the server entry, so TAPDANCE-OSSH and CONJURE-OSSH dial
  673. // destinations cannot be validated for in-proxy use.
  674. for _, tunnelProtocol := range SupportedTunnelProtocols {
  675. if !TunnelProtocolUsesInproxy(tunnelProtocol) {
  676. continue
  677. }
  678. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  679. continue
  680. }
  681. usesTCP := TunnelProtocolUsesTCP(tunnelProtocol)
  682. if (usesTCP && networkProtocol != "tcp") || (!usesTCP && networkProtocol != "udp") {
  683. continue
  684. }
  685. tunnelPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  686. if err != nil || tunnelPortNumber != dialPortNumber {
  687. // Silently fail on error as the server entry should be well-formed.
  688. continue
  689. }
  690. if !TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  691. // For all direct protocols, the destination host must be the
  692. // server IP address.
  693. if serverEntry.IpAddress != dialHost {
  694. continue
  695. }
  696. } else {
  697. // For fronted protocols, the destination host may be domain and
  698. // must match either MeekFrontingAddressesRegex or
  699. // MeekFrontingAddresses. As in psiphon.selectFrontingParameters,
  700. // MeekFrontingAddressesRegex takes precedence when not empty.
  701. //
  702. // As the host header value is not checked here, additional
  703. // measures must be taken to ensure the destination is a Psiphon server.
  704. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  705. re, err := regexp.Compile(serverEntry.MeekFrontingAddressesRegex)
  706. if err != nil {
  707. continue
  708. }
  709. // The entire dialHost string must match the regex.
  710. re.Longest()
  711. match := re.FindString(dialHost)
  712. if match == "" || match != dialHost {
  713. continue
  714. }
  715. } else {
  716. if !common.Contains(serverEntry.MeekFrontingAddresses, dialHost) {
  717. continue
  718. }
  719. }
  720. }
  721. // When all of the checks pass for this protocol, the input is a valid
  722. // dial destination.
  723. return true
  724. }
  725. return false
  726. }
  727. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  728. // supported by the ServerEntry's capabilities, that may be used
  729. // for tactics requests.
  730. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  731. supportedProtocols := make([]string, 0)
  732. for _, protocol := range SupportedTunnelProtocols {
  733. if !TunnelProtocolUsesMeek(protocol) {
  734. continue
  735. }
  736. requiredCapability := GetTacticsCapability(protocol)
  737. if !serverEntry.hasCapability(requiredCapability) {
  738. continue
  739. }
  740. supportedProtocols = append(supportedProtocols, protocol)
  741. }
  742. return supportedProtocols
  743. }
  744. // SupportsSSHAPIRequests returns true when the server supports
  745. // SSH API requests.
  746. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  747. return serverEntry.hasCapability(CAPABILITY_SSH_API_REQUESTS)
  748. }
  749. func (serverEntry *ServerEntry) HasProviderID() bool {
  750. return serverEntry.ProviderID != ""
  751. }
  752. func (serverEntry *ServerEntry) HasSignature() bool {
  753. return serverEntry.Signature != ""
  754. }
  755. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  756. return TagToDiagnosticID(serverEntry.Tag)
  757. }
  758. // GenerateServerEntryTag creates a server entry tag value that is
  759. // cryptographically derived from the IP address and web server secret in a
  760. // way that is difficult to reverse the IP address value from the tag or
  761. // compute the tag without having the web server secret, a 256-bit random
  762. // value which is unique per server, in addition to the IP address. A database
  763. // consisting only of server entry tags should be resistent to an attack that
  764. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  765. // or some subset of the web server secrets.
  766. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  767. h := hmac.New(sha256.New, []byte(webServerSecret))
  768. h.Write([]byte(ipAddress))
  769. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  770. }
  771. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  772. // sufficient to uniquely identify servers in diagnostics, while also being
  773. // more human readable than emitting the full tag. The tag is used as the base
  774. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  775. // output.
  776. func TagToDiagnosticID(tag string) string {
  777. if len(tag) < 8 {
  778. return "<unknown>"
  779. }
  780. return tag[:8]
  781. }
  782. // EncodeServerEntry returns a string containing the encoding of
  783. // a ServerEntry following Psiphon conventions.
  784. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  785. encodedServerEntry, err := encodeServerEntry(
  786. serverEntry.IpAddress,
  787. serverEntry.WebServerPort,
  788. serverEntry.WebServerSecret,
  789. serverEntry.WebServerCertificate,
  790. serverEntry)
  791. if err != nil {
  792. return "", errors.Trace(err)
  793. }
  794. return encodedServerEntry, nil
  795. }
  796. // EncodeServerEntryFields returns a string containing the encoding of
  797. // ServerEntryFields following Psiphon conventions.
  798. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  799. encodedServerEntry, err := encodeServerEntry(
  800. serverEntryFields.GetIPAddress(),
  801. serverEntryFields.GetWebServerPort(),
  802. serverEntryFields.GetWebServerSecret(),
  803. serverEntryFields.GetWebServerCertificate(),
  804. serverEntryFields)
  805. if err != nil {
  806. return "", errors.Trace(err)
  807. }
  808. return encodedServerEntry, nil
  809. }
  810. func encodeServerEntry(
  811. prefixIPAddress string,
  812. prefixWebServerPort string,
  813. prefixWebServerSecret string,
  814. prefixWebServerCertificate string,
  815. serverEntry interface{}) (string, error) {
  816. serverEntryJSON, err := json.Marshal(serverEntry)
  817. if err != nil {
  818. return "", errors.Trace(err)
  819. }
  820. // Legacy clients use a space-delimited fields prefix, and all clients expect
  821. // to at least parse the prefix in order to skip over it.
  822. //
  823. // When the server entry has no web API server certificate, the entire prefix
  824. // can be compacted down to single character placeholders. Clients that can
  825. // use the ssh API always prefer it over the web API and won't use the prefix
  826. // values.
  827. if len(prefixWebServerCertificate) == 0 {
  828. prefixIPAddress = "0"
  829. prefixWebServerPort = "0"
  830. prefixWebServerSecret = "0"
  831. prefixWebServerCertificate = "0"
  832. }
  833. return hex.EncodeToString([]byte(fmt.Sprintf(
  834. "%s %s %s %s %s",
  835. prefixIPAddress,
  836. prefixWebServerPort,
  837. prefixWebServerSecret,
  838. prefixWebServerCertificate,
  839. serverEntryJSON))), nil
  840. }
  841. // DecodeServerEntry extracts a server entry from the encoding
  842. // used by remote server lists and Psiphon server handshake requests.
  843. //
  844. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  845. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  846. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  847. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  848. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  849. // should be a RFC 3339 formatted string. These local fields are stored with the
  850. // server entry and reported to the server as stats (a coarse granularity timestamp
  851. // is reported).
  852. func DecodeServerEntry(
  853. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  854. serverEntry := new(ServerEntry)
  855. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  856. if err != nil {
  857. return nil, errors.Trace(err)
  858. }
  859. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  860. serverEntry.LocalSource = serverEntrySource
  861. serverEntry.LocalTimestamp = timestamp
  862. return serverEntry, nil
  863. }
  864. // DecodeServerEntryFields extracts an encoded server entry into a
  865. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  866. // not in ServerEntry are retained in the ServerEntryFields.
  867. //
  868. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  869. // inputs are non-blank.
  870. func DecodeServerEntryFields(
  871. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  872. serverEntryFields := make(ServerEntryFields)
  873. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  874. if err != nil {
  875. return nil, errors.Trace(err)
  876. }
  877. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  878. if serverEntrySource != "" {
  879. serverEntryFields.SetLocalSource(serverEntrySource)
  880. }
  881. if timestamp != "" {
  882. serverEntryFields.SetLocalTimestamp(timestamp)
  883. }
  884. return serverEntryFields, nil
  885. }
  886. func decodeServerEntry(
  887. encodedServerEntry, timestamp, serverEntrySource string,
  888. target interface{}) error {
  889. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  890. if err != nil {
  891. return errors.Trace(err)
  892. }
  893. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  894. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  895. if len(fields) != 5 {
  896. return errors.TraceNew("invalid encoded server entry")
  897. }
  898. err = json.Unmarshal(fields[4], target)
  899. if err != nil {
  900. return errors.Trace(err)
  901. }
  902. return nil
  903. }
  904. // ValidateServerEntryFields checks for malformed server entries.
  905. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  906. // Checks for a valid ipAddress. This is important since the IP
  907. // address is the key used to store/lookup the server entry.
  908. ipAddress := serverEntryFields.GetIPAddress()
  909. if net.ParseIP(ipAddress) == nil {
  910. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  911. }
  912. // TODO: validate more fields?
  913. // Ensure locally initialized fields have been set.
  914. source := serverEntryFields.GetLocalSource()
  915. if !common.Contains(
  916. SupportedServerEntrySources, source) {
  917. return errors.Tracef("server entry has invalid source: %s", source)
  918. }
  919. timestamp := serverEntryFields.GetLocalTimestamp()
  920. _, err := time.Parse(time.RFC3339, timestamp)
  921. if err != nil {
  922. return errors.Tracef("server entry has invalid timestamp: %s", err)
  923. }
  924. return nil
  925. }
  926. // DecodeServerEntryList extracts server entries from the list encoding
  927. // used by remote server lists and Psiphon server handshake requests.
  928. // Each server entry is validated and invalid entries are skipped.
  929. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  930. func DecodeServerEntryList(
  931. encodedServerEntryList, timestamp,
  932. serverEntrySource string) ([]ServerEntryFields, error) {
  933. serverEntries := make([]ServerEntryFields, 0)
  934. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  935. if len(encodedServerEntry) == 0 {
  936. continue
  937. }
  938. // TODO: skip this entry and continue if can't decode?
  939. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  940. if err != nil {
  941. return nil, errors.Trace(err)
  942. }
  943. if ValidateServerEntryFields(serverEntryFields) != nil {
  944. // Skip this entry and continue with the next one
  945. // TODO: invoke a logging callback
  946. continue
  947. }
  948. serverEntries = append(serverEntries, serverEntryFields)
  949. }
  950. return serverEntries, nil
  951. }
  952. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  953. // operation, loading only one server entry into memory at a time.
  954. type StreamingServerEntryDecoder struct {
  955. scanner *bufio.Scanner
  956. timestamp string
  957. serverEntrySource string
  958. }
  959. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  960. func NewStreamingServerEntryDecoder(
  961. encodedServerEntryListReader io.Reader,
  962. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  963. return &StreamingServerEntryDecoder{
  964. scanner: bufio.NewScanner(encodedServerEntryListReader),
  965. timestamp: timestamp,
  966. serverEntrySource: serverEntrySource,
  967. }
  968. }
  969. // Next reads and decodes, and validates the next server entry from the
  970. // input stream, returning a nil server entry when the stream is complete.
  971. //
  972. // Limitations:
  973. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  974. // the default buffer size which this decoder uses. This is 64K.
  975. // - DecodeServerEntry is called on each encoded server entry line, which
  976. // will allocate memory to hex decode and JSON deserialze the server
  977. // entry. As this is not presently reusing a fixed buffer, each call
  978. // will allocate additional memory; garbage collection is necessary to
  979. // reclaim that memory for reuse for the next server entry.
  980. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  981. for {
  982. if !decoder.scanner.Scan() {
  983. return nil, errors.Trace(decoder.scanner.Err())
  984. }
  985. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  986. // TODO: skip this entry and continue if can't decode?
  987. serverEntryFields, err := DecodeServerEntryFields(
  988. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  989. if err != nil {
  990. return nil, errors.Trace(err)
  991. }
  992. if ValidateServerEntryFields(serverEntryFields) != nil {
  993. // Skip this entry and continue with the next one
  994. // TODO: invoke a logging callback
  995. continue
  996. }
  997. return serverEntryFields, nil
  998. }
  999. }