1
0

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