http.go 9.6 KB

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