meek.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. "crypto/rand"
  23. golangtls "crypto/tls"
  24. "encoding/base64"
  25. "encoding/hex"
  26. "encoding/json"
  27. "errors"
  28. "hash/crc64"
  29. "io"
  30. "net"
  31. "net/http"
  32. "strconv"
  33. "strings"
  34. "sync"
  35. "sync/atomic"
  36. "time"
  37. "github.com/Psiphon-Inc/goarista/monotime"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/nacl/box"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tls"
  42. )
  43. // MeekServer is based on meek-server.go from Tor and Psiphon:
  44. //
  45. // https://gitweb.torproject.org/pluggable-transports/meek.git/blob/HEAD:/meek-client/meek-client.go
  46. // CC0 1.0 Universal
  47. //
  48. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/go/meek-client/meek-client.go
  49. const (
  50. // Protocol version 1 clients can handle arbitrary length response bodies. Older clients
  51. // report no version number and expect at most 64K response bodies.
  52. MEEK_PROTOCOL_VERSION_1 = 1
  53. // Protocol version 2 clients initiate a session by sending an encrypted and obfuscated meek
  54. // cookie with their initial HTTP request. Connection information is contained within the
  55. // encrypted cookie payload. The server inspects the cookie and establishes a new session and
  56. // returns a new random session ID back to client via Set-Cookie header. The client uses this
  57. // session ID on all subsequent requests for the remainder of the session.
  58. MEEK_PROTOCOL_VERSION_2 = 2
  59. // Protocol version 3 clients include resiliency enhancements and will add a Range header
  60. // when retrying a request for a partially downloaded response payload.
  61. MEEK_PROTOCOL_VERSION_3 = 3
  62. MEEK_MAX_REQUEST_PAYLOAD_LENGTH = 65536
  63. MEEK_TURN_AROUND_TIMEOUT = 20 * time.Millisecond
  64. MEEK_EXTENDED_TURN_AROUND_TIMEOUT = 100 * time.Millisecond
  65. MEEK_MAX_SESSION_STALENESS = 45 * time.Second
  66. MEEK_HTTP_CLIENT_IO_TIMEOUT = 45 * time.Second
  67. MEEK_MIN_SESSION_ID_LENGTH = 8
  68. MEEK_MAX_SESSION_ID_LENGTH = 20
  69. MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH = 65536
  70. MEEK_DEFAULT_POOL_BUFFER_LENGTH = 65536
  71. MEEK_DEFAULT_POOL_BUFFER_COUNT = 2048
  72. )
  73. // MeekServer implements the meek protocol, which tunnels TCP traffic (in the case of Psiphon,
  74. // Obfusated SSH traffic) over HTTP. Meek may be fronted (through a CDN) or direct and may be
  75. // HTTP or HTTPS.
  76. //
  77. // Upstream traffic arrives in HTTP request bodies and downstream traffic is sent in response
  78. // bodies. The sequence of traffic for a given flow is associated using a session ID that's
  79. // set as a HTTP cookie for the client to submit with each request.
  80. //
  81. // MeekServer hooks into TunnelServer via the net.Conn interface by transforming the
  82. // HTTP payload traffic for a given session into net.Conn conforming Read()s and Write()s via
  83. // the meekConn struct.
  84. type MeekServer struct {
  85. support *SupportServices
  86. listener net.Listener
  87. tlsConfig *tls.Config
  88. clientHandler func(clientTunnelProtocol string, clientConn net.Conn)
  89. openConns *common.Conns
  90. stopBroadcast <-chan struct{}
  91. sessionsLock sync.RWMutex
  92. sessions map[string]*meekSession
  93. checksumTable *crc64.Table
  94. bufferPool *CachedResponseBufferPool
  95. }
  96. // NewMeekServer initializes a new meek server.
  97. func NewMeekServer(
  98. support *SupportServices,
  99. listener net.Listener,
  100. useTLS, useObfuscatedSessionTickets bool,
  101. clientHandler func(clientTunnelProtocol string, clientConn net.Conn),
  102. stopBroadcast <-chan struct{}) (*MeekServer, error) {
  103. checksumTable := crc64.MakeTable(crc64.ECMA)
  104. bufferLength := MEEK_DEFAULT_POOL_BUFFER_LENGTH
  105. if support.Config.MeekCachedResponsePoolBufferSize != 0 {
  106. bufferLength = support.Config.MeekCachedResponsePoolBufferSize
  107. }
  108. bufferCount := MEEK_DEFAULT_POOL_BUFFER_COUNT
  109. if support.Config.MeekCachedResponsePoolBufferCount != 0 {
  110. bufferCount = support.Config.MeekCachedResponsePoolBufferCount
  111. }
  112. bufferPool := NewCachedResponseBufferPool(bufferLength, bufferCount)
  113. meekServer := &MeekServer{
  114. support: support,
  115. listener: listener,
  116. clientHandler: clientHandler,
  117. openConns: new(common.Conns),
  118. stopBroadcast: stopBroadcast,
  119. sessions: make(map[string]*meekSession),
  120. checksumTable: checksumTable,
  121. bufferPool: bufferPool,
  122. }
  123. if useTLS {
  124. tlsConfig, err := makeMeekTLSConfig(
  125. support, useObfuscatedSessionTickets)
  126. if err != nil {
  127. return nil, common.ContextError(err)
  128. }
  129. meekServer.tlsConfig = tlsConfig
  130. }
  131. return meekServer, nil
  132. }
  133. // Run runs the meek server; this function blocks while serving HTTP or
  134. // HTTPS connections on the specified listener. This function also runs
  135. // a goroutine which cleans up expired meek client sessions.
  136. //
  137. // To stop the meek server, both Close() the listener and set the stopBroadcast
  138. // signal specified in NewMeekServer.
  139. func (server *MeekServer) Run() error {
  140. // Expire sessions
  141. reaperWaitGroup := new(sync.WaitGroup)
  142. reaperWaitGroup.Add(1)
  143. go func() {
  144. defer reaperWaitGroup.Done()
  145. ticker := time.NewTicker(MEEK_MAX_SESSION_STALENESS / 2)
  146. defer ticker.Stop()
  147. for {
  148. select {
  149. case <-ticker.C:
  150. server.deleteExpiredSessions()
  151. case <-server.stopBroadcast:
  152. return
  153. }
  154. }
  155. }()
  156. // Serve HTTP or HTTPS
  157. // Notes:
  158. // - WriteTimeout may include time awaiting request, as per:
  159. // https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts
  160. // - Legacy meek-server wrapped each client HTTP connection with an explicit idle
  161. // timeout net.Conn and didn't use http.Server timeouts. We could do the same
  162. // here (use ActivityMonitoredConn) but the stock http.Server timeouts should
  163. // now be sufficient.
  164. httpServer := &http.Server{
  165. ReadTimeout: MEEK_HTTP_CLIENT_IO_TIMEOUT,
  166. WriteTimeout: MEEK_HTTP_CLIENT_IO_TIMEOUT,
  167. Handler: server,
  168. ConnState: server.httpConnStateCallback,
  169. // Disable auto HTTP/2 (https://golang.org/doc/go1.6)
  170. TLSNextProto: make(map[string]func(*http.Server, *golangtls.Conn, http.Handler)),
  171. }
  172. // Note: Serve() will be interrupted by listener.Close() call
  173. var err error
  174. if server.tlsConfig != nil {
  175. httpsServer := HTTPSServer{Server: httpServer}
  176. err = httpsServer.ServeTLS(server.listener, server.tlsConfig)
  177. } else {
  178. err = httpServer.Serve(server.listener)
  179. }
  180. // Can't check for the exact error that Close() will cause in Accept(),
  181. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  182. // explicit stop signal to stop gracefully.
  183. select {
  184. case <-server.stopBroadcast:
  185. err = nil
  186. default:
  187. }
  188. // deleteExpiredSessions calls deleteSession which may block waiting
  189. // for active request handlers to complete; timely shutdown requires
  190. // stopping the listener and closing all existing connections before
  191. // awaiting the reaperWaitGroup.
  192. server.listener.Close()
  193. server.openConns.CloseAll()
  194. reaperWaitGroup.Wait()
  195. return err
  196. }
  197. // ServeHTTP handles meek client HTTP requests, where the request body
  198. // contains upstream traffic and the response will contain downstream
  199. // traffic.
  200. func (server *MeekServer) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  201. // Note: no longer requiring that the request method is POST
  202. // Check for the expected meek/session ID cookie.
  203. // Also check for prohibited HTTP headers.
  204. var meekCookie *http.Cookie
  205. for _, c := range request.Cookies() {
  206. meekCookie = c
  207. break
  208. }
  209. if meekCookie == nil || len(meekCookie.Value) == 0 {
  210. log.WithContext().Warning("missing meek cookie")
  211. server.terminateConnection(responseWriter, request)
  212. return
  213. }
  214. if len(server.support.Config.MeekProhibitedHeaders) > 0 {
  215. for _, header := range server.support.Config.MeekProhibitedHeaders {
  216. value := request.Header.Get(header)
  217. if header != "" {
  218. log.WithContextFields(LogFields{
  219. "header": header,
  220. "value": value,
  221. }).Warning("prohibited meek header")
  222. server.terminateConnection(responseWriter, request)
  223. return
  224. }
  225. }
  226. }
  227. // Lookup or create a new session for given meek cookie/session ID.
  228. sessionID, session, err := server.getSession(request, meekCookie)
  229. if err != nil {
  230. // Debug since session cookie errors commonly occur during
  231. // normal operation.
  232. log.WithContextFields(LogFields{"error": err}).Debug("session lookup failed")
  233. server.terminateConnection(responseWriter, request)
  234. return
  235. }
  236. // Ensure that there's only one concurrent request handler per client
  237. // session. Depending on the nature of a network disruption, it can
  238. // happen that a client detects a failure and retries while the server
  239. // is still streaming response in the handler for the _previous_ client
  240. // request.
  241. //
  242. // Even if the session.cachedResponse were safe for concurrent
  243. // use (it is not), concurrent handling could lead to loss of session
  244. // since upstream data read by the first request may not reach the
  245. // cached response before the second request reads the cached data.
  246. //
  247. // The existing handler will stream response data, holding the lock,
  248. // for no more than MEEK_EXTENDED_TURN_AROUND_TIMEOUT.
  249. //
  250. // TODO: interrupt an existing handler? The existing handler will be
  251. // sending data to the cached response, but if that buffer fills, the
  252. // session will be lost.
  253. requestNumber := atomic.AddInt64(&session.requestCount, 1)
  254. // Wait for the existing request to complete.
  255. session.lock.Lock()
  256. defer session.lock.Unlock()
  257. // If a newer request has arrived while waiting, discard this one.
  258. // Do not delay processing the newest request.
  259. //
  260. // If the session expired and was deleted while this request was waiting,
  261. // discard this request. The session is no longer valid, and the final call
  262. // to session.cachedResponse.Reset may have already occured, so any further
  263. // session.cachedResponse access may deplete resources (fail to refill the pool).
  264. if atomic.LoadInt64(&session.requestCount) > requestNumber || session.deleted {
  265. server.terminateConnection(responseWriter, request)
  266. return
  267. }
  268. // pumpReads causes a TunnelServer/SSH goroutine blocking on a Read to
  269. // read the request body as upstream traffic.
  270. // TODO: run pumpReads and pumpWrites concurrently?
  271. // pumpReads checksums the request payload and skips relaying it when
  272. // it matches the immediately previous request payload. This allows
  273. // clients to resend request payloads, when retrying due to connection
  274. // interruption, without knowing whether the server has received or
  275. // relayed the data.
  276. err = session.clientConn.pumpReads(request.Body)
  277. if err != nil {
  278. if err != io.EOF {
  279. // Debug since errors such as "i/o timeout" occur during normal operation;
  280. // also, golang network error messages may contain client IP.
  281. log.WithContextFields(LogFields{"error": err}).Debug("read request failed")
  282. }
  283. server.terminateConnection(responseWriter, request)
  284. // Note: keep session open to allow client to retry
  285. return
  286. }
  287. // Set cookie before writing the response.
  288. if session.meekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 && session.sessionIDSent == false {
  289. // Replace the meek cookie with the session ID.
  290. // SetCookie for the the session ID cookie is only set once, to reduce overhead. This
  291. // session ID value replaces the original meek cookie value.
  292. http.SetCookie(responseWriter, &http.Cookie{Name: meekCookie.Name, Value: sessionID})
  293. session.sessionIDSent = true
  294. }
  295. // When streaming data into the response body, a copy is
  296. // retained in the cachedResponse buffer. This allows the
  297. // client to retry and request that the response be resent
  298. // when the HTTP connection is interrupted.
  299. //
  300. // If a Range header is present, the client is retrying,
  301. // possibly after having received a partial response. In
  302. // this case, use any cached response to attempt to resend
  303. // the response, starting from the resend position the client
  304. // indicates.
  305. //
  306. // When the resend position is not available -- because the
  307. // cachedResponse buffer could not hold it -- the client session
  308. // is closed, as there's no way to resume streaming the payload
  309. // uninterrupted.
  310. //
  311. // The client may retry before a cached response is prepared,
  312. // so a cached response is not always used when a Range header
  313. // is present.
  314. //
  315. // TODO: invalid Range header is ignored; should it be otherwise?
  316. position, isRetry := checkRangeHeader(request)
  317. if isRetry {
  318. atomic.AddInt64(&session.metricClientRetries, 1)
  319. }
  320. hasCompleteCachedResponse := session.cachedResponse.HasPosition(0)
  321. // The client is not expected to send position > 0 when there is
  322. // no cached response; let that case fall through to the next
  323. // HasPosition check which will fail and close the session.
  324. var responseSize int
  325. var responseError error
  326. if isRetry && (hasCompleteCachedResponse || position > 0) {
  327. if !session.cachedResponse.HasPosition(position) {
  328. greaterThanSwapInt64(&session.metricCachedResponseMissPosition, int64(position))
  329. server.terminateConnection(responseWriter, request)
  330. session.delete(true)
  331. return
  332. }
  333. responseWriter.WriteHeader(http.StatusPartialContent)
  334. // TODO:
  335. // - enforce a max extended buffer count per client, for
  336. // fairness? Throttling may make this unnecessary.
  337. // - cachedResponse can now start releasing extended buffers,
  338. // as response bytes before "position" will never be requested
  339. // again?
  340. responseSize, responseError = session.cachedResponse.CopyFromPosition(position, responseWriter)
  341. greaterThanSwapInt64(&session.metricPeakCachedResponseHitSize, int64(responseSize))
  342. // The client may again fail to receive the payload and may again
  343. // retry, so not yet releasing cachedResponse buffers.
  344. } else {
  345. // _Now_ we release buffers holding data from the previous
  346. // response. And then immediately stream the new response into
  347. // newly acquired buffers.
  348. session.cachedResponse.Reset()
  349. // Note: this code depends on an implementation detail of
  350. // io.MultiWriter: a Write() to the MultiWriter writes first
  351. // to the cache, and then to the response writer. So if the
  352. // write to the response writer fails, the payload is cached.
  353. multiWriter := io.MultiWriter(session.cachedResponse, responseWriter)
  354. // The client expects 206, not 200, whenever it sets a Range header,
  355. // which it may do even when no cached response is prepared.
  356. if isRetry {
  357. responseWriter.WriteHeader(http.StatusPartialContent)
  358. }
  359. // pumpWrites causes a TunnelServer/SSH goroutine blocking on a Write to
  360. // write its downstream traffic through to the response body.
  361. responseSize, responseError = session.clientConn.pumpWrites(multiWriter)
  362. greaterThanSwapInt64(&session.metricPeakResponseSize, int64(responseSize))
  363. greaterThanSwapInt64(&session.metricPeakCachedResponseSize, int64(session.cachedResponse.Available()))
  364. }
  365. // responseError is the result of writing the body either from CopyFromPosition or pumpWrites
  366. if responseError != nil {
  367. if responseError != io.EOF {
  368. // Debug since errors such as "i/o timeout" occur during normal operation;
  369. // also, golang network error messages may contain client IP.
  370. log.WithContextFields(LogFields{"error": responseError}).Debug("write response failed")
  371. }
  372. server.terminateConnection(responseWriter, request)
  373. // Note: keep session open to allow client to retry
  374. return
  375. }
  376. }
  377. func checkRangeHeader(request *http.Request) (int, bool) {
  378. rangeHeader := request.Header.Get("Range")
  379. if rangeHeader == "" {
  380. return 0, false
  381. }
  382. prefix := "bytes="
  383. suffix := "-"
  384. if !strings.HasPrefix(rangeHeader, prefix) ||
  385. !strings.HasSuffix(rangeHeader, suffix) {
  386. return 0, false
  387. }
  388. rangeHeader = strings.TrimPrefix(rangeHeader, prefix)
  389. rangeHeader = strings.TrimSuffix(rangeHeader, suffix)
  390. position, err := strconv.Atoi(rangeHeader)
  391. if err != nil {
  392. return 0, false
  393. }
  394. return position, true
  395. }
  396. // getSession returns the meek client session corresponding the
  397. // meek cookie/session ID. If no session is found, the cookie is
  398. // treated as a meek cookie for a new session and its payload is
  399. // extracted and used to establish a new session.
  400. func (server *MeekServer) getSession(
  401. request *http.Request, meekCookie *http.Cookie) (string, *meekSession, error) {
  402. // Check for an existing session
  403. server.sessionsLock.RLock()
  404. existingSessionID := meekCookie.Value
  405. session, ok := server.sessions[existingSessionID]
  406. server.sessionsLock.RUnlock()
  407. if ok {
  408. session.touch()
  409. return existingSessionID, session, nil
  410. }
  411. // Don't create new sessions when not establishing. A subsequent SSH handshake
  412. // will not succeed, so creating a meek session just wastes resources.
  413. if server.support.TunnelServer != nil &&
  414. !server.support.TunnelServer.GetEstablishTunnels() {
  415. return "", nil, common.ContextError(errors.New("not establishing tunnels"))
  416. }
  417. // TODO: can multiple http client connections using same session cookie
  418. // cause race conditions on session struct?
  419. // The session is new (or expired). Treat the cookie value as a new meek
  420. // cookie, extract the payload, and create a new session.
  421. payloadJSON, err := getMeekCookiePayload(server.support, meekCookie.Value)
  422. if err != nil {
  423. return "", nil, common.ContextError(err)
  424. }
  425. // Note: this meek server ignores legacy values PsiphonClientSessionId
  426. // and PsiphonServerAddress.
  427. var clientSessionData protocol.MeekCookieData
  428. err = json.Unmarshal(payloadJSON, &clientSessionData)
  429. if err != nil {
  430. return "", nil, common.ContextError(err)
  431. }
  432. // Determine the client remote address, which is used for geolocation
  433. // and stats. When an intermediate proxy or CDN is in use, we may be
  434. // able to determine the original client address by inspecting HTTP
  435. // headers such as X-Forwarded-For.
  436. clientIP := strings.Split(request.RemoteAddr, ":")[0]
  437. if len(server.support.Config.MeekProxyForwardedForHeaders) > 0 {
  438. for _, header := range server.support.Config.MeekProxyForwardedForHeaders {
  439. value := request.Header.Get(header)
  440. if len(value) > 0 {
  441. // Some headers, such as X-Forwarded-For, are a comma-separated
  442. // list of IPs (each proxy in a chain). The first IP should be
  443. // the client IP.
  444. proxyClientIP := strings.Split(value, ",")[0]
  445. if net.ParseIP(proxyClientIP) != nil &&
  446. server.support.GeoIPService.Lookup(proxyClientIP).Country != GEOIP_UNKNOWN_VALUE {
  447. clientIP = proxyClientIP
  448. break
  449. }
  450. }
  451. }
  452. }
  453. // Create a new session
  454. bufferLength := MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH
  455. if server.support.Config.MeekCachedResponseBufferSize != 0 {
  456. bufferLength = server.support.Config.MeekCachedResponseBufferSize
  457. }
  458. cachedResponse := NewCachedResponse(bufferLength, server.bufferPool)
  459. session = &meekSession{
  460. meekProtocolVersion: clientSessionData.MeekProtocolVersion,
  461. sessionIDSent: false,
  462. cachedResponse: cachedResponse,
  463. }
  464. session.touch()
  465. // Create a new meek conn that will relay the payload
  466. // between meek request/responses and the tunnel server client
  467. // handler. The client IP is also used to initialize the
  468. // meek conn with a useful value to return when the tunnel
  469. // server calls conn.RemoteAddr() to get the client's IP address.
  470. // Assumes clientIP is a valid IP address; the port value is a stub
  471. // and is expected to be ignored.
  472. clientConn := newMeekConn(
  473. server,
  474. session,
  475. &net.TCPAddr{
  476. IP: net.ParseIP(clientIP),
  477. Port: 0,
  478. },
  479. clientSessionData.MeekProtocolVersion)
  480. session.clientConn = clientConn
  481. // Note: MEEK_PROTOCOL_VERSION_1 doesn't support changing the
  482. // meek cookie to a session ID; v1 clients always send the
  483. // original meek cookie value with each request. The issue with
  484. // v1 is that clients which wake after a device sleep will attempt
  485. // to resume a meek session and the server can't differentiate
  486. // between resuming a session and creating a new session. This
  487. // causes the v1 client connection to hang/timeout.
  488. sessionID := meekCookie.Value
  489. if clientSessionData.MeekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 {
  490. sessionID, err = makeMeekSessionID()
  491. if err != nil {
  492. return "", nil, common.ContextError(err)
  493. }
  494. }
  495. server.sessionsLock.Lock()
  496. server.sessions[sessionID] = session
  497. server.sessionsLock.Unlock()
  498. // Note: from the tunnel server's perspective, this client connection
  499. // will close when session.delete calls Close() on the meekConn.
  500. server.clientHandler(clientSessionData.ClientTunnelProtocol, session.clientConn)
  501. return sessionID, session, nil
  502. }
  503. func (server *MeekServer) deleteSession(sessionID string) {
  504. // Don't obtain the server.sessionsLock write lock until modifying
  505. // server.sessions, as the session.delete can block for up to
  506. // MEEK_HTTP_CLIENT_IO_TIMEOUT. Allow new sessions to be added
  507. // concurrently.
  508. //
  509. // Since a lock isn't held for the duration, concurrent calls to
  510. // deleteSession with the same sessionID could happen; this is
  511. // not expected since only the reaper goroutine calls deleteExpiredSessions
  512. // (and in any case concurrent execution of the ok block is not an issue).
  513. server.sessionsLock.RLock()
  514. session, ok := server.sessions[sessionID]
  515. server.sessionsLock.RUnlock()
  516. if ok {
  517. session.delete(false)
  518. server.sessionsLock.Lock()
  519. delete(server.sessions, sessionID)
  520. server.sessionsLock.Unlock()
  521. }
  522. }
  523. func (server *MeekServer) deleteExpiredSessions() {
  524. // A deleteSession call may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  525. // so grab a snapshot list of expired sessions and do not hold a lock for
  526. // the duration of deleteExpiredSessions. This allows new sessions to be
  527. // added concurrently.
  528. //
  529. // New sessions added after the snapshot is taken will be checked for
  530. // expiry on subsequent periodic calls to deleteExpiredSessions.
  531. //
  532. // To avoid long delays in releasing resources, individual deletes are
  533. // performed concurrently.
  534. server.sessionsLock.Lock()
  535. expiredSessionIDs := make([]string, 0)
  536. for sessionID, session := range server.sessions {
  537. if session.expired() {
  538. expiredSessionIDs = append(expiredSessionIDs, sessionID)
  539. }
  540. }
  541. server.sessionsLock.Unlock()
  542. start := monotime.Now()
  543. deleteWaitGroup := new(sync.WaitGroup)
  544. for _, sessionID := range expiredSessionIDs {
  545. deleteWaitGroup.Add(1)
  546. go func(sessionID string) {
  547. defer deleteWaitGroup.Done()
  548. server.deleteSession(sessionID)
  549. }(sessionID)
  550. }
  551. deleteWaitGroup.Wait()
  552. log.WithContextFields(
  553. LogFields{"elapsed time": monotime.Since(start)}).Debug("deleted expired sessions")
  554. }
  555. // httpConnStateCallback tracks open persistent HTTP/HTTPS connections to the
  556. // meek server.
  557. func (server *MeekServer) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  558. switch connState {
  559. case http.StateNew:
  560. server.openConns.Add(conn)
  561. case http.StateHijacked, http.StateClosed:
  562. server.openConns.Remove(conn)
  563. }
  564. }
  565. // terminateConnection sends a 404 response to a client and also closes
  566. // the persistent connection.
  567. func (server *MeekServer) terminateConnection(
  568. responseWriter http.ResponseWriter, request *http.Request) {
  569. http.NotFound(responseWriter, request)
  570. hijack, ok := responseWriter.(http.Hijacker)
  571. if !ok {
  572. return
  573. }
  574. conn, buffer, err := hijack.Hijack()
  575. if err != nil {
  576. return
  577. }
  578. buffer.Flush()
  579. conn.Close()
  580. }
  581. type meekSession struct {
  582. // Note: 64-bit ints used with atomic operations are placed
  583. // at the start of struct to ensure 64-bit alignment.
  584. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  585. lastActivity int64
  586. requestCount int64
  587. metricClientRetries int64
  588. metricPeakResponseSize int64
  589. metricPeakCachedResponseSize int64
  590. metricPeakCachedResponseHitSize int64
  591. metricCachedResponseMissPosition int64
  592. lock sync.Mutex
  593. deleted bool
  594. clientConn *meekConn
  595. meekProtocolVersion int
  596. sessionIDSent bool
  597. cachedResponse *CachedResponse
  598. }
  599. func (session *meekSession) touch() {
  600. atomic.StoreInt64(&session.lastActivity, int64(monotime.Now()))
  601. }
  602. func (session *meekSession) expired() bool {
  603. lastActivity := monotime.Time(atomic.LoadInt64(&session.lastActivity))
  604. return monotime.Since(lastActivity) > MEEK_MAX_SESSION_STALENESS
  605. }
  606. // delete releases all resources allocated by a session.
  607. func (session *meekSession) delete(haveLock bool) {
  608. // TODO: close the persistent HTTP client connection, if one exists?
  609. // This final call session.cachedResponse.Reset releases shared resources.
  610. //
  611. // This call requires exclusive access. session.lock is be obtained before
  612. // calling session.cachedResponse.Reset. Once the lock is obtained, no
  613. // request for this session is being processed concurrently, and pending
  614. // requests will block at session.lock.
  615. //
  616. // This logic assumes that no further session.cachedResponse access occurs,
  617. // or else resources may deplete (buffers won't be returned to the pool).
  618. // These requirements are achieved by obtaining the lock, setting
  619. // session.deleted, and any subsequent request handlers checking
  620. // session.deleted immediately after obtaining the lock.
  621. //
  622. // session.lock.Lock may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  623. // the timeout for any active request handler processing a session
  624. // request.
  625. //
  626. // When the lock must be acquired, clientConn.Close is called first, to
  627. // interrupt any existing request handler blocking on pumpReads or pumpWrites.
  628. session.clientConn.Close()
  629. if !haveLock {
  630. session.lock.Lock()
  631. }
  632. // Release all extended buffers back to the pool.
  633. // session.cachedResponse.Reset is not safe for concurrent calls.
  634. session.cachedResponse.Reset()
  635. session.deleted = true
  636. if !haveLock {
  637. session.lock.Unlock()
  638. }
  639. }
  640. // GetMetrics implements the MetricsSource interface.
  641. func (session *meekSession) GetMetrics() LogFields {
  642. logFields := make(LogFields)
  643. logFields["meek_client_retries"] = atomic.LoadInt64(&session.metricClientRetries)
  644. logFields["meek_peak_response_size"] = atomic.LoadInt64(&session.metricPeakResponseSize)
  645. logFields["meek_peak_cached_response_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseSize)
  646. logFields["meek_peak_cached_response_hit_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseHitSize)
  647. logFields["meek_cached_response_miss_position"] = atomic.LoadInt64(&session.metricCachedResponseMissPosition)
  648. return logFields
  649. }
  650. // makeMeekTLSConfig creates a TLS config for a meek HTTPS listener.
  651. // Currently, this config is optimized for fronted meek where the nature
  652. // of the connection is non-circumvention; it's optimized for performance
  653. // assuming the peer is an uncensored CDN.
  654. func makeMeekTLSConfig(
  655. support *SupportServices,
  656. useObfuscatedSessionTickets bool) (*tls.Config, error) {
  657. certificate, privateKey, err := GenerateWebServerCertificate(common.GenerateHostName())
  658. if err != nil {
  659. return nil, common.ContextError(err)
  660. }
  661. tlsCertificate, err := tls.X509KeyPair(
  662. []byte(certificate), []byte(privateKey))
  663. if err != nil {
  664. return nil, common.ContextError(err)
  665. }
  666. config := &tls.Config{
  667. Certificates: []tls.Certificate{tlsCertificate},
  668. NextProtos: []string{"http/1.1"},
  669. MinVersion: tls.VersionTLS10,
  670. // This is a reordering of the supported CipherSuites in golang 1.6. Non-ephemeral key
  671. // CipherSuites greatly reduce server load, and we try to select these since the meek
  672. // protocol is providing obfuscation, not privacy/integrity (this is provided by the
  673. // tunneled SSH), so we don't benefit from the perfect forward secrecy property provided
  674. // by ephemeral key CipherSuites.
  675. // https://github.com/golang/go/blob/1cb3044c9fcd88e1557eca1bf35845a4108bc1db/src/crypto/tls/cipher_suites.go#L75
  676. CipherSuites: []uint16{
  677. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  678. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  679. tls.TLS_RSA_WITH_RC4_128_SHA,
  680. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  681. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  682. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  683. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  684. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  685. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  686. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  687. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  688. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  689. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  690. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  691. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  692. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  693. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  694. },
  695. PreferServerCipherSuites: true,
  696. }
  697. if useObfuscatedSessionTickets {
  698. // See obfuscated session ticket overview
  699. // in tls.NewObfuscatedClientSessionCache
  700. var obfuscatedSessionTicketKey [32]byte
  701. key, err := hex.DecodeString(support.Config.MeekObfuscatedKey)
  702. if err == nil && len(key) != 32 {
  703. err = errors.New("invalid obfuscated session key length")
  704. }
  705. if err != nil {
  706. return nil, common.ContextError(err)
  707. }
  708. copy(obfuscatedSessionTicketKey[:], key)
  709. var standardSessionTicketKey [32]byte
  710. _, err = rand.Read(standardSessionTicketKey[:])
  711. if err != nil {
  712. return nil, common.ContextError(err)
  713. }
  714. // Note: SessionTicketKey needs to be set, or else, it appears,
  715. // tls.Config.serverInit() will clobber the value set by
  716. // SetSessionTicketKeys.
  717. config.SessionTicketKey = obfuscatedSessionTicketKey
  718. config.SetSessionTicketKeys([][32]byte{
  719. standardSessionTicketKey,
  720. obfuscatedSessionTicketKey})
  721. }
  722. return config, nil
  723. }
  724. // getMeekCookiePayload extracts the payload from a meek cookie. The cookie
  725. // paylod is base64 encoded, obfuscated, and NaCl encrypted.
  726. func getMeekCookiePayload(support *SupportServices, cookieValue string) ([]byte, error) {
  727. decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
  728. if err != nil {
  729. return nil, common.ContextError(err)
  730. }
  731. // The data consists of an obfuscated seed message prepended
  732. // to the obfuscated, encrypted payload. The server obfuscator
  733. // will read the seed message, leaving the remaining encrypted
  734. // data in the reader.
  735. reader := bytes.NewReader(decodedValue[:])
  736. obfuscator, err := common.NewServerObfuscator(
  737. reader,
  738. &common.ObfuscatorConfig{Keyword: support.Config.MeekObfuscatedKey})
  739. if err != nil {
  740. return nil, common.ContextError(err)
  741. }
  742. offset, err := reader.Seek(0, 1)
  743. if err != nil {
  744. return nil, common.ContextError(err)
  745. }
  746. encryptedPayload := decodedValue[offset:]
  747. obfuscator.ObfuscateClientToServer(encryptedPayload)
  748. var nonce [24]byte
  749. var privateKey, ephemeralPublicKey [32]byte
  750. decodedPrivateKey, err := base64.StdEncoding.DecodeString(
  751. support.Config.MeekCookieEncryptionPrivateKey)
  752. if err != nil {
  753. return nil, common.ContextError(err)
  754. }
  755. copy(privateKey[:], decodedPrivateKey)
  756. if len(encryptedPayload) < 32 {
  757. return nil, common.ContextError(errors.New("unexpected encrypted payload size"))
  758. }
  759. copy(ephemeralPublicKey[0:32], encryptedPayload[0:32])
  760. payload, ok := box.Open(nil, encryptedPayload[32:], &nonce, &ephemeralPublicKey, &privateKey)
  761. if !ok {
  762. return nil, common.ContextError(errors.New("open box failed"))
  763. }
  764. return payload, nil
  765. }
  766. // makeMeekSessionID creates a new session ID. The variable size is intended to
  767. // frustrate traffic analysis of both plaintext and TLS meek traffic.
  768. func makeMeekSessionID() (string, error) {
  769. size := MEEK_MIN_SESSION_ID_LENGTH
  770. n, err := common.MakeSecureRandomInt(MEEK_MAX_SESSION_ID_LENGTH - MEEK_MIN_SESSION_ID_LENGTH)
  771. if err != nil {
  772. return "", common.ContextError(err)
  773. }
  774. size += n
  775. sessionID, err := common.MakeRandomStringBase64(size)
  776. if err != nil {
  777. return "", common.ContextError(err)
  778. }
  779. return sessionID, nil
  780. }
  781. // meekConn implements the net.Conn interface and is to be used as a client
  782. // connection by the tunnel server (being passed to sshServer.handleClient).
  783. // meekConn bridges net/http request/response payload readers and writers
  784. // and goroutines calling Read()s and Write()s.
  785. type meekConn struct {
  786. meekServer *MeekServer
  787. meekSession *meekSession
  788. remoteAddr net.Addr
  789. protocolVersion int
  790. closeBroadcast chan struct{}
  791. closed int32
  792. lastReadChecksum *uint64
  793. readLock sync.Mutex
  794. emptyReadBuffer chan *bytes.Buffer
  795. partialReadBuffer chan *bytes.Buffer
  796. fullReadBuffer chan *bytes.Buffer
  797. writeLock sync.Mutex
  798. nextWriteBuffer chan []byte
  799. writeResult chan error
  800. }
  801. func newMeekConn(
  802. meekServer *MeekServer,
  803. meekSession *meekSession,
  804. remoteAddr net.Addr,
  805. protocolVersion int) *meekConn {
  806. conn := &meekConn{
  807. meekServer: meekServer,
  808. meekSession: meekSession,
  809. remoteAddr: remoteAddr,
  810. protocolVersion: protocolVersion,
  811. closeBroadcast: make(chan struct{}),
  812. closed: 0,
  813. emptyReadBuffer: make(chan *bytes.Buffer, 1),
  814. partialReadBuffer: make(chan *bytes.Buffer, 1),
  815. fullReadBuffer: make(chan *bytes.Buffer, 1),
  816. nextWriteBuffer: make(chan []byte, 1),
  817. writeResult: make(chan error, 1),
  818. }
  819. // Read() calls and pumpReads() are synchronized by exchanging control
  820. // of a single readBuffer. This is the same scheme used in and described
  821. // in psiphon.MeekConn.
  822. conn.emptyReadBuffer <- new(bytes.Buffer)
  823. return conn
  824. }
  825. // pumpReads causes goroutines blocking on meekConn.Read() to read
  826. // from the specified reader. This function blocks until the reader
  827. // is fully consumed or the meekConn is closed. A read buffer allows
  828. // up to MEEK_MAX_REQUEST_PAYLOAD_LENGTH bytes to be read and buffered
  829. // without a Read() immediately consuming the bytes, but there's still
  830. // a possibility of a stall if no Read() calls are made after this
  831. // read buffer is full.
  832. // Note: assumes only one concurrent call to pumpReads
  833. func (conn *meekConn) pumpReads(reader io.Reader) error {
  834. // Use either an empty or partial buffer. By using a partial
  835. // buffer, pumpReads will not block if the Read() caller has
  836. // not fully drained the read buffer.
  837. var readBuffer *bytes.Buffer
  838. select {
  839. case readBuffer = <-conn.emptyReadBuffer:
  840. case readBuffer = <-conn.partialReadBuffer:
  841. case <-conn.closeBroadcast:
  842. return io.EOF
  843. }
  844. newDataOffset := readBuffer.Len()
  845. // Since we need to read the full request payload in order to
  846. // take its checksum before relaying it, the read buffer can
  847. // grow to up to 2 x MEEK_MAX_REQUEST_PAYLOAD_LENGTH + 1.
  848. // +1 allows for an explicit check for request payloads that
  849. // exceed the maximum permitted length.
  850. limitReader := io.LimitReader(reader, MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1)
  851. n, err := readBuffer.ReadFrom(limitReader)
  852. if err == nil && n == MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1 {
  853. err = errors.New("invalid request payload length")
  854. }
  855. // If the request read fails, don't relay the new data. This allows
  856. // the client to retry and resend its request payload without
  857. // interrupting/duplicating the payload flow.
  858. if err != nil {
  859. readBuffer.Truncate(newDataOffset)
  860. conn.replaceReadBuffer(readBuffer)
  861. return common.ContextError(err)
  862. }
  863. // Check if request payload checksum matches immediately
  864. // previous payload. On match, assume this is a client retry
  865. // sending payload that was already relayed and skip this
  866. // payload. Payload is OSSH ciphertext and almost surely
  867. // will not repeat. In the highly unlikely case that it does,
  868. // the underlying SSH connection will fail and the client
  869. // must reconnect.
  870. checksum := crc64.Checksum(
  871. readBuffer.Bytes()[newDataOffset:], conn.meekServer.checksumTable)
  872. if conn.lastReadChecksum == nil {
  873. conn.lastReadChecksum = new(uint64)
  874. } else if *conn.lastReadChecksum == checksum {
  875. readBuffer.Truncate(newDataOffset)
  876. }
  877. *conn.lastReadChecksum = checksum
  878. conn.replaceReadBuffer(readBuffer)
  879. return nil
  880. }
  881. var errMeekConnectionHasClosed = errors.New("meek connection has closed")
  882. // Read reads from the meekConn into buffer. Read blocks until
  883. // some data is read or the meekConn closes. Under the hood, it
  884. // waits for pumpReads to submit a reader to read from.
  885. // Note: lock is to conform with net.Conn concurrency semantics
  886. func (conn *meekConn) Read(buffer []byte) (int, error) {
  887. conn.readLock.Lock()
  888. defer conn.readLock.Unlock()
  889. var readBuffer *bytes.Buffer
  890. select {
  891. case readBuffer = <-conn.partialReadBuffer:
  892. case readBuffer = <-conn.fullReadBuffer:
  893. case <-conn.closeBroadcast:
  894. return 0, common.ContextError(errMeekConnectionHasClosed)
  895. }
  896. n, err := readBuffer.Read(buffer)
  897. conn.replaceReadBuffer(readBuffer)
  898. return n, err
  899. }
  900. func (conn *meekConn) replaceReadBuffer(readBuffer *bytes.Buffer) {
  901. length := readBuffer.Len()
  902. if length >= MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  903. conn.fullReadBuffer <- readBuffer
  904. } else if length == 0 {
  905. conn.emptyReadBuffer <- readBuffer
  906. } else {
  907. conn.partialReadBuffer <- readBuffer
  908. }
  909. }
  910. // pumpWrites causes goroutines blocking on meekConn.Write() to write
  911. // to the specified writer. This function blocks until the meek response
  912. // body limits (size for protocol v1, turn around time for protocol v2+)
  913. // are met, or the meekConn is closed.
  914. // Note: channel scheme assumes only one concurrent call to pumpWrites
  915. func (conn *meekConn) pumpWrites(writer io.Writer) (int, error) {
  916. startTime := monotime.Now()
  917. timeout := time.NewTimer(MEEK_TURN_AROUND_TIMEOUT)
  918. defer timeout.Stop()
  919. n := 0
  920. for {
  921. select {
  922. case buffer := <-conn.nextWriteBuffer:
  923. written, err := writer.Write(buffer)
  924. n += written
  925. // Assumes that writeResult won't block.
  926. // Note: always send the err to writeResult,
  927. // as the Write() caller is blocking on this.
  928. conn.writeResult <- err
  929. if err != nil {
  930. return n, err
  931. }
  932. if conn.protocolVersion < MEEK_PROTOCOL_VERSION_1 {
  933. // Pre-protocol version 1 clients expect at most
  934. // MEEK_MAX_REQUEST_PAYLOAD_LENGTH response bodies
  935. return n, nil
  936. }
  937. totalElapsedTime := monotime.Since(startTime) / time.Millisecond
  938. if totalElapsedTime >= MEEK_EXTENDED_TURN_AROUND_TIMEOUT {
  939. return n, nil
  940. }
  941. timeout.Reset(MEEK_TURN_AROUND_TIMEOUT)
  942. case <-timeout.C:
  943. return n, nil
  944. case <-conn.closeBroadcast:
  945. return n, common.ContextError(errMeekConnectionHasClosed)
  946. }
  947. }
  948. }
  949. // Write writes the buffer to the meekConn. It blocks until the
  950. // entire buffer is written to or the meekConn closes. Under the
  951. // hood, it waits for sufficient pumpWrites calls to consume the
  952. // write buffer.
  953. // Note: lock is to conform with net.Conn concurrency semantics
  954. func (conn *meekConn) Write(buffer []byte) (int, error) {
  955. conn.writeLock.Lock()
  956. defer conn.writeLock.Unlock()
  957. // TODO: may be more efficient to send whole buffer
  958. // and have pumpWrites stash partial buffer when can't
  959. // send it all.
  960. n := 0
  961. for n < len(buffer) {
  962. end := n + MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  963. if end > len(buffer) {
  964. end = len(buffer)
  965. }
  966. // Only write MEEK_MAX_REQUEST_PAYLOAD_LENGTH at a time,
  967. // to ensure compatibility with v1 protocol.
  968. chunk := buffer[n:end]
  969. select {
  970. case conn.nextWriteBuffer <- chunk:
  971. case <-conn.closeBroadcast:
  972. return n, common.ContextError(errMeekConnectionHasClosed)
  973. }
  974. // Wait for the buffer to be processed.
  975. select {
  976. case _ = <-conn.writeResult:
  977. // The err from conn.writeResult comes from the
  978. // io.MultiWriter used in pumpWrites, which writes
  979. // to both the cached response and the HTTP response.
  980. //
  981. // Don't stop on error here, since only writing
  982. // to the HTTP response will fail, and the client
  983. // may retry and use the cached response.
  984. //
  985. // It's possible that the cached response buffer
  986. // is too small for the client to successfully
  987. // retry, but that cannot be determined. In this
  988. // case, the meek connection will eventually fail.
  989. //
  990. // err is already logged in ServeHTTP.
  991. case <-conn.closeBroadcast:
  992. return n, common.ContextError(errMeekConnectionHasClosed)
  993. }
  994. n += len(chunk)
  995. }
  996. return n, nil
  997. }
  998. // Close closes the meekConn. This will interrupt any blocked
  999. // Read, Write, pumpReads, and pumpWrites.
  1000. func (conn *meekConn) Close() error {
  1001. if atomic.CompareAndSwapInt32(&conn.closed, 0, 1) {
  1002. close(conn.closeBroadcast)
  1003. }
  1004. return nil
  1005. }
  1006. // Stub implementation of net.Conn.LocalAddr
  1007. func (conn *meekConn) LocalAddr() net.Addr {
  1008. return nil
  1009. }
  1010. // RemoteAddr returns the remoteAddr specified in newMeekConn. This
  1011. // acts as a proxy for the actual remote address, which is either a
  1012. // direct HTTP/HTTPS connection remote address, or in the case of
  1013. // downstream proxy of CDN fronts, some other value determined via
  1014. // HTTP headers.
  1015. func (conn *meekConn) RemoteAddr() net.Addr {
  1016. return conn.remoteAddr
  1017. }
  1018. // SetDeadline is not a true implementation of net.Conn.SetDeadline. It
  1019. // merely checks that the requested timeout exceeds the MEEK_MAX_SESSION_STALENESS
  1020. // period. When it does, and the session is idle, the meekConn Read/Write will
  1021. // be interrupted and return an error (not a timeout error) before the deadline.
  1022. // In other words, this conn will approximate the desired functionality of
  1023. // timing out on idle on or before the requested deadline.
  1024. func (conn *meekConn) SetDeadline(t time.Time) error {
  1025. // Overhead: nanoseconds (https://blog.cloudflare.com/its-go-time-on-linux/)
  1026. if time.Now().Add(MEEK_MAX_SESSION_STALENESS).Before(t) {
  1027. return nil
  1028. }
  1029. return common.ContextError(errors.New("not supported"))
  1030. }
  1031. // Stub implementation of net.Conn.SetReadDeadline
  1032. func (conn *meekConn) SetReadDeadline(t time.Time) error {
  1033. return common.ContextError(errors.New("not supported"))
  1034. }
  1035. // Stub implementation of net.Conn.SetWriteDeadline
  1036. func (conn *meekConn) SetWriteDeadline(t time.Time) error {
  1037. return common.ContextError(errors.New("not supported"))
  1038. }
  1039. // GetMetrics implements the MetricsSource interface. The metrics are maintained
  1040. // in the meek session type; but logTunnel, which calls MetricsSource.GetMetrics,
  1041. // has a pointer only to this conn, so it calls through to the session.
  1042. func (conn *meekConn) GetMetrics() LogFields {
  1043. return conn.meekSession.GetMetrics()
  1044. }