proxy_server.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package proxy
  14. import (
  15. "fmt"
  16. "net"
  17. "net/http"
  18. "net/url"
  19. "os"
  20. "regexp"
  21. "strings"
  22. "time"
  23. utilnet "k8s.io/apimachinery/pkg/util/net"
  24. "k8s.io/apimachinery/pkg/util/proxy"
  25. "k8s.io/client-go/rest"
  26. "k8s.io/client-go/transport"
  27. "k8s.io/klog"
  28. "k8s.io/kubernetes/pkg/kubectl/util"
  29. )
  30. const (
  31. // DefaultHostAcceptRE is the default value for which hosts to accept.
  32. DefaultHostAcceptRE = "^localhost$,^127\\.0\\.0\\.1$,^\\[::1\\]$"
  33. // DefaultPathAcceptRE is the default path to accept.
  34. DefaultPathAcceptRE = "^.*"
  35. // DefaultPathRejectRE is the default set of paths to reject.
  36. DefaultPathRejectRE = "^/api/.*/pods/.*/exec,^/api/.*/pods/.*/attach"
  37. // DefaultMethodRejectRE is the set of HTTP methods to reject by default.
  38. DefaultMethodRejectRE = "^$"
  39. )
  40. // FilterServer rejects requests which don't match one of the specified regular expressions
  41. type FilterServer struct {
  42. // Only paths that match this regexp will be accepted
  43. AcceptPaths []*regexp.Regexp
  44. // Paths that match this regexp will be rejected, even if they match the above
  45. RejectPaths []*regexp.Regexp
  46. // Hosts are required to match this list of regexp
  47. AcceptHosts []*regexp.Regexp
  48. // Methods that match this regexp are rejected
  49. RejectMethods []*regexp.Regexp
  50. // The delegate to call to handle accepted requests.
  51. delegate http.Handler
  52. }
  53. // MakeRegexpArray splits a comma separated list of regexps into an array of Regexp objects.
  54. func MakeRegexpArray(str string) ([]*regexp.Regexp, error) {
  55. parts := strings.Split(str, ",")
  56. result := make([]*regexp.Regexp, len(parts))
  57. for ix := range parts {
  58. re, err := regexp.Compile(parts[ix])
  59. if err != nil {
  60. return nil, err
  61. }
  62. result[ix] = re
  63. }
  64. return result, nil
  65. }
  66. // MakeRegexpArrayOrDie creates an array of regular expression objects from a string or exits.
  67. func MakeRegexpArrayOrDie(str string) []*regexp.Regexp {
  68. result, err := MakeRegexpArray(str)
  69. if err != nil {
  70. klog.Fatalf("Error compiling re: %v", err)
  71. }
  72. return result
  73. }
  74. func matchesRegexp(str string, regexps []*regexp.Regexp) bool {
  75. for _, re := range regexps {
  76. if re.MatchString(str) {
  77. klog.V(6).Infof("%v matched %s", str, re)
  78. return true
  79. }
  80. }
  81. return false
  82. }
  83. func (f *FilterServer) accept(method, path, host string) bool {
  84. if matchesRegexp(path, f.RejectPaths) {
  85. return false
  86. }
  87. if matchesRegexp(method, f.RejectMethods) {
  88. return false
  89. }
  90. if matchesRegexp(path, f.AcceptPaths) && matchesRegexp(host, f.AcceptHosts) {
  91. return true
  92. }
  93. return false
  94. }
  95. // HandlerFor makes a shallow copy of f which passes its requests along to the
  96. // new delegate.
  97. func (f *FilterServer) HandlerFor(delegate http.Handler) *FilterServer {
  98. f2 := *f
  99. f2.delegate = delegate
  100. return &f2
  101. }
  102. // Get host from a host header value like "localhost" or "localhost:8080"
  103. func extractHost(header string) (host string) {
  104. host, _, err := net.SplitHostPort(header)
  105. if err != nil {
  106. host = header
  107. }
  108. return host
  109. }
  110. func (f *FilterServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  111. host := extractHost(req.Host)
  112. if f.accept(req.Method, req.URL.Path, host) {
  113. klog.V(3).Infof("Filter accepting %v %v %v", req.Method, req.URL.Path, host)
  114. f.delegate.ServeHTTP(rw, req)
  115. return
  116. }
  117. klog.V(3).Infof("Filter rejecting %v %v %v", req.Method, req.URL.Path, host)
  118. http.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  119. }
  120. // Server is a http.Handler which proxies Kubernetes APIs to remote API server.
  121. type Server struct {
  122. handler http.Handler
  123. }
  124. type responder struct{}
  125. func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error) {
  126. klog.Errorf("Error while proxying request: %v", err)
  127. http.Error(w, err.Error(), http.StatusInternalServerError)
  128. }
  129. // makeUpgradeTransport creates a transport that explicitly bypasses HTTP2 support
  130. // for proxy connections that must upgrade.
  131. func makeUpgradeTransport(config *rest.Config, keepalive time.Duration) (proxy.UpgradeRequestRoundTripper, error) {
  132. transportConfig, err := config.TransportConfig()
  133. if err != nil {
  134. return nil, err
  135. }
  136. tlsConfig, err := transport.TLSConfigFor(transportConfig)
  137. if err != nil {
  138. return nil, err
  139. }
  140. rt := utilnet.SetOldTransportDefaults(&http.Transport{
  141. TLSClientConfig: tlsConfig,
  142. DialContext: (&net.Dialer{
  143. Timeout: 30 * time.Second,
  144. KeepAlive: keepalive,
  145. }).DialContext,
  146. })
  147. upgrader, err := transport.HTTPWrappersForConfig(transportConfig, proxy.MirrorRequest)
  148. if err != nil {
  149. return nil, err
  150. }
  151. return proxy.NewUpgradeRequestRoundTripper(rt, upgrader), nil
  152. }
  153. // NewServer creates and installs a new Server.
  154. // 'filter', if non-nil, protects requests to the api only.
  155. func NewServer(filebase string, apiProxyPrefix string, staticPrefix string, filter *FilterServer, cfg *rest.Config, keepalive time.Duration) (*Server, error) {
  156. host := cfg.Host
  157. if !strings.HasSuffix(host, "/") {
  158. host = host + "/"
  159. }
  160. target, err := url.Parse(host)
  161. if err != nil {
  162. return nil, err
  163. }
  164. responder := &responder{}
  165. transport, err := rest.TransportFor(cfg)
  166. if err != nil {
  167. return nil, err
  168. }
  169. upgradeTransport, err := makeUpgradeTransport(cfg, keepalive)
  170. if err != nil {
  171. return nil, err
  172. }
  173. proxy := proxy.NewUpgradeAwareHandler(target, transport, false, false, responder)
  174. proxy.UpgradeTransport = upgradeTransport
  175. proxy.UseRequestLocation = true
  176. proxyServer := http.Handler(proxy)
  177. if filter != nil {
  178. proxyServer = filter.HandlerFor(proxyServer)
  179. }
  180. if !strings.HasPrefix(apiProxyPrefix, "/api") {
  181. proxyServer = stripLeaveSlash(apiProxyPrefix, proxyServer)
  182. }
  183. mux := http.NewServeMux()
  184. mux.Handle(apiProxyPrefix, proxyServer)
  185. if filebase != "" {
  186. // Require user to explicitly request this behavior rather than
  187. // serving their working directory by default.
  188. mux.Handle(staticPrefix, newFileHandler(staticPrefix, filebase))
  189. }
  190. return &Server{handler: mux}, nil
  191. }
  192. // Listen is a simple wrapper around net.Listen.
  193. func (s *Server) Listen(address string, port int) (net.Listener, error) {
  194. return net.Listen("tcp", fmt.Sprintf("%s:%d", address, port))
  195. }
  196. // ListenUnix does net.Listen for a unix socket
  197. func (s *Server) ListenUnix(path string) (net.Listener, error) {
  198. // Remove any socket, stale or not, but fall through for other files
  199. fi, err := os.Stat(path)
  200. if err == nil && (fi.Mode()&os.ModeSocket) != 0 {
  201. os.Remove(path)
  202. }
  203. // Default to only user accessible socket, caller can open up later if desired
  204. oldmask, _ := util.Umask(0077)
  205. l, err := net.Listen("unix", path)
  206. util.Umask(oldmask)
  207. return l, err
  208. }
  209. // ServeOnListener starts the server using given listener, loops forever.
  210. func (s *Server) ServeOnListener(l net.Listener) error {
  211. server := http.Server{
  212. Handler: s.handler,
  213. }
  214. return server.Serve(l)
  215. }
  216. func newFileHandler(prefix, base string) http.Handler {
  217. return http.StripPrefix(prefix, http.FileServer(http.Dir(base)))
  218. }
  219. // like http.StripPrefix, but always leaves an initial slash. (so that our
  220. // regexps will work.)
  221. func stripLeaveSlash(prefix string, h http.Handler) http.Handler {
  222. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  223. p := strings.TrimPrefix(req.URL.Path, prefix)
  224. if len(p) >= len(req.URL.Path) {
  225. http.NotFound(w, req)
  226. return
  227. }
  228. if len(p) > 0 && p[:1] != "/" {
  229. p = "/" + p
  230. }
  231. req.URL.Path = p
  232. h.ServeHTTP(w, req)
  233. })
  234. }