http.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. "strings"
  25. "time"
  26. frpLog "github.com/fatedier/frp/pkg/util/log"
  27. "github.com/fatedier/frp/pkg/util/util"
  28. "github.com/fatedier/golib/pool"
  29. )
  30. var (
  31. ErrNoDomain = errors.New("no such domain")
  32. )
  33. type HTTPReverseProxyOptions struct {
  34. ResponseHeaderTimeoutS int64
  35. }
  36. type HTTPReverseProxy struct {
  37. proxy *ReverseProxy
  38. vhostRouter *Routers
  39. responseHeaderTimeout time.Duration
  40. }
  41. func NewHTTPReverseProxy(option HTTPReverseProxyOptions, vhostRouter *Routers) *HTTPReverseProxy {
  42. if option.ResponseHeaderTimeoutS <= 0 {
  43. option.ResponseHeaderTimeoutS = 60
  44. }
  45. rp := &HTTPReverseProxy{
  46. responseHeaderTimeout: time.Duration(option.ResponseHeaderTimeoutS) * time.Second,
  47. vhostRouter: vhostRouter,
  48. }
  49. proxy := &ReverseProxy{
  50. Director: func(req *http.Request) {
  51. req.URL.Scheme = "http"
  52. url := req.Context().Value(RouteInfoURL).(string)
  53. oldHost, _ := util.CanonicalHost(req.Context().Value(RouteInfoHost).(string))
  54. rc := rp.GetRouteConfig(oldHost, url)
  55. if rc != nil {
  56. if rc.RewriteHost != "" {
  57. req.Host = rc.RewriteHost
  58. }
  59. // Set {domain}.{location} as URL host here to let http transport reuse connections.
  60. req.URL.Host = rc.Domain + "." + base64.StdEncoding.EncodeToString([]byte(rc.Location))
  61. for k, v := range rc.Headers {
  62. req.Header.Set(k, v)
  63. }
  64. } else {
  65. req.URL.Host = req.Host
  66. }
  67. },
  68. Transport: &http.Transport{
  69. ResponseHeaderTimeout: rp.responseHeaderTimeout,
  70. IdleConnTimeout: 60 * time.Second,
  71. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  72. url := ctx.Value(RouteInfoURL).(string)
  73. host, _ := util.CanonicalHost(ctx.Value(RouteInfoHost).(string))
  74. remote := ctx.Value(RouteInfoRemote).(string)
  75. return rp.CreateConnection(host, url, remote)
  76. },
  77. },
  78. BufferPool: newWrapPool(),
  79. ErrorLog: log.New(newWrapLogger(), "", 0),
  80. ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
  81. frpLog.Warn("do http proxy request error: %v", err)
  82. rw.WriteHeader(http.StatusNotFound)
  83. rw.Write(getNotFoundPageContent())
  84. },
  85. }
  86. rp.proxy = proxy
  87. return rp
  88. }
  89. // Register register the route config to reverse proxy
  90. // reverse proxy will use CreateConnFn from routeCfg to create a connection to the remote service
  91. func (rp *HTTPReverseProxy) Register(routeCfg RouteConfig) error {
  92. err := rp.vhostRouter.Add(routeCfg.Domain, routeCfg.Location, &routeCfg)
  93. if err != nil {
  94. return err
  95. }
  96. return nil
  97. }
  98. // UnRegister unregister route config by domain and location
  99. func (rp *HTTPReverseProxy) UnRegister(domain string, location string) {
  100. rp.vhostRouter.Del(domain, location)
  101. }
  102. func (rp *HTTPReverseProxy) GetRouteConfig(domain string, location string) *RouteConfig {
  103. vr, ok := rp.getVhost(domain, location)
  104. if ok {
  105. return vr.payload.(*RouteConfig)
  106. }
  107. return nil
  108. }
  109. func (rp *HTTPReverseProxy) GetRealHost(domain string, location string) (host string) {
  110. vr, ok := rp.getVhost(domain, location)
  111. if ok {
  112. host = vr.payload.(*RouteConfig).RewriteHost
  113. }
  114. return
  115. }
  116. func (rp *HTTPReverseProxy) GetHeaders(domain string, location string) (headers map[string]string) {
  117. vr, ok := rp.getVhost(domain, location)
  118. if ok {
  119. headers = vr.payload.(*RouteConfig).Headers
  120. }
  121. return
  122. }
  123. // CreateConnection create a new connection by route config
  124. func (rp *HTTPReverseProxy) CreateConnection(domain string, location string, remoteAddr string) (net.Conn, error) {
  125. vr, ok := rp.getVhost(domain, location)
  126. if ok {
  127. fn := vr.payload.(*RouteConfig).CreateConnFn
  128. if fn != nil {
  129. return fn(remoteAddr)
  130. }
  131. }
  132. return nil, fmt.Errorf("%v: %s %s", ErrNoDomain, domain, location)
  133. }
  134. func (rp *HTTPReverseProxy) CheckAuth(domain, location, user, passwd string) bool {
  135. vr, ok := rp.getVhost(domain, location)
  136. if ok {
  137. checkUser := vr.payload.(*RouteConfig).Username
  138. checkPasswd := vr.payload.(*RouteConfig).Password
  139. if (checkUser != "" || checkPasswd != "") && (checkUser != user || checkPasswd != passwd) {
  140. return false
  141. }
  142. }
  143. return true
  144. }
  145. // getVhost get vhost router by domain and location
  146. func (rp *HTTPReverseProxy) getVhost(domain string, location string) (vr *Router, ok bool) {
  147. // first we check the full hostname
  148. // if not exist, then check the wildcard_domain such as *.example.com
  149. vr, ok = rp.vhostRouter.Get(domain, location)
  150. if ok {
  151. return
  152. }
  153. domainSplit := strings.Split(domain, ".")
  154. if len(domainSplit) < 3 {
  155. return nil, false
  156. }
  157. for {
  158. if len(domainSplit) < 3 {
  159. return nil, false
  160. }
  161. domainSplit[0] = "*"
  162. domain = strings.Join(domainSplit, ".")
  163. vr, ok = rp.vhostRouter.Get(domain, location)
  164. if ok {
  165. return vr, true
  166. }
  167. domainSplit = domainSplit[1:]
  168. }
  169. }
  170. func (rp *HTTPReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  171. domain, _ := util.CanonicalHost(req.Host)
  172. location := req.URL.Path
  173. user, passwd, _ := req.BasicAuth()
  174. if !rp.CheckAuth(domain, location, user, passwd) {
  175. rw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  176. http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  177. return
  178. }
  179. rp.proxy.ServeHTTP(rw, req)
  180. }
  181. type wrapPool struct{}
  182. func newWrapPool() *wrapPool { return &wrapPool{} }
  183. func (p *wrapPool) Get() []byte { return pool.GetBuf(32 * 1024) }
  184. func (p *wrapPool) Put(buf []byte) { pool.PutBuf(buf) }
  185. type wrapLogger struct{}
  186. func newWrapLogger() *wrapLogger { return &wrapLogger{} }
  187. func (l *wrapLogger) Write(p []byte) (n int, err error) {
  188. frpLog.Warn("%s", string(bytes.TrimRight(p, "\n")))
  189. return len(p), nil
  190. }