reverse.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package proxy
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "log"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "strings"
  25. "sync/atomic"
  26. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  27. )
  28. // Hop-by-hop headers. These are removed when sent to the backend.
  29. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  30. // This list of headers borrowed from stdlib httputil.ReverseProxy
  31. var singleHopHeaders = []string{
  32. "Connection",
  33. "Keep-Alive",
  34. "Proxy-Authenticate",
  35. "Proxy-Authorization",
  36. "Te", // canonicalized version of "TE"
  37. "Trailers",
  38. "Transfer-Encoding",
  39. "Upgrade",
  40. }
  41. func removeSingleHopHeaders(hdrs *http.Header) {
  42. for _, h := range singleHopHeaders {
  43. hdrs.Del(h)
  44. }
  45. }
  46. type reverseProxy struct {
  47. director *director
  48. transport http.RoundTripper
  49. }
  50. func (p *reverseProxy) ServeHTTP(rw http.ResponseWriter, clientreq *http.Request) {
  51. proxyreq := new(http.Request)
  52. *proxyreq = *clientreq
  53. var (
  54. proxybody []byte
  55. err error
  56. )
  57. if clientreq.Body != nil {
  58. proxybody, err = ioutil.ReadAll(clientreq.Body)
  59. if err != nil {
  60. msg := fmt.Sprintf("proxy: failed to read request body: %v", err)
  61. e := httptypes.NewHTTPError(http.StatusInternalServerError, msg)
  62. e.WriteTo(rw)
  63. return
  64. }
  65. }
  66. // deep-copy the headers, as these will be modified below
  67. proxyreq.Header = make(http.Header)
  68. copyHeader(proxyreq.Header, clientreq.Header)
  69. normalizeRequest(proxyreq)
  70. removeSingleHopHeaders(&proxyreq.Header)
  71. maybeSetForwardedFor(proxyreq)
  72. endpoints := p.director.endpoints()
  73. if len(endpoints) == 0 {
  74. msg := "proxy: zero endpoints currently available"
  75. // TODO: limit the rate of the error logging.
  76. log.Printf(msg)
  77. e := httptypes.NewHTTPError(http.StatusServiceUnavailable, msg)
  78. e.WriteTo(rw)
  79. return
  80. }
  81. var requestClosed int32
  82. completeCh := make(chan bool, 1)
  83. closeNotifier, ok := rw.(http.CloseNotifier)
  84. if ok {
  85. go func() {
  86. select {
  87. case <-closeNotifier.CloseNotify():
  88. atomic.StoreInt32(&requestClosed, 1)
  89. log.Printf("proxy: client %v closed request prematurely", clientreq.RemoteAddr)
  90. tp, ok := p.transport.(*http.Transport)
  91. if ok {
  92. tp.CancelRequest(proxyreq)
  93. }
  94. case <-completeCh:
  95. }
  96. }()
  97. defer func() {
  98. completeCh <- true
  99. }()
  100. }
  101. var res *http.Response
  102. for _, ep := range endpoints {
  103. if proxybody != nil {
  104. proxyreq.Body = ioutil.NopCloser(bytes.NewBuffer(proxybody))
  105. }
  106. redirectRequest(proxyreq, ep.URL)
  107. res, err = p.transport.RoundTrip(proxyreq)
  108. if atomic.LoadInt32(&requestClosed) == 1 {
  109. return
  110. }
  111. if err != nil {
  112. log.Printf("proxy: failed to direct request to %s: %v", ep.URL.String(), err)
  113. ep.Failed()
  114. continue
  115. }
  116. break
  117. }
  118. if res == nil {
  119. // TODO: limit the rate of the error logging.
  120. msg := fmt.Sprintf("proxy: unable to get response from %d endpoint(s)", len(endpoints))
  121. log.Printf(msg)
  122. e := httptypes.NewHTTPError(http.StatusBadGateway, msg)
  123. e.WriteTo(rw)
  124. return
  125. }
  126. defer res.Body.Close()
  127. removeSingleHopHeaders(&res.Header)
  128. copyHeader(rw.Header(), res.Header)
  129. rw.WriteHeader(res.StatusCode)
  130. io.Copy(rw, res.Body)
  131. }
  132. func copyHeader(dst, src http.Header) {
  133. for k, vv := range src {
  134. for _, v := range vv {
  135. dst.Add(k, v)
  136. }
  137. }
  138. }
  139. func redirectRequest(req *http.Request, loc url.URL) {
  140. req.URL.Scheme = loc.Scheme
  141. req.URL.Host = loc.Host
  142. }
  143. func normalizeRequest(req *http.Request) {
  144. req.Proto = "HTTP/1.1"
  145. req.ProtoMajor = 1
  146. req.ProtoMinor = 1
  147. req.Close = false
  148. }
  149. func maybeSetForwardedFor(req *http.Request) {
  150. clientIP, _, err := net.SplitHostPort(req.RemoteAddr)
  151. if err != nil {
  152. return
  153. }
  154. // If we aren't the first proxy retain prior
  155. // X-Forwarded-For information as a comma+space
  156. // separated list and fold multiple headers into one.
  157. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  158. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  159. }
  160. req.Header.Set("X-Forwarded-For", clientIP)
  161. }