http.go 10.0 KB

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