meek.go 43 KB

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