meek.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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. // TODO: can multiple http client connections using same session cookie
  412. // cause race conditions on session struct?
  413. // The session is new (or expired). Treat the cookie value as a new meek
  414. // cookie, extract the payload, and create a new session.
  415. payloadJSON, err := getMeekCookiePayload(server.support, meekCookie.Value)
  416. if err != nil {
  417. return "", nil, common.ContextError(err)
  418. }
  419. // Note: this meek server ignores legacy values PsiphonClientSessionId
  420. // and PsiphonServerAddress.
  421. var clientSessionData protocol.MeekCookieData
  422. err = json.Unmarshal(payloadJSON, &clientSessionData)
  423. if err != nil {
  424. return "", nil, common.ContextError(err)
  425. }
  426. // Determine the client remote address, which is used for geolocation
  427. // and stats. When an intermediate proxy or CDN is in use, we may be
  428. // able to determine the original client address by inspecting HTTP
  429. // headers such as X-Forwarded-For.
  430. clientIP := strings.Split(request.RemoteAddr, ":")[0]
  431. if len(server.support.Config.MeekProxyForwardedForHeaders) > 0 {
  432. for _, header := range server.support.Config.MeekProxyForwardedForHeaders {
  433. value := request.Header.Get(header)
  434. if len(value) > 0 {
  435. // Some headers, such as X-Forwarded-For, are a comma-separated
  436. // list of IPs (each proxy in a chain). The first IP should be
  437. // the client IP.
  438. proxyClientIP := strings.Split(value, ",")[0]
  439. if net.ParseIP(proxyClientIP) != nil &&
  440. server.support.GeoIPService.Lookup(proxyClientIP).Country != GEOIP_UNKNOWN_VALUE {
  441. clientIP = proxyClientIP
  442. break
  443. }
  444. }
  445. }
  446. }
  447. // Create a new session
  448. bufferLength := MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH
  449. if server.support.Config.MeekCachedResponseBufferSize != 0 {
  450. bufferLength = server.support.Config.MeekCachedResponseBufferSize
  451. }
  452. cachedResponse := NewCachedResponse(bufferLength, server.bufferPool)
  453. session = &meekSession{
  454. meekProtocolVersion: clientSessionData.MeekProtocolVersion,
  455. sessionIDSent: false,
  456. cachedResponse: cachedResponse,
  457. }
  458. session.touch()
  459. // Create a new meek conn that will relay the payload
  460. // between meek request/responses and the tunnel server client
  461. // handler. The client IP is also used to initialize the
  462. // meek conn with a useful value to return when the tunnel
  463. // server calls conn.RemoteAddr() to get the client's IP address.
  464. // Assumes clientIP is a valid IP address; the port value is a stub
  465. // and is expected to be ignored.
  466. clientConn := newMeekConn(
  467. server,
  468. session,
  469. &net.TCPAddr{
  470. IP: net.ParseIP(clientIP),
  471. Port: 0,
  472. },
  473. clientSessionData.MeekProtocolVersion)
  474. session.clientConn = clientConn
  475. // Note: MEEK_PROTOCOL_VERSION_1 doesn't support changing the
  476. // meek cookie to a session ID; v1 clients always send the
  477. // original meek cookie value with each request. The issue with
  478. // v1 is that clients which wake after a device sleep will attempt
  479. // to resume a meek session and the server can't differentiate
  480. // between resuming a session and creating a new session. This
  481. // causes the v1 client connection to hang/timeout.
  482. sessionID := meekCookie.Value
  483. if clientSessionData.MeekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 {
  484. sessionID, err = makeMeekSessionID()
  485. if err != nil {
  486. return "", nil, common.ContextError(err)
  487. }
  488. }
  489. server.sessionsLock.Lock()
  490. server.sessions[sessionID] = session
  491. server.sessionsLock.Unlock()
  492. // Note: from the tunnel server's perspective, this client connection
  493. // will close when session.delete calls Close() on the meekConn.
  494. server.clientHandler(clientSessionData.ClientTunnelProtocol, session.clientConn)
  495. return sessionID, session, nil
  496. }
  497. func (server *MeekServer) deleteSession(sessionID string) {
  498. // Don't obtain the server.sessionsLock write lock until modifying
  499. // server.sessions, as the session.delete can block for up to
  500. // MEEK_HTTP_CLIENT_IO_TIMEOUT. Allow new sessions to be added
  501. // concurrently.
  502. //
  503. // Since a lock isn't held for the duration, concurrent calls to
  504. // deleteSession with the same sessionID could happen; this is
  505. // not expected since only the reaper goroutine calls deleteExpiredSessions
  506. // (and in any case concurrent execution of the ok block is not an issue).
  507. server.sessionsLock.RLock()
  508. session, ok := server.sessions[sessionID]
  509. server.sessionsLock.RUnlock()
  510. if ok {
  511. session.delete(false)
  512. server.sessionsLock.Lock()
  513. delete(server.sessions, sessionID)
  514. server.sessionsLock.Unlock()
  515. }
  516. }
  517. func (server *MeekServer) deleteExpiredSessions() {
  518. // A deleteSession call may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  519. // so grab a snapshot list of expired sessions and do not hold a lock for
  520. // the duration of deleteExpiredSessions. This allows new sessions to be
  521. // added concurrently.
  522. //
  523. // New sessions added after the snapshot is taken will be checked for
  524. // expiry on subsequent periodic calls to deleteExpiredSessions.
  525. //
  526. // To avoid long delays in releasing resources, individual deletes are
  527. // performed concurrently.
  528. server.sessionsLock.Lock()
  529. expiredSessionIDs := make([]string, 0)
  530. for sessionID, session := range server.sessions {
  531. if session.expired() {
  532. expiredSessionIDs = append(expiredSessionIDs, sessionID)
  533. }
  534. }
  535. server.sessionsLock.Unlock()
  536. start := monotime.Now()
  537. deleteWaitGroup := new(sync.WaitGroup)
  538. for _, sessionID := range expiredSessionIDs {
  539. deleteWaitGroup.Add(1)
  540. go func(sessionID string) {
  541. defer deleteWaitGroup.Done()
  542. server.deleteSession(sessionID)
  543. }(sessionID)
  544. }
  545. deleteWaitGroup.Wait()
  546. log.WithContextFields(
  547. LogFields{"elapsed time": monotime.Since(start)}).Debug("deleted expired sessions")
  548. }
  549. // httpConnStateCallback tracks open persistent HTTP/HTTPS connections to the
  550. // meek server.
  551. func (server *MeekServer) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  552. switch connState {
  553. case http.StateNew:
  554. server.openConns.Add(conn)
  555. case http.StateHijacked, http.StateClosed:
  556. server.openConns.Remove(conn)
  557. }
  558. }
  559. // terminateConnection sends a 404 response to a client and also closes
  560. // the persistent connection.
  561. func (server *MeekServer) terminateConnection(
  562. responseWriter http.ResponseWriter, request *http.Request) {
  563. http.NotFound(responseWriter, request)
  564. hijack, ok := responseWriter.(http.Hijacker)
  565. if !ok {
  566. return
  567. }
  568. conn, buffer, err := hijack.Hijack()
  569. if err != nil {
  570. return
  571. }
  572. buffer.Flush()
  573. conn.Close()
  574. }
  575. type meekSession struct {
  576. // Note: 64-bit ints used with atomic operations are placed
  577. // at the start of struct to ensure 64-bit alignment.
  578. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  579. lastActivity int64
  580. requestCount int64
  581. metricClientRetries int64
  582. metricPeakResponseSize int64
  583. metricPeakCachedResponseSize int64
  584. metricPeakCachedResponseHitSize int64
  585. metricCachedResponseMissPosition int64
  586. lock sync.Mutex
  587. deleted bool
  588. clientConn *meekConn
  589. meekProtocolVersion int
  590. sessionIDSent bool
  591. cachedResponse *CachedResponse
  592. }
  593. func (session *meekSession) touch() {
  594. atomic.StoreInt64(&session.lastActivity, int64(monotime.Now()))
  595. }
  596. func (session *meekSession) expired() bool {
  597. lastActivity := monotime.Time(atomic.LoadInt64(&session.lastActivity))
  598. return monotime.Since(lastActivity) > MEEK_MAX_SESSION_STALENESS
  599. }
  600. // delete releases all resources allocated by a session.
  601. func (session *meekSession) delete(haveLock bool) {
  602. // TODO: close the persistent HTTP client connection, if one exists?
  603. // This final call session.cachedResponse.Reset releases shared resources.
  604. //
  605. // This call requires exclusive access. session.lock is be obtained before
  606. // calling session.cachedResponse.Reset. Once the lock is obtained, no
  607. // request for this session is being processed concurrently, and pending
  608. // requests will block at session.lock.
  609. //
  610. // This logic assumes that no further session.cachedResponse access occurs,
  611. // or else resources may deplete (buffers won't be returned to the pool).
  612. // These requirements are achieved by obtaining the lock, setting
  613. // session.deleted, and any subsequent request handlers checking
  614. // session.deleted immediately after obtaining the lock.
  615. //
  616. // session.lock.Lock may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  617. // the timeout for any active request handler processing a session
  618. // request.
  619. //
  620. // When the lock must be acquired, clientConn.Close is called first, to
  621. // interrupt any existing request handler blocking on pumpReads or pumpWrites.
  622. session.clientConn.Close()
  623. if !haveLock {
  624. session.lock.Lock()
  625. }
  626. // Release all extended buffers back to the pool.
  627. // session.cachedResponse.Reset is not safe for concurrent calls.
  628. session.cachedResponse.Reset()
  629. session.deleted = true
  630. if !haveLock {
  631. session.lock.Unlock()
  632. }
  633. }
  634. // GetMetrics implements the MetricsSource interface.
  635. func (session *meekSession) GetMetrics() LogFields {
  636. logFields := make(LogFields)
  637. logFields["meek_client_retries"] = atomic.LoadInt64(&session.metricClientRetries)
  638. logFields["meek_peak_response_size"] = atomic.LoadInt64(&session.metricPeakResponseSize)
  639. logFields["meek_peak_cached_response_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseSize)
  640. logFields["meek_peak_cached_response_hit_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseHitSize)
  641. logFields["meek_cached_response_miss_position"] = atomic.LoadInt64(&session.metricCachedResponseMissPosition)
  642. return logFields
  643. }
  644. // makeMeekTLSConfig creates a TLS config for a meek HTTPS listener.
  645. // Currently, this config is optimized for fronted meek where the nature
  646. // of the connection is non-circumvention; it's optimized for performance
  647. // assuming the peer is an uncensored CDN.
  648. func makeMeekTLSConfig(
  649. support *SupportServices,
  650. useObfuscatedSessionTickets bool) (*tls.Config, error) {
  651. certificate, privateKey, err := GenerateWebServerCertificate(common.GenerateHostName())
  652. if err != nil {
  653. return nil, common.ContextError(err)
  654. }
  655. tlsCertificate, err := tls.X509KeyPair(
  656. []byte(certificate), []byte(privateKey))
  657. if err != nil {
  658. return nil, common.ContextError(err)
  659. }
  660. config := &tls.Config{
  661. Certificates: []tls.Certificate{tlsCertificate},
  662. NextProtos: []string{"http/1.1"},
  663. MinVersion: tls.VersionTLS10,
  664. // This is a reordering of the supported CipherSuites in golang 1.6. Non-ephemeral key
  665. // CipherSuites greatly reduce server load, and we try to select these since the meek
  666. // protocol is providing obfuscation, not privacy/integrity (this is provided by the
  667. // tunneled SSH), so we don't benefit from the perfect forward secrecy property provided
  668. // by ephemeral key CipherSuites.
  669. // https://github.com/golang/go/blob/1cb3044c9fcd88e1557eca1bf35845a4108bc1db/src/crypto/tls/cipher_suites.go#L75
  670. CipherSuites: []uint16{
  671. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  672. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  673. tls.TLS_RSA_WITH_RC4_128_SHA,
  674. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  675. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  676. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  677. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  678. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  679. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  680. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  681. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  682. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  683. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  684. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  685. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  686. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  687. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  688. },
  689. PreferServerCipherSuites: true,
  690. }
  691. if useObfuscatedSessionTickets {
  692. // See obfuscated session ticket overview
  693. // in tls.NewObfuscatedClientSessionCache
  694. var obfuscatedSessionTicketKey [32]byte
  695. key, err := hex.DecodeString(support.Config.MeekObfuscatedKey)
  696. if err == nil && len(key) != 32 {
  697. err = errors.New("invalid obfuscated session key length")
  698. }
  699. if err != nil {
  700. return nil, common.ContextError(err)
  701. }
  702. copy(obfuscatedSessionTicketKey[:], key)
  703. var standardSessionTicketKey [32]byte
  704. _, err = rand.Read(standardSessionTicketKey[:])
  705. if err != nil {
  706. return nil, common.ContextError(err)
  707. }
  708. // Note: SessionTicketKey needs to be set, or else, it appears,
  709. // tls.Config.serverInit() will clobber the value set by
  710. // SetSessionTicketKeys.
  711. config.SessionTicketKey = obfuscatedSessionTicketKey
  712. config.SetSessionTicketKeys([][32]byte{
  713. standardSessionTicketKey,
  714. obfuscatedSessionTicketKey})
  715. }
  716. return config, nil
  717. }
  718. // getMeekCookiePayload extracts the payload from a meek cookie. The cookie
  719. // paylod is base64 encoded, obfuscated, and NaCl encrypted.
  720. func getMeekCookiePayload(support *SupportServices, cookieValue string) ([]byte, error) {
  721. decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
  722. if err != nil {
  723. return nil, common.ContextError(err)
  724. }
  725. // The data consists of an obfuscated seed message prepended
  726. // to the obfuscated, encrypted payload. The server obfuscator
  727. // will read the seed message, leaving the remaining encrypted
  728. // data in the reader.
  729. reader := bytes.NewReader(decodedValue[:])
  730. obfuscator, err := common.NewServerObfuscator(
  731. reader,
  732. &common.ObfuscatorConfig{Keyword: support.Config.MeekObfuscatedKey})
  733. if err != nil {
  734. return nil, common.ContextError(err)
  735. }
  736. offset, err := reader.Seek(0, 1)
  737. if err != nil {
  738. return nil, common.ContextError(err)
  739. }
  740. encryptedPayload := decodedValue[offset:]
  741. obfuscator.ObfuscateClientToServer(encryptedPayload)
  742. var nonce [24]byte
  743. var privateKey, ephemeralPublicKey [32]byte
  744. decodedPrivateKey, err := base64.StdEncoding.DecodeString(
  745. support.Config.MeekCookieEncryptionPrivateKey)
  746. if err != nil {
  747. return nil, common.ContextError(err)
  748. }
  749. copy(privateKey[:], decodedPrivateKey)
  750. if len(encryptedPayload) < 32 {
  751. return nil, common.ContextError(errors.New("unexpected encrypted payload size"))
  752. }
  753. copy(ephemeralPublicKey[0:32], encryptedPayload[0:32])
  754. payload, ok := box.Open(nil, encryptedPayload[32:], &nonce, &ephemeralPublicKey, &privateKey)
  755. if !ok {
  756. return nil, common.ContextError(errors.New("open box failed"))
  757. }
  758. return payload, nil
  759. }
  760. // makeMeekSessionID creates a new session ID. The variable size is intended to
  761. // frustrate traffic analysis of both plaintext and TLS meek traffic.
  762. func makeMeekSessionID() (string, error) {
  763. size := MEEK_MIN_SESSION_ID_LENGTH
  764. n, err := common.MakeSecureRandomInt(MEEK_MAX_SESSION_ID_LENGTH - MEEK_MIN_SESSION_ID_LENGTH)
  765. if err != nil {
  766. return "", common.ContextError(err)
  767. }
  768. size += n
  769. sessionID, err := common.MakeRandomStringBase64(size)
  770. if err != nil {
  771. return "", common.ContextError(err)
  772. }
  773. return sessionID, nil
  774. }
  775. // meekConn implements the net.Conn interface and is to be used as a client
  776. // connection by the tunnel server (being passed to sshServer.handleClient).
  777. // meekConn bridges net/http request/response payload readers and writers
  778. // and goroutines calling Read()s and Write()s.
  779. type meekConn struct {
  780. meekServer *MeekServer
  781. meekSession *meekSession
  782. remoteAddr net.Addr
  783. protocolVersion int
  784. closeBroadcast chan struct{}
  785. closed int32
  786. lastReadChecksum *uint64
  787. readLock sync.Mutex
  788. emptyReadBuffer chan *bytes.Buffer
  789. partialReadBuffer chan *bytes.Buffer
  790. fullReadBuffer chan *bytes.Buffer
  791. writeLock sync.Mutex
  792. nextWriteBuffer chan []byte
  793. writeResult chan error
  794. }
  795. func newMeekConn(
  796. meekServer *MeekServer,
  797. meekSession *meekSession,
  798. remoteAddr net.Addr,
  799. protocolVersion int) *meekConn {
  800. conn := &meekConn{
  801. meekServer: meekServer,
  802. meekSession: meekSession,
  803. remoteAddr: remoteAddr,
  804. protocolVersion: protocolVersion,
  805. closeBroadcast: make(chan struct{}),
  806. closed: 0,
  807. emptyReadBuffer: make(chan *bytes.Buffer, 1),
  808. partialReadBuffer: make(chan *bytes.Buffer, 1),
  809. fullReadBuffer: make(chan *bytes.Buffer, 1),
  810. nextWriteBuffer: make(chan []byte, 1),
  811. writeResult: make(chan error, 1),
  812. }
  813. // Read() calls and pumpReads() are synchronized by exchanging control
  814. // of a single readBuffer. This is the same scheme used in and described
  815. // in psiphon.MeekConn.
  816. conn.emptyReadBuffer <- new(bytes.Buffer)
  817. return conn
  818. }
  819. // pumpReads causes goroutines blocking on meekConn.Read() to read
  820. // from the specified reader. This function blocks until the reader
  821. // is fully consumed or the meekConn is closed. A read buffer allows
  822. // up to MEEK_MAX_REQUEST_PAYLOAD_LENGTH bytes to be read and buffered
  823. // without a Read() immediately consuming the bytes, but there's still
  824. // a possibility of a stall if no Read() calls are made after this
  825. // read buffer is full.
  826. // Note: assumes only one concurrent call to pumpReads
  827. func (conn *meekConn) pumpReads(reader io.Reader) error {
  828. // Use either an empty or partial buffer. By using a partial
  829. // buffer, pumpReads will not block if the Read() caller has
  830. // not fully drained the read buffer.
  831. var readBuffer *bytes.Buffer
  832. select {
  833. case readBuffer = <-conn.emptyReadBuffer:
  834. case readBuffer = <-conn.partialReadBuffer:
  835. case <-conn.closeBroadcast:
  836. return io.EOF
  837. }
  838. newDataOffset := readBuffer.Len()
  839. // Since we need to read the full request payload in order to
  840. // take its checksum before relaying it, the read buffer can
  841. // grow to up to 2 x MEEK_MAX_REQUEST_PAYLOAD_LENGTH + 1.
  842. // +1 allows for an explicit check for request payloads that
  843. // exceed the maximum permitted length.
  844. limitReader := io.LimitReader(reader, MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1)
  845. n, err := readBuffer.ReadFrom(limitReader)
  846. if err == nil && n == MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1 {
  847. err = errors.New("invalid request payload length")
  848. }
  849. // If the request read fails, don't relay the new data. This allows
  850. // the client to retry and resend its request payload without
  851. // interrupting/duplicating the payload flow.
  852. if err != nil {
  853. readBuffer.Truncate(newDataOffset)
  854. conn.replaceReadBuffer(readBuffer)
  855. return common.ContextError(err)
  856. }
  857. // Check if request payload checksum matches immediately
  858. // previous payload. On match, assume this is a client retry
  859. // sending payload that was already relayed and skip this
  860. // payload. Payload is OSSH ciphertext and almost surely
  861. // will not repeat. In the highly unlikely case that it does,
  862. // the underlying SSH connection will fail and the client
  863. // must reconnect.
  864. checksum := crc64.Checksum(
  865. readBuffer.Bytes()[newDataOffset:], conn.meekServer.checksumTable)
  866. if conn.lastReadChecksum == nil {
  867. conn.lastReadChecksum = new(uint64)
  868. } else if *conn.lastReadChecksum == checksum {
  869. readBuffer.Truncate(newDataOffset)
  870. }
  871. *conn.lastReadChecksum = checksum
  872. conn.replaceReadBuffer(readBuffer)
  873. return nil
  874. }
  875. var errMeekConnectionHasClosed = errors.New("meek connection has closed")
  876. // Read reads from the meekConn into buffer. Read blocks until
  877. // some data is read or the meekConn closes. Under the hood, it
  878. // waits for pumpReads to submit a reader to read from.
  879. // Note: lock is to conform with net.Conn concurrency semantics
  880. func (conn *meekConn) Read(buffer []byte) (int, error) {
  881. conn.readLock.Lock()
  882. defer conn.readLock.Unlock()
  883. var readBuffer *bytes.Buffer
  884. select {
  885. case readBuffer = <-conn.partialReadBuffer:
  886. case readBuffer = <-conn.fullReadBuffer:
  887. case <-conn.closeBroadcast:
  888. return 0, common.ContextError(errMeekConnectionHasClosed)
  889. }
  890. n, err := readBuffer.Read(buffer)
  891. conn.replaceReadBuffer(readBuffer)
  892. return n, err
  893. }
  894. func (conn *meekConn) replaceReadBuffer(readBuffer *bytes.Buffer) {
  895. length := readBuffer.Len()
  896. if length >= MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  897. conn.fullReadBuffer <- readBuffer
  898. } else if length == 0 {
  899. conn.emptyReadBuffer <- readBuffer
  900. } else {
  901. conn.partialReadBuffer <- readBuffer
  902. }
  903. }
  904. // pumpWrites causes goroutines blocking on meekConn.Write() to write
  905. // to the specified writer. This function blocks until the meek response
  906. // body limits (size for protocol v1, turn around time for protocol v2+)
  907. // are met, or the meekConn is closed.
  908. // Note: channel scheme assumes only one concurrent call to pumpWrites
  909. func (conn *meekConn) pumpWrites(writer io.Writer) (int, error) {
  910. startTime := monotime.Now()
  911. timeout := time.NewTimer(MEEK_TURN_AROUND_TIMEOUT)
  912. defer timeout.Stop()
  913. n := 0
  914. for {
  915. select {
  916. case buffer := <-conn.nextWriteBuffer:
  917. written, err := writer.Write(buffer)
  918. n += written
  919. // Assumes that writeResult won't block.
  920. // Note: always send the err to writeResult,
  921. // as the Write() caller is blocking on this.
  922. conn.writeResult <- err
  923. if err != nil {
  924. return n, err
  925. }
  926. if conn.protocolVersion < MEEK_PROTOCOL_VERSION_1 {
  927. // Pre-protocol version 1 clients expect at most
  928. // MEEK_MAX_REQUEST_PAYLOAD_LENGTH response bodies
  929. return n, nil
  930. }
  931. totalElapsedTime := monotime.Since(startTime) / time.Millisecond
  932. if totalElapsedTime >= MEEK_EXTENDED_TURN_AROUND_TIMEOUT {
  933. return n, nil
  934. }
  935. timeout.Reset(MEEK_TURN_AROUND_TIMEOUT)
  936. case <-timeout.C:
  937. return n, nil
  938. case <-conn.closeBroadcast:
  939. return n, common.ContextError(errMeekConnectionHasClosed)
  940. }
  941. }
  942. }
  943. // Write writes the buffer to the meekConn. It blocks until the
  944. // entire buffer is written to or the meekConn closes. Under the
  945. // hood, it waits for sufficient pumpWrites calls to consume the
  946. // write buffer.
  947. // Note: lock is to conform with net.Conn concurrency semantics
  948. func (conn *meekConn) Write(buffer []byte) (int, error) {
  949. conn.writeLock.Lock()
  950. defer conn.writeLock.Unlock()
  951. // TODO: may be more efficient to send whole buffer
  952. // and have pumpWrites stash partial buffer when can't
  953. // send it all.
  954. n := 0
  955. for n < len(buffer) {
  956. end := n + MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  957. if end > len(buffer) {
  958. end = len(buffer)
  959. }
  960. // Only write MEEK_MAX_REQUEST_PAYLOAD_LENGTH at a time,
  961. // to ensure compatibility with v1 protocol.
  962. chunk := buffer[n:end]
  963. select {
  964. case conn.nextWriteBuffer <- chunk:
  965. case <-conn.closeBroadcast:
  966. return n, common.ContextError(errMeekConnectionHasClosed)
  967. }
  968. // Wait for the buffer to be processed.
  969. select {
  970. case _ = <-conn.writeResult:
  971. // The err from conn.writeResult comes from the
  972. // io.MultiWriter used in pumpWrites, which writes
  973. // to both the cached response and the HTTP response.
  974. //
  975. // Don't stop on error here, since only writing
  976. // to the HTTP response will fail, and the client
  977. // may retry and use the cached response.
  978. //
  979. // It's possible that the cached response buffer
  980. // is too small for the client to successfully
  981. // retry, but that cannot be determined. In this
  982. // case, the meek connection will eventually fail.
  983. //
  984. // err is already logged in ServeHTTP.
  985. case <-conn.closeBroadcast:
  986. return n, common.ContextError(errMeekConnectionHasClosed)
  987. }
  988. n += len(chunk)
  989. }
  990. return n, nil
  991. }
  992. // Close closes the meekConn. This will interrupt any blocked
  993. // Read, Write, pumpReads, and pumpWrites.
  994. func (conn *meekConn) Close() error {
  995. if atomic.CompareAndSwapInt32(&conn.closed, 0, 1) {
  996. close(conn.closeBroadcast)
  997. }
  998. return nil
  999. }
  1000. // Stub implementation of net.Conn.LocalAddr
  1001. func (conn *meekConn) LocalAddr() net.Addr {
  1002. return nil
  1003. }
  1004. // RemoteAddr returns the remoteAddr specified in newMeekConn. This
  1005. // acts as a proxy for the actual remote address, which is either a
  1006. // direct HTTP/HTTPS connection remote address, or in the case of
  1007. // downstream proxy of CDN fronts, some other value determined via
  1008. // HTTP headers.
  1009. func (conn *meekConn) RemoteAddr() net.Addr {
  1010. return conn.remoteAddr
  1011. }
  1012. // SetDeadline is not a true implementation of net.Conn.SetDeadline. It
  1013. // merely checks that the requested timeout exceeds the MEEK_MAX_SESSION_STALENESS
  1014. // period. When it does, and the session is idle, the meekConn Read/Write will
  1015. // be interrupted and return an error (not a timeout error) before the deadline.
  1016. // In other words, this conn will approximate the desired functionality of
  1017. // timing out on idle on or before the requested deadline.
  1018. func (conn *meekConn) SetDeadline(t time.Time) error {
  1019. // Overhead: nanoseconds (https://blog.cloudflare.com/its-go-time-on-linux/)
  1020. if time.Now().Add(MEEK_MAX_SESSION_STALENESS).Before(t) {
  1021. return nil
  1022. }
  1023. return common.ContextError(errors.New("not supported"))
  1024. }
  1025. // Stub implementation of net.Conn.SetReadDeadline
  1026. func (conn *meekConn) SetReadDeadline(t time.Time) error {
  1027. return common.ContextError(errors.New("not supported"))
  1028. }
  1029. // Stub implementation of net.Conn.SetWriteDeadline
  1030. func (conn *meekConn) SetWriteDeadline(t time.Time) error {
  1031. return common.ContextError(errors.New("not supported"))
  1032. }
  1033. // GetMetrics implements the MetricsSource interface. The metrics are maintained
  1034. // in the meek session type; but logTunnel, which calls MetricsSource.GetMetrics,
  1035. // has a pointer only to this conn, so it calls through to the session.
  1036. func (conn *meekConn) GetMetrics() LogFields {
  1037. return conn.meekSession.GetMetrics()
  1038. }