1
0

http.go 10.0 KB

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