meek.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "bytes"
  22. "context"
  23. "crypto/rand"
  24. "crypto/tls"
  25. "encoding/base64"
  26. "encoding/hex"
  27. "encoding/json"
  28. std_errors "errors"
  29. "hash/crc64"
  30. "io"
  31. "net"
  32. "net/http"
  33. "runtime"
  34. "strconv"
  35. "strings"
  36. "sync"
  37. "sync/atomic"
  38. "time"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/monotime"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  46. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  47. tris "github.com/Psiphon-Labs/tls-tris"
  48. lrucache "github.com/cognusion/go-cache-lru"
  49. "github.com/juju/ratelimit"
  50. "golang.org/x/crypto/nacl/box"
  51. )
  52. // MeekServer is based on meek-server.go from Tor and Psiphon:
  53. //
  54. // https://gitweb.torproject.org/pluggable-transports/meek.git/blob/HEAD:/meek-client/meek-client.go
  55. // CC0 1.0 Universal
  56. //
  57. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/go/meek-client/meek-client.go
  58. const (
  59. // Protocol version 1 clients can handle arbitrary length response bodies. Older clients
  60. // report no version number and expect at most 64K response bodies.
  61. MEEK_PROTOCOL_VERSION_1 = 1
  62. // Protocol version 2 clients initiate a session by sending an encrypted and obfuscated meek
  63. // cookie with their initial HTTP request. Connection information is contained within the
  64. // encrypted cookie payload. The server inspects the cookie and establishes a new session and
  65. // returns a new random session ID back to client via Set-Cookie header. The client uses this
  66. // session ID on all subsequent requests for the remainder of the session.
  67. MEEK_PROTOCOL_VERSION_2 = 2
  68. // Protocol version 3 clients include resiliency enhancements and will add a Range header
  69. // when retrying a request for a partially downloaded response payload.
  70. MEEK_PROTOCOL_VERSION_3 = 3
  71. MEEK_MAX_REQUEST_PAYLOAD_LENGTH = 65536
  72. MEEK_MIN_SESSION_ID_LENGTH = 8
  73. MEEK_MAX_SESSION_ID_LENGTH = 20
  74. MEEK_DEFAULT_TURN_AROUND_TIMEOUT = 10 * time.Millisecond
  75. MEEK_DEFAULT_EXTENDED_TURN_AROUND_TIMEOUT = 100 * time.Millisecond
  76. MEEK_DEFAULT_SKIP_EXTENDED_TURN_AROUND_THRESHOLD = 8192
  77. MEEK_DEFAULT_MAX_SESSION_STALENESS = 45 * time.Second
  78. MEEK_DEFAULT_HTTP_CLIENT_IO_TIMEOUT = 45 * time.Second
  79. MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH = 65536
  80. MEEK_DEFAULT_POOL_BUFFER_LENGTH = 65536
  81. MEEK_DEFAULT_POOL_BUFFER_COUNT = 2048
  82. )
  83. // MeekServer implements the meek protocol, which tunnels TCP traffic (in the case of Psiphon,
  84. // Obfuscated SSH traffic) over HTTP. Meek may be fronted (through a CDN) or direct and may be
  85. // HTTP or HTTPS.
  86. //
  87. // Upstream traffic arrives in HTTP request bodies and downstream traffic is sent in response
  88. // bodies. The sequence of traffic for a given flow is associated using a session ID that's
  89. // set as a HTTP cookie for the client to submit with each request.
  90. //
  91. // MeekServer hooks into TunnelServer via the net.Conn interface by transforming the
  92. // HTTP payload traffic for a given session into net.Conn conforming Read()s and Write()s via
  93. // the meekConn struct.
  94. type MeekServer struct {
  95. support *SupportServices
  96. listener net.Listener
  97. listenerTunnelProtocol string
  98. listenerPort int
  99. passthroughAddress string
  100. turnAroundTimeout time.Duration
  101. extendedTurnAroundTimeout time.Duration
  102. skipExtendedTurnAroundThreshold int
  103. maxSessionStaleness time.Duration
  104. httpClientIOTimeout time.Duration
  105. tlsConfig *tris.Config
  106. obfuscatorSeedHistory *obfuscator.SeedHistory
  107. clientHandler func(clientTunnelProtocol string, clientConn net.Conn)
  108. openConns *common.Conns
  109. stopBroadcast <-chan struct{}
  110. sessionsLock sync.RWMutex
  111. sessions map[string]*meekSession
  112. checksumTable *crc64.Table
  113. bufferPool *CachedResponseBufferPool
  114. rateLimitLock sync.Mutex
  115. rateLimitHistory *lrucache.Cache
  116. rateLimitCount int
  117. rateLimitSignalGC chan struct{}
  118. }
  119. // NewMeekServer initializes a new meek server.
  120. func NewMeekServer(
  121. support *SupportServices,
  122. listener net.Listener,
  123. listenerTunnelProtocol string,
  124. listenerPort int,
  125. useTLS, isFronted, useObfuscatedSessionTickets bool,
  126. clientHandler func(clientTunnelProtocol string, clientConn net.Conn),
  127. stopBroadcast <-chan struct{}) (*MeekServer, error) {
  128. passthroughAddress := support.Config.TunnelProtocolPassthroughAddresses[listenerTunnelProtocol]
  129. turnAroundTimeout := MEEK_DEFAULT_TURN_AROUND_TIMEOUT
  130. if support.Config.MeekTurnAroundTimeoutMilliseconds != nil {
  131. turnAroundTimeout = time.Duration(
  132. *support.Config.MeekTurnAroundTimeoutMilliseconds) * time.Millisecond
  133. }
  134. extendedTurnAroundTimeout := MEEK_DEFAULT_EXTENDED_TURN_AROUND_TIMEOUT
  135. if support.Config.MeekExtendedTurnAroundTimeoutMilliseconds != nil {
  136. extendedTurnAroundTimeout = time.Duration(
  137. *support.Config.MeekExtendedTurnAroundTimeoutMilliseconds) * time.Millisecond
  138. }
  139. skipExtendedTurnAroundThreshold := MEEK_DEFAULT_SKIP_EXTENDED_TURN_AROUND_THRESHOLD
  140. if support.Config.MeekSkipExtendedTurnAroundThresholdBytes != nil {
  141. skipExtendedTurnAroundThreshold = *support.Config.MeekSkipExtendedTurnAroundThresholdBytes
  142. }
  143. maxSessionStaleness := MEEK_DEFAULT_MAX_SESSION_STALENESS
  144. if support.Config.MeekMaxSessionStalenessMilliseconds != nil {
  145. maxSessionStaleness = time.Duration(
  146. *support.Config.MeekMaxSessionStalenessMilliseconds) * time.Millisecond
  147. }
  148. httpClientIOTimeout := MEEK_DEFAULT_HTTP_CLIENT_IO_TIMEOUT
  149. if support.Config.MeekHTTPClientIOTimeoutMilliseconds != nil {
  150. httpClientIOTimeout = time.Duration(
  151. *support.Config.MeekHTTPClientIOTimeoutMilliseconds) * time.Millisecond
  152. }
  153. checksumTable := crc64.MakeTable(crc64.ECMA)
  154. bufferLength := MEEK_DEFAULT_POOL_BUFFER_LENGTH
  155. if support.Config.MeekCachedResponsePoolBufferSize != 0 {
  156. bufferLength = support.Config.MeekCachedResponsePoolBufferSize
  157. }
  158. bufferCount := MEEK_DEFAULT_POOL_BUFFER_COUNT
  159. if support.Config.MeekCachedResponsePoolBufferCount != 0 {
  160. bufferCount = support.Config.MeekCachedResponsePoolBufferCount
  161. }
  162. _, thresholdSeconds, _, _, _, _, _, _, reapFrequencySeconds, maxEntries :=
  163. support.TrafficRulesSet.GetMeekRateLimiterConfig()
  164. rateLimitHistory := lrucache.NewWithLRU(
  165. time.Duration(thresholdSeconds)*time.Second,
  166. time.Duration(reapFrequencySeconds)*time.Second,
  167. maxEntries)
  168. bufferPool := NewCachedResponseBufferPool(bufferLength, bufferCount)
  169. meekServer := &MeekServer{
  170. support: support,
  171. listener: listener,
  172. listenerTunnelProtocol: listenerTunnelProtocol,
  173. listenerPort: listenerPort,
  174. passthroughAddress: passthroughAddress,
  175. turnAroundTimeout: turnAroundTimeout,
  176. extendedTurnAroundTimeout: extendedTurnAroundTimeout,
  177. skipExtendedTurnAroundThreshold: skipExtendedTurnAroundThreshold,
  178. maxSessionStaleness: maxSessionStaleness,
  179. httpClientIOTimeout: httpClientIOTimeout,
  180. obfuscatorSeedHistory: obfuscator.NewSeedHistory(nil),
  181. clientHandler: clientHandler,
  182. openConns: common.NewConns(),
  183. stopBroadcast: stopBroadcast,
  184. sessions: make(map[string]*meekSession),
  185. checksumTable: checksumTable,
  186. bufferPool: bufferPool,
  187. rateLimitHistory: rateLimitHistory,
  188. rateLimitSignalGC: make(chan struct{}, 1),
  189. }
  190. if useTLS {
  191. tlsConfig, err := meekServer.makeMeekTLSConfig(
  192. isFronted, useObfuscatedSessionTickets)
  193. if err != nil {
  194. return nil, errors.Trace(err)
  195. }
  196. meekServer.tlsConfig = tlsConfig
  197. }
  198. return meekServer, nil
  199. }
  200. type meekContextKey struct {
  201. key string
  202. }
  203. var meekNetConnContextKey = &meekContextKey{"net.Conn"}
  204. // Run runs the meek server; this function blocks while serving HTTP or
  205. // HTTPS connections on the specified listener. This function also runs
  206. // a goroutine which cleans up expired meek client sessions.
  207. //
  208. // To stop the meek server, both Close() the listener and set the stopBroadcast
  209. // signal specified in NewMeekServer.
  210. func (server *MeekServer) Run() error {
  211. waitGroup := new(sync.WaitGroup)
  212. waitGroup.Add(1)
  213. go func() {
  214. defer waitGroup.Done()
  215. ticker := time.NewTicker(server.maxSessionStaleness / 2)
  216. defer ticker.Stop()
  217. for {
  218. select {
  219. case <-ticker.C:
  220. server.deleteExpiredSessions()
  221. case <-server.stopBroadcast:
  222. return
  223. }
  224. }
  225. }()
  226. waitGroup.Add(1)
  227. go func() {
  228. defer waitGroup.Done()
  229. server.rateLimitWorker()
  230. }()
  231. // Serve HTTP or HTTPS
  232. //
  233. // - WriteTimeout may include time awaiting request, as per:
  234. // https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts
  235. // - Legacy meek-server wrapped each client HTTP connection with an explicit idle
  236. // timeout net.Conn and didn't use http.Server timeouts. We could do the same
  237. // here (use ActivityMonitoredConn) but the stock http.Server timeouts should
  238. // now be sufficient.
  239. httpServer := &http.Server{
  240. ReadTimeout: server.httpClientIOTimeout,
  241. WriteTimeout: server.httpClientIOTimeout,
  242. Handler: server,
  243. ConnState: server.httpConnStateCallback,
  244. ConnContext: func(ctx context.Context, conn net.Conn) context.Context {
  245. return context.WithValue(ctx, meekNetConnContextKey, conn)
  246. },
  247. // Disable auto HTTP/2 (https://golang.org/doc/go1.6)
  248. TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
  249. }
  250. // Note: Serve() will be interrupted by listener.Close() call
  251. var err error
  252. if server.tlsConfig != nil {
  253. httpsServer := HTTPSServer{Server: httpServer}
  254. err = httpsServer.ServeTLS(server.listener, server.tlsConfig)
  255. } else {
  256. err = httpServer.Serve(server.listener)
  257. }
  258. // Can't check for the exact error that Close() will cause in Accept(),
  259. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  260. // explicit stop signal to stop gracefully.
  261. select {
  262. case <-server.stopBroadcast:
  263. err = nil
  264. default:
  265. }
  266. // deleteExpiredSessions calls deleteSession which may block waiting
  267. // for active request handlers to complete; timely shutdown requires
  268. // stopping the listener and closing all existing connections before
  269. // awaiting the reaperWaitGroup.
  270. server.listener.Close()
  271. server.openConns.CloseAll()
  272. waitGroup.Wait()
  273. return err
  274. }
  275. // ServeHTTP handles meek client HTTP requests, where the request body
  276. // contains upstream traffic and the response will contain downstream
  277. // traffic.
  278. func (server *MeekServer) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  279. // Note: no longer requiring that the request method is POST
  280. // Check for the expected meek/session ID cookie.
  281. // Also check for prohibited HTTP headers.
  282. var meekCookie *http.Cookie
  283. for _, c := range request.Cookies() {
  284. meekCookie = c
  285. break
  286. }
  287. if meekCookie == nil || len(meekCookie.Value) == 0 {
  288. log.WithTrace().Warning("missing meek cookie")
  289. common.TerminateHTTPConnection(responseWriter, request)
  290. return
  291. }
  292. if len(server.support.Config.MeekProhibitedHeaders) > 0 {
  293. for _, header := range server.support.Config.MeekProhibitedHeaders {
  294. value := request.Header.Get(header)
  295. if header != "" {
  296. log.WithTraceFields(LogFields{
  297. "header": header,
  298. "value": value,
  299. }).Warning("prohibited meek header")
  300. common.TerminateHTTPConnection(responseWriter, request)
  301. return
  302. }
  303. }
  304. }
  305. // A valid meek cookie indicates which class of request this is:
  306. //
  307. // 1. A new meek session. Create a new session ID and proceed with
  308. // relaying tunnel traffic.
  309. //
  310. // 2. An existing meek session. Resume relaying tunnel traffic.
  311. //
  312. // 3. A request to an endpoint. This meek connection is not for relaying
  313. // tunnel traffic. Instead, the request is handed off to a custom handler.
  314. sessionID,
  315. session,
  316. underlyingConn,
  317. endPoint,
  318. endPointGeoIPData,
  319. err := server.getSessionOrEndpoint(request, meekCookie)
  320. if err != nil {
  321. // Debug since session cookie errors commonly occur during
  322. // normal operation.
  323. log.WithTraceFields(LogFields{"error": err}).Debug("session lookup failed")
  324. common.TerminateHTTPConnection(responseWriter, request)
  325. return
  326. }
  327. if endPoint != "" {
  328. // Endpoint mode. Currently, this means it's handled by the tactics
  329. // request handler.
  330. handled := server.support.TacticsServer.HandleEndPoint(
  331. endPoint, common.GeoIPData(*endPointGeoIPData), responseWriter, request)
  332. if !handled {
  333. log.WithTraceFields(LogFields{"endPoint": endPoint}).Info("unhandled endpoint")
  334. common.TerminateHTTPConnection(responseWriter, request)
  335. }
  336. return
  337. }
  338. // Tunnel relay mode.
  339. // Ensure that there's only one concurrent request handler per client
  340. // session. Depending on the nature of a network disruption, it can
  341. // happen that a client detects a failure and retries while the server
  342. // is still streaming response in the handler for the _previous_ client
  343. // request.
  344. //
  345. // Even if the session.cachedResponse were safe for concurrent
  346. // use (it is not), concurrent handling could lead to loss of session
  347. // since upstream data read by the first request may not reach the
  348. // cached response before the second request reads the cached data.
  349. //
  350. // The existing handler will stream response data, holding the lock,
  351. // for no more than MEEK_EXTENDED_TURN_AROUND_TIMEOUT.
  352. //
  353. // TODO: interrupt an existing handler? The existing handler will be
  354. // sending data to the cached response, but if that buffer fills, the
  355. // session will be lost.
  356. requestNumber := atomic.AddInt64(&session.requestCount, 1)
  357. // Wait for the existing request to complete.
  358. session.lock.Lock()
  359. defer session.lock.Unlock()
  360. // Count this metric once the lock is acquired, to avoid concurrent and
  361. // potentially incorrect session.underlyingConn updates.
  362. //
  363. // It should never be the case that a new underlyingConn has the same
  364. // value as the previous session.underlyingConn, as each is a net.Conn
  365. // interface which includes a pointer, and the previous value cannot
  366. // be garbage collected until session.underlyingConn is updated.
  367. if session.underlyingConn != underlyingConn {
  368. atomic.AddInt64(&session.metricUnderlyingConnCount, 1)
  369. session.underlyingConn = underlyingConn
  370. }
  371. // If a newer request has arrived while waiting, discard this one.
  372. // Do not delay processing the newest request.
  373. //
  374. // If the session expired and was deleted while this request was waiting,
  375. // discard this request. The session is no longer valid, and the final call
  376. // to session.cachedResponse.Reset may have already occured, so any further
  377. // session.cachedResponse access may deplete resources (fail to refill the pool).
  378. if atomic.LoadInt64(&session.requestCount) > requestNumber || session.deleted {
  379. common.TerminateHTTPConnection(responseWriter, request)
  380. return
  381. }
  382. // pumpReads causes a TunnelServer/SSH goroutine blocking on a Read to
  383. // read the request body as upstream traffic.
  384. // TODO: run pumpReads and pumpWrites concurrently?
  385. // pumpReads checksums the request payload and skips relaying it when
  386. // it matches the immediately previous request payload. This allows
  387. // clients to resend request payloads, when retrying due to connection
  388. // interruption, without knowing whether the server has received or
  389. // relayed the data.
  390. requestSize, err := session.clientConn.pumpReads(request.Body)
  391. if err != nil {
  392. if err != io.EOF {
  393. // Debug since errors such as "i/o timeout" occur during normal operation;
  394. // also, golang network error messages may contain client IP.
  395. log.WithTraceFields(LogFields{"error": err}).Debug("read request failed")
  396. }
  397. common.TerminateHTTPConnection(responseWriter, request)
  398. // Note: keep session open to allow client to retry
  399. return
  400. }
  401. // The extended turn around mechanism optimizes for downstream flows by
  402. // sending more data in the response as long as it's available. As a
  403. // heuristic, when the request size meets a threshold, optimize instead
  404. // of upstream flows by skipping the extended turn around.
  405. skipExtendedTurnAround := requestSize >= int64(server.skipExtendedTurnAroundThreshold)
  406. // Set cookie before writing the response.
  407. if session.meekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 && !session.sessionIDSent {
  408. // Replace the meek cookie with the session ID.
  409. // SetCookie for the the session ID cookie is only set once, to reduce overhead. This
  410. // session ID value replaces the original meek cookie value.
  411. http.SetCookie(responseWriter, &http.Cookie{Name: meekCookie.Name, Value: sessionID})
  412. session.sessionIDSent = true
  413. }
  414. // When streaming data into the response body, a copy is
  415. // retained in the cachedResponse buffer. This allows the
  416. // client to retry and request that the response be resent
  417. // when the HTTP connection is interrupted.
  418. //
  419. // If a Range header is present, the client is retrying,
  420. // possibly after having received a partial response. In
  421. // this case, use any cached response to attempt to resend
  422. // the response, starting from the resend position the client
  423. // indicates.
  424. //
  425. // When the resend position is not available -- because the
  426. // cachedResponse buffer could not hold it -- the client session
  427. // is closed, as there's no way to resume streaming the payload
  428. // uninterrupted.
  429. //
  430. // The client may retry before a cached response is prepared,
  431. // so a cached response is not always used when a Range header
  432. // is present.
  433. //
  434. // TODO: invalid Range header is ignored; should it be otherwise?
  435. position, isRetry := checkRangeHeader(request)
  436. if isRetry {
  437. atomic.AddInt64(&session.metricClientRetries, 1)
  438. }
  439. hasCompleteCachedResponse := session.cachedResponse.HasPosition(0)
  440. // The client is not expected to send position > 0 when there is
  441. // no cached response; let that case fall through to the next
  442. // HasPosition check which will fail and close the session.
  443. var responseSize int
  444. var responseError error
  445. if isRetry && (hasCompleteCachedResponse || position > 0) {
  446. if !session.cachedResponse.HasPosition(position) {
  447. greaterThanSwapInt64(&session.metricCachedResponseMissPosition, int64(position))
  448. common.TerminateHTTPConnection(responseWriter, request)
  449. session.delete(true)
  450. return
  451. }
  452. responseWriter.WriteHeader(http.StatusPartialContent)
  453. // TODO:
  454. // - enforce a max extended buffer count per client, for
  455. // fairness? Throttling may make this unnecessary.
  456. // - cachedResponse can now start releasing extended buffers,
  457. // as response bytes before "position" will never be requested
  458. // again?
  459. responseSize, responseError = session.cachedResponse.CopyFromPosition(position, responseWriter)
  460. greaterThanSwapInt64(&session.metricPeakCachedResponseHitSize, int64(responseSize))
  461. // The client may again fail to receive the payload and may again
  462. // retry, so not yet releasing cachedResponse buffers.
  463. } else {
  464. // _Now_ we release buffers holding data from the previous
  465. // response. And then immediately stream the new response into
  466. // newly acquired buffers.
  467. session.cachedResponse.Reset()
  468. // Note: this code depends on an implementation detail of
  469. // io.MultiWriter: a Write() to the MultiWriter writes first
  470. // to the cache, and then to the response writer. So if the
  471. // write to the response writer fails, the payload is cached.
  472. multiWriter := io.MultiWriter(session.cachedResponse, responseWriter)
  473. // The client expects 206, not 200, whenever it sets a Range header,
  474. // which it may do even when no cached response is prepared.
  475. if isRetry {
  476. responseWriter.WriteHeader(http.StatusPartialContent)
  477. }
  478. // pumpWrites causes a TunnelServer/SSH goroutine blocking on a Write to
  479. // write its downstream traffic through to the response body.
  480. responseSize, responseError = session.clientConn.pumpWrites(multiWriter, skipExtendedTurnAround)
  481. greaterThanSwapInt64(&session.metricPeakResponseSize, int64(responseSize))
  482. greaterThanSwapInt64(&session.metricPeakCachedResponseSize, int64(session.cachedResponse.Available()))
  483. }
  484. // responseError is the result of writing the body either from CopyFromPosition or pumpWrites
  485. if responseError != nil {
  486. if responseError != io.EOF {
  487. // Debug since errors such as "i/o timeout" occur during normal operation;
  488. // also, golang network error messages may contain client IP.
  489. log.WithTraceFields(LogFields{"error": responseError}).Debug("write response failed")
  490. }
  491. common.TerminateHTTPConnection(responseWriter, request)
  492. // Note: keep session open to allow client to retry
  493. return
  494. }
  495. }
  496. func checkRangeHeader(request *http.Request) (int, bool) {
  497. rangeHeader := request.Header.Get("Range")
  498. if rangeHeader == "" {
  499. return 0, false
  500. }
  501. prefix := "bytes="
  502. suffix := "-"
  503. if !strings.HasPrefix(rangeHeader, prefix) ||
  504. !strings.HasSuffix(rangeHeader, suffix) {
  505. return 0, false
  506. }
  507. rangeHeader = strings.TrimPrefix(rangeHeader, prefix)
  508. rangeHeader = strings.TrimSuffix(rangeHeader, suffix)
  509. position, err := strconv.Atoi(rangeHeader)
  510. if err != nil {
  511. return 0, false
  512. }
  513. return position, true
  514. }
  515. // getSessionOrEndpoint checks if the cookie corresponds to an existing tunnel
  516. // relay session ID. If no session is found, the cookie must be an obfuscated
  517. // meek cookie. A new session is created when the meek cookie indicates relay
  518. // mode; or the endpoint is returned when the meek cookie indicates endpoint
  519. // mode.
  520. func (server *MeekServer) getSessionOrEndpoint(
  521. request *http.Request, meekCookie *http.Cookie) (string, *meekSession, net.Conn, string, *GeoIPData, error) {
  522. underlyingConn := request.Context().Value(meekNetConnContextKey).(net.Conn)
  523. // Check for an existing session.
  524. server.sessionsLock.RLock()
  525. existingSessionID := meekCookie.Value
  526. session, ok := server.sessions[existingSessionID]
  527. server.sessionsLock.RUnlock()
  528. if ok {
  529. // TODO: can multiple http client connections using same session cookie
  530. // cause race conditions on session struct?
  531. session.touch()
  532. return existingSessionID, session, underlyingConn, "", nil, nil
  533. }
  534. // Determine the client remote address, which is used for geolocation
  535. // stats, rate limiting, anti-probing, discovery, and tactics selection
  536. // logic.
  537. //
  538. // When an intermediate proxy or CDN is in use, we may be
  539. // able to determine the original client address by inspecting HTTP
  540. // headers such as X-Forwarded-For.
  541. //
  542. // We trust only headers provided by CDNs. Fronted Psiphon server hosts
  543. // should be configured to accept tunnel connections only from CDN edges.
  544. // When the CDN passes along a chain of IPs, as in X-Forwarded-For, we
  545. // trust only the right-most IP, which is provided by the CDN.
  546. clientIP, _, err := net.SplitHostPort(request.RemoteAddr)
  547. if err != nil {
  548. return "", nil, nil, "", nil, errors.Trace(err)
  549. }
  550. if net.ParseIP(clientIP) == nil {
  551. return "", nil, nil, "", nil, errors.TraceNew("invalid IP address")
  552. }
  553. if protocol.TunnelProtocolUsesFrontedMeek(server.listenerTunnelProtocol) &&
  554. len(server.support.Config.MeekProxyForwardedForHeaders) > 0 {
  555. // When there are multiple header names in MeekProxyForwardedForHeaders,
  556. // the first valid match is preferred. MeekProxyForwardedForHeaders should be
  557. // configured to use header names that are always provided by the CDN(s) and
  558. // not header names that may be passed through from clients.
  559. for _, header := range server.support.Config.MeekProxyForwardedForHeaders {
  560. // In the case where there are multiple headers,
  561. // request.Header.Get returns the first header, but we want the
  562. // last header; so use request.Header.Values and select the last
  563. // value. As per RFC 2616 section 4.2, a proxy must not change
  564. // the order of field values, which implies that it should append
  565. // values to the last header.
  566. values := request.Header.Values(header)
  567. if len(values) > 0 {
  568. value := values[len(values)-1]
  569. // Some headers, such as X-Forwarded-For, are a comma-separated
  570. // list of IPs (each proxy in a chain). Select the last IP.
  571. IPs := strings.Split(value, ",")
  572. IP := IPs[len(IPs)-1]
  573. // Remove optional whitespace surrounding the commas.
  574. IP = strings.TrimSpace(IP)
  575. if net.ParseIP(IP) != nil {
  576. clientIP = IP
  577. break
  578. }
  579. }
  580. }
  581. }
  582. geoIPData := server.support.GeoIPService.Lookup(clientIP)
  583. // The session is new (or expired). Treat the cookie value as a new meek
  584. // cookie, extract the payload, and create a new session.
  585. // Limitation: when the cookie is a session ID for an expired session, we
  586. // still attempt to treat it as a meek cookie. As it stands, that yields
  587. // either base64 decoding errors (RawStdEncoding vs. StdEncoding) or
  588. // length errors. We could log cleaner errors ("session is expired") by
  589. // checking that the cookie is a well-formed (base64.RawStdEncoding) value
  590. // between MEEK_MIN_SESSION_ID_LENGTH and MEEK_MAX_SESSION_ID_LENGTH
  591. // bytes -- assuming that MEEK_MAX_SESSION_ID_LENGTH is too short to be a
  592. // valid meek cookie.
  593. payloadJSON, err := server.getMeekCookiePayload(clientIP, meekCookie.Value)
  594. if err != nil {
  595. return "", nil, nil, "", nil, errors.Trace(err)
  596. }
  597. // Note: this meek server ignores legacy values PsiphonClientSessionId
  598. // and PsiphonServerAddress.
  599. var clientSessionData protocol.MeekCookieData
  600. err = json.Unmarshal(payloadJSON, &clientSessionData)
  601. if err != nil {
  602. return "", nil, nil, "", nil, errors.Trace(err)
  603. }
  604. tunnelProtocol := server.listenerTunnelProtocol
  605. if clientSessionData.ClientTunnelProtocol != "" {
  606. if !protocol.IsValidClientTunnelProtocol(
  607. clientSessionData.ClientTunnelProtocol,
  608. server.listenerTunnelProtocol,
  609. server.support.Config.GetRunningProtocols()) {
  610. return "", nil, nil, "", nil, errors.Tracef(
  611. "invalid client tunnel protocol: %s", clientSessionData.ClientTunnelProtocol)
  612. }
  613. tunnelProtocol = clientSessionData.ClientTunnelProtocol
  614. }
  615. // Any rate limit is enforced after the meek cookie is validated, so a prober
  616. // without the obfuscation secret will be unable to fingerprint the server
  617. // based on response time combined with the rate limit configuration. The
  618. // rate limit is primarily intended to limit memory resource consumption and
  619. // not the overhead incurred by cookie validation.
  620. if server.rateLimit(clientIP, geoIPData, tunnelProtocol) {
  621. return "", nil, nil, "", nil, errors.TraceNew("rate limit exceeded")
  622. }
  623. // Handle endpoints before enforcing CheckEstablishTunnels.
  624. // Currently, endpoints are tactics requests, and we allow these to be
  625. // handled by servers which would otherwise reject new tunnels.
  626. if clientSessionData.EndPoint != "" {
  627. return "", nil, nil, clientSessionData.EndPoint, &geoIPData, nil
  628. }
  629. // Don't create new sessions when not establishing. A subsequent SSH handshake
  630. // will not succeed, so creating a meek session just wastes resources.
  631. if server.support.TunnelServer != nil &&
  632. !server.support.TunnelServer.CheckEstablishTunnels() {
  633. return "", nil, nil, "", nil, errors.TraceNew("not establishing tunnels")
  634. }
  635. // Disconnect immediately if the tactics for the client restricts usage of
  636. // the fronting provider ID. The probability may be used to influence
  637. // usage of a given fronting provider; but when only that provider works
  638. // for a given client, and the probability is less than 1.0, the client
  639. // can retry until it gets a successful coin flip.
  640. //
  641. // Clients will also skip candidates with restricted fronting provider IDs.
  642. // The client-side probability, RestrictFrontingProviderIDsClientProbability,
  643. // is applied independently of the server-side coin flip here.
  644. //
  645. // At this stage, GeoIP tactics filters are active, but handshake API
  646. // parameters are not.
  647. //
  648. // See the comment in server.LoadConfig regarding fronting provider ID
  649. // limitations.
  650. if protocol.TunnelProtocolUsesFrontedMeek(server.listenerTunnelProtocol) &&
  651. server.support.ServerTacticsParametersCache != nil {
  652. p, err := server.support.ServerTacticsParametersCache.Get(geoIPData)
  653. if err != nil {
  654. return "", nil, nil, "", nil, errors.Trace(err)
  655. }
  656. if !p.IsNil() &&
  657. common.Contains(
  658. p.Strings(parameters.RestrictFrontingProviderIDs),
  659. server.support.Config.GetFrontingProviderID()) {
  660. if p.WeightedCoinFlip(
  661. parameters.RestrictFrontingProviderIDsServerProbability) {
  662. return "", nil, nil, "", nil, errors.TraceNew("restricted fronting provider")
  663. }
  664. }
  665. }
  666. // Create a new session
  667. bufferLength := MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH
  668. if server.support.Config.MeekCachedResponseBufferSize != 0 {
  669. bufferLength = server.support.Config.MeekCachedResponseBufferSize
  670. }
  671. cachedResponse := NewCachedResponse(bufferLength, server.bufferPool)
  672. session = &meekSession{
  673. meekProtocolVersion: clientSessionData.MeekProtocolVersion,
  674. sessionIDSent: false,
  675. cachedResponse: cachedResponse,
  676. cookieName: meekCookie.Name,
  677. contentType: request.Header.Get("Content-Type"),
  678. }
  679. session.touch()
  680. // Create a new meek conn that will relay the payload
  681. // between meek request/responses and the tunnel server client
  682. // handler. The client IP is also used to initialize the
  683. // meek conn with a useful value to return when the tunnel
  684. // server calls conn.RemoteAddr() to get the client's IP address.
  685. // Assumes clientIP is a valid IP address; the port value is a stub
  686. // and is expected to be ignored.
  687. clientConn := newMeekConn(
  688. server,
  689. session,
  690. underlyingConn,
  691. &net.TCPAddr{
  692. IP: net.ParseIP(clientIP),
  693. Port: 0,
  694. },
  695. clientSessionData.MeekProtocolVersion)
  696. session.clientConn = clientConn
  697. // Note: MEEK_PROTOCOL_VERSION_1 doesn't support changing the
  698. // meek cookie to a session ID; v1 clients always send the
  699. // original meek cookie value with each request. The issue with
  700. // v1 is that clients which wake after a device sleep will attempt
  701. // to resume a meek session and the server can't differentiate
  702. // between resuming a session and creating a new session. This
  703. // causes the v1 client connection to hang/timeout.
  704. sessionID := meekCookie.Value
  705. if clientSessionData.MeekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 {
  706. sessionID, err = makeMeekSessionID()
  707. if err != nil {
  708. return "", nil, nil, "", nil, errors.Trace(err)
  709. }
  710. }
  711. server.sessionsLock.Lock()
  712. server.sessions[sessionID] = session
  713. server.sessionsLock.Unlock()
  714. // Note: from the tunnel server's perspective, this client connection
  715. // will close when session.delete calls Close() on the meekConn.
  716. server.clientHandler(clientSessionData.ClientTunnelProtocol, session.clientConn)
  717. return sessionID, session, underlyingConn, "", nil, nil
  718. }
  719. func (server *MeekServer) rateLimit(
  720. clientIP string, geoIPData GeoIPData, tunnelProtocol string) bool {
  721. historySize,
  722. thresholdSeconds,
  723. tunnelProtocols,
  724. regions,
  725. ISPs,
  726. ASNs,
  727. cities,
  728. GCTriggerCount, _, _ :=
  729. server.support.TrafficRulesSet.GetMeekRateLimiterConfig()
  730. if historySize == 0 {
  731. return false
  732. }
  733. if len(tunnelProtocols) > 0 {
  734. if !common.Contains(tunnelProtocols, tunnelProtocol) {
  735. return false
  736. }
  737. }
  738. if len(regions) > 0 || len(ISPs) > 0 || len(ASNs) > 0 || len(cities) > 0 {
  739. if len(regions) > 0 {
  740. if !common.Contains(regions, geoIPData.Country) {
  741. return false
  742. }
  743. }
  744. if len(ISPs) > 0 {
  745. if !common.Contains(ISPs, geoIPData.ISP) {
  746. return false
  747. }
  748. }
  749. if len(ASNs) > 0 {
  750. if !common.Contains(ASNs, geoIPData.ASN) {
  751. return false
  752. }
  753. }
  754. if len(cities) > 0 {
  755. if !common.Contains(cities, geoIPData.City) {
  756. return false
  757. }
  758. }
  759. }
  760. // With IPv6, individual users or sites are users commonly allocated a /64
  761. // or /56, so rate limit by /56.
  762. rateLimitIP := clientIP
  763. IP := net.ParseIP(clientIP)
  764. if IP != nil && IP.To4() == nil {
  765. rateLimitIP = IP.Mask(net.CIDRMask(56, 128)).String()
  766. }
  767. // go-cache-lru is safe for concurrent access, but lacks an atomic
  768. // compare-and-set type operations to check if an entry exists before
  769. // adding a new one. This mutex ensures the Get and Add are atomic
  770. // (as well as synchronizing access to rateLimitCount).
  771. server.rateLimitLock.Lock()
  772. var rateLimiter *ratelimit.Bucket
  773. entry, ok := server.rateLimitHistory.Get(rateLimitIP)
  774. if ok {
  775. rateLimiter = entry.(*ratelimit.Bucket)
  776. } else {
  777. rateLimiter = ratelimit.NewBucketWithQuantum(
  778. time.Duration(thresholdSeconds)*time.Second,
  779. int64(historySize),
  780. int64(historySize))
  781. server.rateLimitHistory.Set(
  782. rateLimitIP,
  783. rateLimiter,
  784. time.Duration(thresholdSeconds)*time.Second)
  785. }
  786. limit := rateLimiter.TakeAvailable(1) < 1
  787. triggerGC := false
  788. if limit {
  789. server.rateLimitCount += 1
  790. if server.rateLimitCount >= GCTriggerCount {
  791. triggerGC = true
  792. server.rateLimitCount = 0
  793. }
  794. }
  795. server.rateLimitLock.Unlock()
  796. if triggerGC {
  797. select {
  798. case server.rateLimitSignalGC <- struct{}{}:
  799. default:
  800. }
  801. }
  802. return limit
  803. }
  804. func (server *MeekServer) rateLimitWorker() {
  805. for {
  806. select {
  807. case <-server.rateLimitSignalGC:
  808. runtime.GC()
  809. case <-server.stopBroadcast:
  810. return
  811. }
  812. }
  813. }
  814. func (server *MeekServer) deleteSession(sessionID string) {
  815. // Don't obtain the server.sessionsLock write lock until modifying
  816. // server.sessions, as the session.delete can block for up to
  817. // MEEK_HTTP_CLIENT_IO_TIMEOUT. Allow new sessions to be added
  818. // concurrently.
  819. //
  820. // Since a lock isn't held for the duration, concurrent calls to
  821. // deleteSession with the same sessionID could happen; this is
  822. // not expected since only the reaper goroutine calls deleteExpiredSessions
  823. // (and in any case concurrent execution of the ok block is not an issue).
  824. server.sessionsLock.RLock()
  825. session, ok := server.sessions[sessionID]
  826. server.sessionsLock.RUnlock()
  827. if ok {
  828. session.delete(false)
  829. server.sessionsLock.Lock()
  830. delete(server.sessions, sessionID)
  831. server.sessionsLock.Unlock()
  832. }
  833. }
  834. func (server *MeekServer) deleteExpiredSessions() {
  835. // A deleteSession call may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  836. // so grab a snapshot list of expired sessions and do not hold a lock for
  837. // the duration of deleteExpiredSessions. This allows new sessions to be
  838. // added concurrently.
  839. //
  840. // New sessions added after the snapshot is taken will be checked for
  841. // expiry on subsequent periodic calls to deleteExpiredSessions.
  842. //
  843. // To avoid long delays in releasing resources, individual deletes are
  844. // performed concurrently.
  845. server.sessionsLock.Lock()
  846. expiredSessionIDs := make([]string, 0)
  847. for sessionID, session := range server.sessions {
  848. if session.expired() {
  849. expiredSessionIDs = append(expiredSessionIDs, sessionID)
  850. }
  851. }
  852. server.sessionsLock.Unlock()
  853. start := time.Now()
  854. deleteWaitGroup := new(sync.WaitGroup)
  855. for _, sessionID := range expiredSessionIDs {
  856. deleteWaitGroup.Add(1)
  857. go func(sessionID string) {
  858. defer deleteWaitGroup.Done()
  859. server.deleteSession(sessionID)
  860. }(sessionID)
  861. }
  862. deleteWaitGroup.Wait()
  863. log.WithTraceFields(
  864. LogFields{"elapsed time": time.Since(start)}).Debug("deleted expired sessions")
  865. }
  866. // httpConnStateCallback tracks open persistent HTTP/HTTPS connections to the
  867. // meek server.
  868. func (server *MeekServer) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  869. switch connState {
  870. case http.StateNew:
  871. server.openConns.Add(conn)
  872. case http.StateHijacked, http.StateClosed:
  873. server.openConns.Remove(conn)
  874. }
  875. }
  876. // getMeekCookiePayload extracts the payload from a meek cookie. The cookie
  877. // payload is base64 encoded, obfuscated, and NaCl encrypted.
  878. func (server *MeekServer) getMeekCookiePayload(
  879. clientIP string, cookieValue string) ([]byte, error) {
  880. decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
  881. if err != nil {
  882. return nil, errors.Trace(err)
  883. }
  884. // The data consists of an obfuscated seed message prepended
  885. // to the obfuscated, encrypted payload. The server obfuscator
  886. // will read the seed message, leaving the remaining encrypted
  887. // data in the reader.
  888. reader := bytes.NewReader(decodedValue[:])
  889. obfuscator, err := obfuscator.NewServerObfuscator(
  890. &obfuscator.ObfuscatorConfig{
  891. Keyword: server.support.Config.MeekObfuscatedKey,
  892. SeedHistory: server.obfuscatorSeedHistory,
  893. IrregularLogger: func(clientIP string, err error, logFields common.LogFields) {
  894. logIrregularTunnel(
  895. server.support,
  896. server.listenerTunnelProtocol,
  897. server.listenerPort,
  898. clientIP,
  899. errors.Trace(err),
  900. LogFields(logFields))
  901. },
  902. },
  903. clientIP,
  904. reader)
  905. if err != nil {
  906. return nil, errors.Trace(err)
  907. }
  908. offset, err := reader.Seek(0, 1)
  909. if err != nil {
  910. return nil, errors.Trace(err)
  911. }
  912. encryptedPayload := decodedValue[offset:]
  913. obfuscator.ObfuscateClientToServer(encryptedPayload)
  914. var nonce [24]byte
  915. var privateKey, ephemeralPublicKey [32]byte
  916. decodedPrivateKey, err := base64.StdEncoding.DecodeString(
  917. server.support.Config.MeekCookieEncryptionPrivateKey)
  918. if err != nil {
  919. return nil, errors.Trace(err)
  920. }
  921. copy(privateKey[:], decodedPrivateKey)
  922. if len(encryptedPayload) < 32 {
  923. return nil, errors.TraceNew("unexpected encrypted payload size")
  924. }
  925. copy(ephemeralPublicKey[0:32], encryptedPayload[0:32])
  926. payload, ok := box.Open(nil, encryptedPayload[32:], &nonce, &ephemeralPublicKey, &privateKey)
  927. if !ok {
  928. return nil, errors.TraceNew("open box failed")
  929. }
  930. return payload, nil
  931. }
  932. // makeMeekTLSConfig creates a TLS config for a meek HTTPS listener.
  933. // Currently, this config is optimized for fronted meek where the nature
  934. // of the connection is non-circumvention; it's optimized for performance
  935. // assuming the peer is an uncensored CDN.
  936. func (server *MeekServer) makeMeekTLSConfig(
  937. isFronted bool, useObfuscatedSessionTickets bool) (*tris.Config, error) {
  938. certificate, privateKey, err := common.GenerateWebServerCertificate(values.GetHostName())
  939. if err != nil {
  940. return nil, errors.Trace(err)
  941. }
  942. tlsCertificate, err := tris.X509KeyPair(
  943. []byte(certificate), []byte(privateKey))
  944. if err != nil {
  945. return nil, errors.Trace(err)
  946. }
  947. // Vary the minimum version to frustrate scanning/fingerprinting of unfronted servers.
  948. // Limitation: like the certificate, this value changes on restart.
  949. minVersionCandidates := []uint16{tris.VersionTLS10, tris.VersionTLS11, tris.VersionTLS12}
  950. minVersion := minVersionCandidates[prng.Intn(len(minVersionCandidates))]
  951. config := &tris.Config{
  952. Certificates: []tris.Certificate{tlsCertificate},
  953. NextProtos: []string{"http/1.1"},
  954. MinVersion: minVersion,
  955. UseExtendedMasterSecret: true,
  956. }
  957. if isFronted {
  958. // This is a reordering of the supported CipherSuites in golang 1.6[*]. Non-ephemeral key
  959. // CipherSuites greatly reduce server load, and we try to select these since the meek
  960. // protocol is providing obfuscation, not privacy/integrity (this is provided by the
  961. // tunneled SSH), so we don't benefit from the perfect forward secrecy property provided
  962. // by ephemeral key CipherSuites.
  963. // https://github.com/golang/go/blob/1cb3044c9fcd88e1557eca1bf35845a4108bc1db/src/crypto/tls/cipher_suites.go#L75
  964. //
  965. // This optimization is applied only when there's a CDN in front of the meek server; in
  966. // unfronted cases we prefer a more natural TLS handshake.
  967. //
  968. // [*] the list has since been updated, removing CipherSuites using RC4 and 3DES.
  969. config.CipherSuites = []uint16{
  970. tris.TLS_RSA_WITH_AES_128_GCM_SHA256,
  971. tris.TLS_RSA_WITH_AES_256_GCM_SHA384,
  972. tris.TLS_RSA_WITH_AES_128_CBC_SHA,
  973. tris.TLS_RSA_WITH_AES_256_CBC_SHA,
  974. tris.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  975. tris.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  976. tris.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  977. tris.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  978. tris.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  979. tris.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  980. tris.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  981. tris.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  982. }
  983. config.PreferServerCipherSuites = true
  984. }
  985. if useObfuscatedSessionTickets {
  986. // See obfuscated session ticket overview
  987. // in NewObfuscatedClientSessionCache.
  988. config.UseObfuscatedSessionTickets = true
  989. var obfuscatedSessionTicketKey [32]byte
  990. key, err := hex.DecodeString(server.support.Config.MeekObfuscatedKey)
  991. if err == nil && len(key) != 32 {
  992. err = std_errors.New("invalid obfuscated session key length")
  993. }
  994. if err != nil {
  995. return nil, errors.Trace(err)
  996. }
  997. copy(obfuscatedSessionTicketKey[:], key)
  998. var standardSessionTicketKey [32]byte
  999. _, err = rand.Read(standardSessionTicketKey[:])
  1000. if err != nil {
  1001. return nil, errors.Trace(err)
  1002. }
  1003. // Note: SessionTicketKey needs to be set, or else, it appears,
  1004. // tris.Config.serverInit() will clobber the value set by
  1005. // SetSessionTicketKeys.
  1006. config.SessionTicketKey = obfuscatedSessionTicketKey
  1007. config.SetSessionTicketKeys([][32]byte{
  1008. standardSessionTicketKey,
  1009. obfuscatedSessionTicketKey})
  1010. }
  1011. // When configured, initialize passthrough mode, an anti-probing defense.
  1012. // Clients must prove knowledge of the obfuscated key via a message sent in
  1013. // the TLS ClientHello random field.
  1014. //
  1015. // When clients fail to provide a valid message, the client connection is
  1016. // relayed to the designated passthrough address, typically another web site.
  1017. // The entire flow is relayed, including the original ClientHello, so the
  1018. // client will perform a TLS handshake with the passthrough target.
  1019. //
  1020. // Irregular events are logged for invalid client activity.
  1021. if server.passthroughAddress != "" {
  1022. config.PassthroughAddress = server.passthroughAddress
  1023. config.PassthroughVerifyMessage = func(
  1024. message []byte) bool {
  1025. return obfuscator.VerifyTLSPassthroughMessage(
  1026. !server.support.Config.LegacyPassthrough,
  1027. server.support.Config.MeekObfuscatedKey,
  1028. message)
  1029. }
  1030. config.PassthroughLogInvalidMessage = func(
  1031. clientIP string) {
  1032. logIrregularTunnel(
  1033. server.support,
  1034. server.listenerTunnelProtocol,
  1035. server.listenerPort,
  1036. clientIP,
  1037. errors.TraceNew("invalid passthrough message"),
  1038. nil)
  1039. }
  1040. config.PassthroughHistoryAddNew = func(
  1041. clientIP string,
  1042. clientRandom []byte) bool {
  1043. // Use a custom, shorter TTL based on the validity period of the
  1044. // passthrough message.
  1045. TTL := obfuscator.TLS_PASSTHROUGH_TIME_PERIOD
  1046. if server.support.Config.LegacyPassthrough {
  1047. TTL = obfuscator.HISTORY_SEED_TTL
  1048. }
  1049. // strictMode is true as, unlike with meek cookies, legitimate meek clients
  1050. // never retry TLS connections using a previous random value.
  1051. ok, logFields := server.obfuscatorSeedHistory.AddNewWithTTL(
  1052. true,
  1053. clientIP,
  1054. "client-random",
  1055. clientRandom,
  1056. TTL)
  1057. if logFields != nil {
  1058. logIrregularTunnel(
  1059. server.support,
  1060. server.listenerTunnelProtocol,
  1061. server.listenerPort,
  1062. clientIP,
  1063. errors.TraceNew("duplicate passthrough message"),
  1064. LogFields(*logFields))
  1065. }
  1066. return ok
  1067. }
  1068. }
  1069. return config, nil
  1070. }
  1071. type meekSession struct {
  1072. // Note: 64-bit ints used with atomic operations are placed
  1073. // at the start of struct to ensure 64-bit alignment.
  1074. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  1075. lastActivity int64
  1076. requestCount int64
  1077. metricClientRetries int64
  1078. metricPeakResponseSize int64
  1079. metricPeakCachedResponseSize int64
  1080. metricPeakCachedResponseHitSize int64
  1081. metricCachedResponseMissPosition int64
  1082. metricUnderlyingConnCount int64
  1083. lock sync.Mutex
  1084. deleted bool
  1085. underlyingConn net.Conn
  1086. clientConn *meekConn
  1087. meekProtocolVersion int
  1088. sessionIDSent bool
  1089. cachedResponse *CachedResponse
  1090. cookieName string
  1091. contentType string
  1092. }
  1093. func (session *meekSession) touch() {
  1094. atomic.StoreInt64(&session.lastActivity, int64(monotime.Now()))
  1095. }
  1096. func (session *meekSession) expired() bool {
  1097. if session.clientConn == nil {
  1098. // Not fully initialized. meekSession.clientConn will be set before adding
  1099. // the session to MeekServer.sessions.
  1100. return false
  1101. }
  1102. lastActivity := monotime.Time(atomic.LoadInt64(&session.lastActivity))
  1103. return monotime.Since(lastActivity) >
  1104. session.clientConn.meekServer.maxSessionStaleness
  1105. }
  1106. // delete releases all resources allocated by a session.
  1107. func (session *meekSession) delete(haveLock bool) {
  1108. // TODO: close the persistent HTTP client connection, if one exists?
  1109. // This final call session.cachedResponse.Reset releases shared resources.
  1110. //
  1111. // This call requires exclusive access. session.lock is be obtained before
  1112. // calling session.cachedResponse.Reset. Once the lock is obtained, no
  1113. // request for this session is being processed concurrently, and pending
  1114. // requests will block at session.lock.
  1115. //
  1116. // This logic assumes that no further session.cachedResponse access occurs,
  1117. // or else resources may deplete (buffers won't be returned to the pool).
  1118. // These requirements are achieved by obtaining the lock, setting
  1119. // session.deleted, and any subsequent request handlers checking
  1120. // session.deleted immediately after obtaining the lock.
  1121. //
  1122. // session.lock.Lock may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  1123. // the timeout for any active request handler processing a session
  1124. // request.
  1125. //
  1126. // When the lock must be acquired, clientConn.Close is called first, to
  1127. // interrupt any existing request handler blocking on pumpReads or pumpWrites.
  1128. session.clientConn.Close()
  1129. if !haveLock {
  1130. session.lock.Lock()
  1131. }
  1132. // Release all extended buffers back to the pool.
  1133. // session.cachedResponse.Reset is not safe for concurrent calls.
  1134. session.cachedResponse.Reset()
  1135. session.deleted = true
  1136. if !haveLock {
  1137. session.lock.Unlock()
  1138. }
  1139. }
  1140. // GetMetrics implements the common.MetricsSource interface.
  1141. func (session *meekSession) GetMetrics() common.LogFields {
  1142. logFields := make(common.LogFields)
  1143. logFields["meek_client_retries"] = atomic.LoadInt64(&session.metricClientRetries)
  1144. logFields["meek_peak_response_size"] = atomic.LoadInt64(&session.metricPeakResponseSize)
  1145. logFields["meek_peak_cached_response_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseSize)
  1146. logFields["meek_peak_cached_response_hit_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseHitSize)
  1147. logFields["meek_cached_response_miss_position"] = atomic.LoadInt64(&session.metricCachedResponseMissPosition)
  1148. logFields["meek_underlying_connection_count"] = atomic.LoadInt64(&session.metricUnderlyingConnCount)
  1149. logFields["meek_cookie_name"] = session.cookieName
  1150. logFields["meek_content_type"] = session.contentType
  1151. return logFields
  1152. }
  1153. // makeMeekSessionID creates a new session ID. The variable size is intended to
  1154. // frustrate traffic analysis of both plaintext and TLS meek traffic.
  1155. func makeMeekSessionID() (string, error) {
  1156. size := MEEK_MIN_SESSION_ID_LENGTH +
  1157. prng.Intn(MEEK_MAX_SESSION_ID_LENGTH-MEEK_MIN_SESSION_ID_LENGTH)
  1158. sessionID, err := common.MakeSecureRandomBytes(size)
  1159. if err != nil {
  1160. return "", errors.Trace(err)
  1161. }
  1162. // Omit padding to maximize variable size space. To the client, the session
  1163. // ID is an opaque string cookie value.
  1164. return base64.RawStdEncoding.EncodeToString(sessionID), nil
  1165. }
  1166. // meekConn implements the net.Conn interface and is to be used as a client
  1167. // connection by the tunnel server (being passed to sshServer.handleClient).
  1168. // meekConn bridges net/http request/response payload readers and writers
  1169. // and goroutines calling Read()s and Write()s.
  1170. type meekConn struct {
  1171. meekServer *MeekServer
  1172. meekSession *meekSession
  1173. firstUnderlyingConn net.Conn
  1174. remoteAddr net.Addr
  1175. protocolVersion int
  1176. closeBroadcast chan struct{}
  1177. closed int32
  1178. lastReadChecksum *uint64
  1179. readLock sync.Mutex
  1180. emptyReadBuffer chan *bytes.Buffer
  1181. partialReadBuffer chan *bytes.Buffer
  1182. fullReadBuffer chan *bytes.Buffer
  1183. writeLock sync.Mutex
  1184. nextWriteBuffer chan []byte
  1185. writeResult chan error
  1186. }
  1187. func newMeekConn(
  1188. meekServer *MeekServer,
  1189. meekSession *meekSession,
  1190. underlyingConn net.Conn,
  1191. remoteAddr net.Addr,
  1192. protocolVersion int) *meekConn {
  1193. // In order to inspect its properties, meekConn will hold a reference to
  1194. // firstUnderlyingConn, the _first_ underlying TCP conn, for the full
  1195. // lifetime of meekConn, which may exceed the lifetime of firstUnderlyingConn
  1196. // and include subsequent underlying TCP conns. In this case, it is expected
  1197. // that firstUnderlyingConn will be closed by "net/http", so no OS resources
  1198. // (e.g., a socket) are retained longer than necessary.
  1199. conn := &meekConn{
  1200. meekServer: meekServer,
  1201. meekSession: meekSession,
  1202. firstUnderlyingConn: underlyingConn,
  1203. remoteAddr: remoteAddr,
  1204. protocolVersion: protocolVersion,
  1205. closeBroadcast: make(chan struct{}),
  1206. closed: 0,
  1207. emptyReadBuffer: make(chan *bytes.Buffer, 1),
  1208. partialReadBuffer: make(chan *bytes.Buffer, 1),
  1209. fullReadBuffer: make(chan *bytes.Buffer, 1),
  1210. nextWriteBuffer: make(chan []byte, 1),
  1211. writeResult: make(chan error, 1),
  1212. }
  1213. // Read() calls and pumpReads() are synchronized by exchanging control
  1214. // of a single readBuffer. This is the same scheme used in and described
  1215. // in psiphon.MeekConn.
  1216. conn.emptyReadBuffer <- new(bytes.Buffer)
  1217. return conn
  1218. }
  1219. // GetMetrics implements the common.MetricsSource interface. The metrics are
  1220. // maintained in the meek session type; but logTunnel, which calls
  1221. // MetricsSource.GetMetrics, has a pointer only to this conn, so it calls
  1222. // through to the session.
  1223. func (conn *meekConn) GetMetrics() common.LogFields {
  1224. logFields := conn.meekSession.GetMetrics()
  1225. if conn.meekServer.passthroughAddress != "" {
  1226. logFields["passthrough_address"] = conn.meekServer.passthroughAddress
  1227. }
  1228. // Include metrics, such as fragmentor metrics, from the _first_ underlying
  1229. // TCP conn. Properties of subsequent underlying TCP conns are not reflected
  1230. // in these metrics; we assume that the first TCP conn, which most likely
  1231. // transits the various protocol handshakes, is most significant.
  1232. underlyingMetrics, ok := conn.firstUnderlyingConn.(common.MetricsSource)
  1233. if ok {
  1234. logFields.Add(underlyingMetrics.GetMetrics())
  1235. }
  1236. return logFields
  1237. }
  1238. // GetUnderlyingTCPAddrs implements the common.UnderlyingTCPAddrSource
  1239. // interface, returning the TCP addresses for the _first_ underlying TCP
  1240. // connection in the meek tunnel.
  1241. func (conn *meekConn) GetUnderlyingTCPAddrs() (*net.TCPAddr, *net.TCPAddr, bool) {
  1242. localAddr, ok := conn.firstUnderlyingConn.LocalAddr().(*net.TCPAddr)
  1243. if !ok {
  1244. return nil, nil, false
  1245. }
  1246. remoteAddr, ok := conn.firstUnderlyingConn.RemoteAddr().(*net.TCPAddr)
  1247. if !ok {
  1248. return nil, nil, false
  1249. }
  1250. return localAddr, remoteAddr, true
  1251. }
  1252. // SetReplay implements the common.FragmentorReplayAccessor interface, applying
  1253. // the inputs to the _first_ underlying TCP connection in the meek tunnel. If
  1254. // the underlying connection is closed, the SetSeed call will have no effect.
  1255. func (conn *meekConn) SetReplay(PRNG *prng.PRNG) {
  1256. fragmentor, ok := conn.firstUnderlyingConn.(common.FragmentorReplayAccessor)
  1257. if ok {
  1258. fragmentor.SetReplay(PRNG)
  1259. }
  1260. }
  1261. // GetReplay implements the FragmentorReplayAccessor interface, getting the
  1262. // outputs from the _first_ underlying TCP connection in the meek tunnel.
  1263. //
  1264. // We assume that the first TCP conn is most significant: the initial TCP
  1265. // connection most likely fragments protocol handshakes; and, in the case the
  1266. // packet manipulation, any selected packet manipulation spec would have been
  1267. // successful.
  1268. func (conn *meekConn) GetReplay() (*prng.Seed, bool) {
  1269. fragmentor, ok := conn.firstUnderlyingConn.(common.FragmentorReplayAccessor)
  1270. if ok {
  1271. return fragmentor.GetReplay()
  1272. }
  1273. return nil, false
  1274. }
  1275. // pumpReads causes goroutines blocking on meekConn.Read() to read
  1276. // from the specified reader. This function blocks until the reader
  1277. // is fully consumed or the meekConn is closed. A read buffer allows
  1278. // up to MEEK_MAX_REQUEST_PAYLOAD_LENGTH bytes to be read and buffered
  1279. // without a Read() immediately consuming the bytes, but there's still
  1280. // a possibility of a stall if no Read() calls are made after this
  1281. // read buffer is full.
  1282. // Returns the number of request bytes read.
  1283. // Note: assumes only one concurrent call to pumpReads
  1284. func (conn *meekConn) pumpReads(reader io.Reader) (int64, error) {
  1285. // Use either an empty or partial buffer. By using a partial
  1286. // buffer, pumpReads will not block if the Read() caller has
  1287. // not fully drained the read buffer.
  1288. var readBuffer *bytes.Buffer
  1289. select {
  1290. case readBuffer = <-conn.emptyReadBuffer:
  1291. case readBuffer = <-conn.partialReadBuffer:
  1292. case <-conn.closeBroadcast:
  1293. return 0, io.EOF
  1294. }
  1295. newDataOffset := readBuffer.Len()
  1296. // Since we need to read the full request payload in order to
  1297. // take its checksum before relaying it, the read buffer can
  1298. // grow to up to 2 x MEEK_MAX_REQUEST_PAYLOAD_LENGTH + 1.
  1299. // +1 allows for an explicit check for request payloads that
  1300. // exceed the maximum permitted length.
  1301. limitReader := io.LimitReader(reader, MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1)
  1302. n, err := readBuffer.ReadFrom(limitReader)
  1303. if err == nil && n == MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1 {
  1304. err = std_errors.New("invalid request payload length")
  1305. }
  1306. // If the request read fails, don't relay the new data. This allows
  1307. // the client to retry and resend its request payload without
  1308. // interrupting/duplicating the payload flow.
  1309. if err != nil {
  1310. readBuffer.Truncate(newDataOffset)
  1311. conn.replaceReadBuffer(readBuffer)
  1312. return 0, errors.Trace(err)
  1313. }
  1314. // Check if request payload checksum matches immediately
  1315. // previous payload. On match, assume this is a client retry
  1316. // sending payload that was already relayed and skip this
  1317. // payload. Payload is OSSH ciphertext and almost surely
  1318. // will not repeat. In the highly unlikely case that it does,
  1319. // the underlying SSH connection will fail and the client
  1320. // must reconnect.
  1321. checksum := crc64.Checksum(
  1322. readBuffer.Bytes()[newDataOffset:], conn.meekServer.checksumTable)
  1323. if conn.lastReadChecksum == nil {
  1324. conn.lastReadChecksum = new(uint64)
  1325. } else if *conn.lastReadChecksum == checksum {
  1326. readBuffer.Truncate(newDataOffset)
  1327. }
  1328. *conn.lastReadChecksum = checksum
  1329. conn.replaceReadBuffer(readBuffer)
  1330. return n, nil
  1331. }
  1332. var errMeekConnectionHasClosed = std_errors.New("meek connection has closed")
  1333. // Read reads from the meekConn into buffer. Read blocks until
  1334. // some data is read or the meekConn closes. Under the hood, it
  1335. // waits for pumpReads to submit a reader to read from.
  1336. // Note: lock is to conform with net.Conn concurrency semantics
  1337. func (conn *meekConn) Read(buffer []byte) (int, error) {
  1338. conn.readLock.Lock()
  1339. defer conn.readLock.Unlock()
  1340. var readBuffer *bytes.Buffer
  1341. select {
  1342. case readBuffer = <-conn.partialReadBuffer:
  1343. case readBuffer = <-conn.fullReadBuffer:
  1344. case <-conn.closeBroadcast:
  1345. return 0, errors.Trace(errMeekConnectionHasClosed)
  1346. }
  1347. n, err := readBuffer.Read(buffer)
  1348. conn.replaceReadBuffer(readBuffer)
  1349. return n, err
  1350. }
  1351. func (conn *meekConn) replaceReadBuffer(readBuffer *bytes.Buffer) {
  1352. length := readBuffer.Len()
  1353. if length >= MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  1354. conn.fullReadBuffer <- readBuffer
  1355. } else if length == 0 {
  1356. conn.emptyReadBuffer <- readBuffer
  1357. } else {
  1358. conn.partialReadBuffer <- readBuffer
  1359. }
  1360. }
  1361. // pumpWrites causes goroutines blocking on meekConn.Write() to write
  1362. // to the specified writer. This function blocks until the meek response
  1363. // body limits (size for protocol v1, turn around time for protocol v2+)
  1364. // are met, or the meekConn is closed.
  1365. //
  1366. // Note: channel scheme assumes only one concurrent call to pumpWrites
  1367. func (conn *meekConn) pumpWrites(
  1368. writer io.Writer, skipExtendedTurnAround bool) (int, error) {
  1369. startTime := time.Now()
  1370. timeout := time.NewTimer(conn.meekServer.turnAroundTimeout)
  1371. defer timeout.Stop()
  1372. n := 0
  1373. for {
  1374. select {
  1375. case buffer := <-conn.nextWriteBuffer:
  1376. written, err := writer.Write(buffer)
  1377. n += written
  1378. // Assumes that writeResult won't block.
  1379. // Note: always send the err to writeResult,
  1380. // as the Write() caller is blocking on this.
  1381. conn.writeResult <- err
  1382. if err != nil {
  1383. return n, err
  1384. }
  1385. if conn.protocolVersion < MEEK_PROTOCOL_VERSION_1 {
  1386. // Pre-protocol version 1 clients expect at most
  1387. // MEEK_MAX_REQUEST_PAYLOAD_LENGTH response bodies
  1388. return n, nil
  1389. }
  1390. if skipExtendedTurnAround {
  1391. // When fast turn around is indicated, skip the extended turn
  1392. // around timeout. This optimizes for upstream flows.
  1393. return n, nil
  1394. }
  1395. totalElapsedTime := time.Since(startTime) / time.Millisecond
  1396. if totalElapsedTime >= conn.meekServer.extendedTurnAroundTimeout {
  1397. return n, nil
  1398. }
  1399. timeout.Reset(conn.meekServer.turnAroundTimeout)
  1400. case <-timeout.C:
  1401. return n, nil
  1402. case <-conn.closeBroadcast:
  1403. return n, errors.Trace(errMeekConnectionHasClosed)
  1404. }
  1405. }
  1406. }
  1407. // Write writes the buffer to the meekConn. It blocks until the
  1408. // entire buffer is written to or the meekConn closes. Under the
  1409. // hood, it waits for sufficient pumpWrites calls to consume the
  1410. // write buffer.
  1411. // Note: lock is to conform with net.Conn concurrency semantics
  1412. func (conn *meekConn) Write(buffer []byte) (int, error) {
  1413. conn.writeLock.Lock()
  1414. defer conn.writeLock.Unlock()
  1415. // TODO: may be more efficient to send whole buffer
  1416. // and have pumpWrites stash partial buffer when can't
  1417. // send it all.
  1418. n := 0
  1419. for n < len(buffer) {
  1420. end := n + MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  1421. if end > len(buffer) {
  1422. end = len(buffer)
  1423. }
  1424. // Only write MEEK_MAX_REQUEST_PAYLOAD_LENGTH at a time,
  1425. // to ensure compatibility with v1 protocol.
  1426. chunk := buffer[n:end]
  1427. select {
  1428. case conn.nextWriteBuffer <- chunk:
  1429. case <-conn.closeBroadcast:
  1430. return n, errors.Trace(errMeekConnectionHasClosed)
  1431. }
  1432. // Wait for the buffer to be processed.
  1433. select {
  1434. case <-conn.writeResult:
  1435. // The err from conn.writeResult comes from the
  1436. // io.MultiWriter used in pumpWrites, which writes
  1437. // to both the cached response and the HTTP response.
  1438. //
  1439. // Don't stop on error here, since only writing
  1440. // to the HTTP response will fail, and the client
  1441. // may retry and use the cached response.
  1442. //
  1443. // It's possible that the cached response buffer
  1444. // is too small for the client to successfully
  1445. // retry, but that cannot be determined. In this
  1446. // case, the meek connection will eventually fail.
  1447. //
  1448. // err is already logged in ServeHTTP.
  1449. case <-conn.closeBroadcast:
  1450. return n, errors.Trace(errMeekConnectionHasClosed)
  1451. }
  1452. n += len(chunk)
  1453. }
  1454. return n, nil
  1455. }
  1456. // Close closes the meekConn. This will interrupt any blocked
  1457. // Read, Write, pumpReads, and pumpWrites.
  1458. func (conn *meekConn) Close() error {
  1459. if atomic.CompareAndSwapInt32(&conn.closed, 0, 1) {
  1460. close(conn.closeBroadcast)
  1461. // In general, we reply on "net/http" to close underlying TCP conns. In this
  1462. // case, we can directly close the first once, if it's still open.
  1463. conn.firstUnderlyingConn.Close()
  1464. }
  1465. return nil
  1466. }
  1467. // Stub implementation of net.Conn.LocalAddr
  1468. func (conn *meekConn) LocalAddr() net.Addr {
  1469. return nil
  1470. }
  1471. // RemoteAddr returns the remoteAddr specified in newMeekConn. This
  1472. // acts as a proxy for the actual remote address, which is either a
  1473. // direct HTTP/HTTPS connection remote address, or in the case of
  1474. // downstream proxy of CDN fronts, some other value determined via
  1475. // HTTP headers.
  1476. func (conn *meekConn) RemoteAddr() net.Addr {
  1477. return conn.remoteAddr
  1478. }
  1479. // SetDeadline is not a true implementation of net.Conn.SetDeadline. It
  1480. // merely checks that the requested timeout exceeds the MEEK_MAX_SESSION_STALENESS
  1481. // period. When it does, and the session is idle, the meekConn Read/Write will
  1482. // be interrupted and return an error (not a timeout error) before the deadline.
  1483. // In other words, this conn will approximate the desired functionality of
  1484. // timing out on idle on or before the requested deadline.
  1485. func (conn *meekConn) SetDeadline(t time.Time) error {
  1486. // Overhead: nanoseconds (https://blog.cloudflare.com/its-go-time-on-linux/)
  1487. if time.Now().Add(conn.meekServer.maxSessionStaleness).Before(t) {
  1488. return nil
  1489. }
  1490. return errors.TraceNew("not supported")
  1491. }
  1492. // Stub implementation of net.Conn.SetReadDeadline
  1493. func (conn *meekConn) SetReadDeadline(t time.Time) error {
  1494. return errors.TraceNew("not supported")
  1495. }
  1496. // Stub implementation of net.Conn.SetWriteDeadline
  1497. func (conn *meekConn) SetWriteDeadline(t time.Time) error {
  1498. return errors.TraceNew("not supported")
  1499. }