1
0

http.go 10 KB

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