http.go 9.9 KB

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