serverEntry.go 40 KB

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