http.go 9.8 KB

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