http.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  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 vhost
  15. import (
  16. "context"
  17. "encoding/base64"
  18. "errors"
  19. "fmt"
  20. stdlog "log"
  21. "net"
  22. "net/http"
  23. "net/http/httputil"
  24. "net/url"
  25. "strings"
  26. "time"
  27. libio "github.com/fatedier/golib/io"
  28. "github.com/fatedier/golib/pool"
  29. "golang.org/x/net/http2"
  30. "golang.org/x/net/http2/h2c"
  31. httppkg "github.com/fatedier/frp/pkg/util/http"
  32. "github.com/fatedier/frp/pkg/util/log"
  33. )
  34. var ErrNoRouteFound = errors.New("no route found")
  35. type HTTPReverseProxyOptions struct {
  36. ResponseHeaderTimeoutS int64
  37. }
  38. type HTTPReverseProxy struct {
  39. proxy http.Handler
  40. vhostRouter *Routers
  41. responseHeaderTimeout time.Duration
  42. }
  43. func NewHTTPReverseProxy(option HTTPReverseProxyOptions, vhostRouter *Routers) *HTTPReverseProxy {
  44. if option.ResponseHeaderTimeoutS <= 0 {
  45. option.ResponseHeaderTimeoutS = 60
  46. }
  47. rp := &HTTPReverseProxy{
  48. responseHeaderTimeout: time.Duration(option.ResponseHeaderTimeoutS) * time.Second,
  49. vhostRouter: vhostRouter,
  50. }
  51. proxy := &httputil.ReverseProxy{
  52. // Modify incoming requests by route policies.
  53. Rewrite: func(r *httputil.ProxyRequest) {
  54. r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"]
  55. r.SetXForwarded()
  56. req := r.Out
  57. req.URL.Scheme = "http"
  58. reqRouteInfo := req.Context().Value(RouteInfoKey).(*RequestRouteInfo)
  59. originalHost, _ := httppkg.CanonicalHost(reqRouteInfo.Host)
  60. rc := req.Context().Value(RouteConfigKey).(*RouteConfig)
  61. if rc != nil {
  62. if rc.RewriteHost != "" {
  63. req.Host = rc.RewriteHost
  64. }
  65. var endpoint string
  66. if rc.ChooseEndpointFn != nil {
  67. // ignore error here, it will use CreateConnFn instead later
  68. endpoint, _ = rc.ChooseEndpointFn()
  69. reqRouteInfo.Endpoint = endpoint
  70. log.Tracef("choose endpoint name [%s] for http request host [%s] path [%s] httpuser [%s]",
  71. endpoint, originalHost, reqRouteInfo.URL, reqRouteInfo.HTTPUser)
  72. }
  73. // Set {domain}.{location}.{routeByHTTPUser}.{endpoint} as URL host here to let http transport reuse connections.
  74. req.URL.Host = rc.Domain + "." +
  75. base64.StdEncoding.EncodeToString([]byte(rc.Location)) + "." +
  76. base64.StdEncoding.EncodeToString([]byte(rc.RouteByHTTPUser)) + "." +
  77. base64.StdEncoding.EncodeToString([]byte(endpoint))
  78. for k, v := range rc.Headers {
  79. req.Header.Set(k, v)
  80. }
  81. } else {
  82. req.URL.Host = req.Host
  83. }
  84. },
  85. ModifyResponse: func(r *http.Response) error {
  86. rc := r.Request.Context().Value(RouteConfigKey).(*RouteConfig)
  87. if rc != nil {
  88. for k, v := range rc.ResponseHeaders {
  89. r.Header.Set(k, v)
  90. }
  91. }
  92. return nil
  93. },
  94. // Create a connection to one proxy routed by route policy.
  95. Transport: &http.Transport{
  96. ResponseHeaderTimeout: rp.responseHeaderTimeout,
  97. IdleConnTimeout: 60 * time.Second,
  98. MaxIdleConnsPerHost: 5,
  99. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  100. return rp.CreateConnection(ctx.Value(RouteInfoKey).(*RequestRouteInfo), true)
  101. },
  102. Proxy: func(req *http.Request) (*url.URL, error) {
  103. // Use proxy mode if there is host in HTTP first request line.
  104. // GET http://example.com/ HTTP/1.1
  105. // Host: example.com
  106. //
  107. // Normal:
  108. // GET / HTTP/1.1
  109. // Host: example.com
  110. urlHost := req.Context().Value(RouteInfoKey).(*RequestRouteInfo).URLHost
  111. if urlHost != "" {
  112. return req.URL, nil
  113. }
  114. return nil, nil
  115. },
  116. },
  117. BufferPool: pool.NewBuffer(32 * 1024),
  118. ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0),
  119. ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
  120. log.Logf(log.WarnLevel, 1, "do http proxy request [host: %s] error: %v", req.Host, err)
  121. if err != nil {
  122. if e, ok := err.(net.Error); ok && e.Timeout() {
  123. rw.WriteHeader(http.StatusGatewayTimeout)
  124. return
  125. }
  126. }
  127. rw.WriteHeader(http.StatusNotFound)
  128. _, _ = rw.Write(getNotFoundPageContent())
  129. },
  130. }
  131. rp.proxy = h2c.NewHandler(proxy, &http2.Server{})
  132. return rp
  133. }
  134. // Register register the route config to reverse proxy
  135. // reverse proxy will use CreateConnFn from routeCfg to create a connection to the remote service
  136. func (rp *HTTPReverseProxy) Register(routeCfg RouteConfig) error {
  137. err := rp.vhostRouter.Add(routeCfg.Domain, routeCfg.Location, routeCfg.RouteByHTTPUser, &routeCfg)
  138. if err != nil {
  139. return err
  140. }
  141. return nil
  142. }
  143. // UnRegister unregister route config by domain and location
  144. func (rp *HTTPReverseProxy) UnRegister(routeCfg RouteConfig) {
  145. rp.vhostRouter.Del(routeCfg.Domain, routeCfg.Location, routeCfg.RouteByHTTPUser)
  146. }
  147. func (rp *HTTPReverseProxy) GetRouteConfig(domain, location, routeByHTTPUser string) *RouteConfig {
  148. vr, ok := rp.getVhost(domain, location, routeByHTTPUser)
  149. if ok {
  150. log.Debugf("get new HTTP request host [%s] path [%s] httpuser [%s]", domain, location, routeByHTTPUser)
  151. return vr.payload.(*RouteConfig)
  152. }
  153. return nil
  154. }
  155. // CreateConnection create a new connection by route config
  156. func (rp *HTTPReverseProxy) CreateConnection(reqRouteInfo *RequestRouteInfo, byEndpoint bool) (net.Conn, error) {
  157. host, _ := httppkg.CanonicalHost(reqRouteInfo.Host)
  158. vr, ok := rp.getVhost(host, reqRouteInfo.URL, reqRouteInfo.HTTPUser)
  159. if ok {
  160. if byEndpoint {
  161. fn := vr.payload.(*RouteConfig).CreateConnByEndpointFn
  162. if fn != nil {
  163. return fn(reqRouteInfo.Endpoint, reqRouteInfo.RemoteAddr)
  164. }
  165. }
  166. fn := vr.payload.(*RouteConfig).CreateConnFn
  167. if fn != nil {
  168. return fn(reqRouteInfo.RemoteAddr)
  169. }
  170. }
  171. return nil, fmt.Errorf("%v: %s %s %s", ErrNoRouteFound, host, reqRouteInfo.URL, reqRouteInfo.HTTPUser)
  172. }
  173. func (rp *HTTPReverseProxy) CheckAuth(domain, location, routeByHTTPUser, user, passwd string) bool {
  174. vr, ok := rp.getVhost(domain, location, routeByHTTPUser)
  175. if ok {
  176. checkUser := vr.payload.(*RouteConfig).Username
  177. checkPasswd := vr.payload.(*RouteConfig).Password
  178. if (checkUser != "" || checkPasswd != "") && (checkUser != user || checkPasswd != passwd) {
  179. return false
  180. }
  181. }
  182. return true
  183. }
  184. // getVhost tries to get vhost router by route policy.
  185. func (rp *HTTPReverseProxy) getVhost(domain, location, routeByHTTPUser string) (*Router, bool) {
  186. findRouter := func(inDomain, inLocation, inRouteByHTTPUser string) (*Router, bool) {
  187. vr, ok := rp.vhostRouter.Get(inDomain, inLocation, inRouteByHTTPUser)
  188. if ok {
  189. return vr, ok
  190. }
  191. // Try to check if there is one proxy that doesn't specify routerByHTTPUser, it means match all.
  192. vr, ok = rp.vhostRouter.Get(inDomain, inLocation, "")
  193. if ok {
  194. return vr, ok
  195. }
  196. return nil, false
  197. }
  198. // First we check the full hostname
  199. // if not exist, then check the wildcard_domain such as *.example.com
  200. vr, ok := findRouter(domain, location, routeByHTTPUser)
  201. if ok {
  202. return vr, ok
  203. }
  204. // e.g. domain = test.example.com, try to match wildcard domains.
  205. // *.example.com
  206. // *.com
  207. domainSplit := strings.Split(domain, ".")
  208. for {
  209. if len(domainSplit) < 3 {
  210. break
  211. }
  212. domainSplit[0] = "*"
  213. domain = strings.Join(domainSplit, ".")
  214. vr, ok = findRouter(domain, location, routeByHTTPUser)
  215. if ok {
  216. return vr, true
  217. }
  218. domainSplit = domainSplit[1:]
  219. }
  220. // Finally, try to check if there is one proxy that domain is "*" means match all domains.
  221. vr, ok = findRouter("*", location, routeByHTTPUser)
  222. if ok {
  223. return vr, true
  224. }
  225. return nil, false
  226. }
  227. func (rp *HTTPReverseProxy) connectHandler(rw http.ResponseWriter, req *http.Request) {
  228. hj, ok := rw.(http.Hijacker)
  229. if !ok {
  230. rw.WriteHeader(http.StatusInternalServerError)
  231. return
  232. }
  233. client, _, err := hj.Hijack()
  234. if err != nil {
  235. rw.WriteHeader(http.StatusInternalServerError)
  236. return
  237. }
  238. remote, err := rp.CreateConnection(req.Context().Value(RouteInfoKey).(*RequestRouteInfo), false)
  239. if err != nil {
  240. _ = NotFoundResponse().Write(client)
  241. client.Close()
  242. return
  243. }
  244. _ = req.Write(remote)
  245. go libio.Join(remote, client)
  246. }
  247. func parseBasicAuth(auth string) (username, password string, ok bool) {
  248. const prefix = "Basic "
  249. // Case insensitive prefix match. See Issue 22736.
  250. if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
  251. return
  252. }
  253. c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
  254. if err != nil {
  255. return
  256. }
  257. cs := string(c)
  258. s := strings.IndexByte(cs, ':')
  259. if s < 0 {
  260. return
  261. }
  262. return cs[:s], cs[s+1:], true
  263. }
  264. func (rp *HTTPReverseProxy) injectRequestInfoToCtx(req *http.Request) *http.Request {
  265. user := ""
  266. // If url host isn't empty, it's a proxy request. Get http user from Proxy-Authorization header.
  267. if req.URL.Host != "" {
  268. proxyAuth := req.Header.Get("Proxy-Authorization")
  269. if proxyAuth != "" {
  270. user, _, _ = parseBasicAuth(proxyAuth)
  271. }
  272. }
  273. if user == "" {
  274. user, _, _ = req.BasicAuth()
  275. }
  276. reqRouteInfo := &RequestRouteInfo{
  277. URL: req.URL.Path,
  278. Host: req.Host,
  279. HTTPUser: user,
  280. RemoteAddr: req.RemoteAddr,
  281. URLHost: req.URL.Host,
  282. }
  283. originalHost, _ := httppkg.CanonicalHost(reqRouteInfo.Host)
  284. rc := rp.GetRouteConfig(originalHost, reqRouteInfo.URL, reqRouteInfo.HTTPUser)
  285. newctx := req.Context()
  286. newctx = context.WithValue(newctx, RouteInfoKey, reqRouteInfo)
  287. newctx = context.WithValue(newctx, RouteConfigKey, rc)
  288. return req.Clone(newctx)
  289. }
  290. func (rp *HTTPReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  291. domain, _ := httppkg.CanonicalHost(req.Host)
  292. location := req.URL.Path
  293. user, passwd, _ := req.BasicAuth()
  294. if !rp.CheckAuth(domain, location, user, user, passwd) {
  295. rw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  296. http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  297. return
  298. }
  299. newreq := rp.injectRequestInfoToCtx(req)
  300. if req.Method == http.MethodConnect {
  301. rp.connectHandler(rw, newreq)
  302. } else {
  303. rp.proxy.ServeHTTP(rw, newreq)
  304. }
  305. }