newhttp.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. "errors"
  19. "log"
  20. "net"
  21. "net/http"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/fatedier/frp/g"
  26. frpLog "github.com/fatedier/frp/utils/log"
  27. "github.com/fatedier/golib/pool"
  28. )
  29. var (
  30. responseHeaderTimeout = time.Duration(g.GlbServerCfg.VhostHttpTimeout) * time.Second
  31. ErrRouterConfigConflict = errors.New("router config conflict")
  32. ErrNoDomain = errors.New("no such domain")
  33. )
  34. func getHostFromAddr(addr string) (host string) {
  35. strs := strings.Split(addr, ":")
  36. if len(strs) > 1 {
  37. host = strs[0]
  38. } else {
  39. host = addr
  40. }
  41. return
  42. }
  43. type HttpReverseProxy struct {
  44. proxy *ReverseProxy
  45. vhostRouter *VhostRouters
  46. cfgMu sync.RWMutex
  47. }
  48. func NewHttpReverseProxy() *HttpReverseProxy {
  49. rp := &HttpReverseProxy{
  50. vhostRouter: NewVhostRouters(),
  51. }
  52. proxy := &ReverseProxy{
  53. Director: func(req *http.Request) {
  54. req.URL.Scheme = "http"
  55. url := req.Context().Value("url").(string)
  56. oldHost := getHostFromAddr(req.Context().Value("host").(string))
  57. host := rp.GetRealHost(oldHost, url)
  58. if host != "" {
  59. req.Host = host
  60. }
  61. req.URL.Host = req.Host
  62. headers := rp.GetHeaders(oldHost, url)
  63. for k, v := range headers {
  64. req.Header.Set(k, v)
  65. }
  66. },
  67. Transport: &http.Transport{
  68. ResponseHeaderTimeout: responseHeaderTimeout,
  69. DisableKeepAlives: true,
  70. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  71. url := ctx.Value("url").(string)
  72. host := getHostFromAddr(ctx.Value("host").(string))
  73. return rp.CreateConnection(host, url)
  74. },
  75. },
  76. WebSocketDialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  77. url := ctx.Value("url").(string)
  78. host := getHostFromAddr(ctx.Value("host").(string))
  79. return rp.CreateConnection(host, url)
  80. },
  81. BufferPool: newWrapPool(),
  82. ErrorLog: log.New(newWrapLogger(), "", 0),
  83. }
  84. rp.proxy = proxy
  85. return rp
  86. }
  87. func (rp *HttpReverseProxy) Register(routeCfg VhostRouteConfig) error {
  88. rp.cfgMu.Lock()
  89. defer rp.cfgMu.Unlock()
  90. _, ok := rp.vhostRouter.Exist(routeCfg.Domain, routeCfg.Location)
  91. if ok {
  92. return ErrRouterConfigConflict
  93. } else {
  94. rp.vhostRouter.Add(routeCfg.Domain, routeCfg.Location, &routeCfg)
  95. }
  96. return nil
  97. }
  98. func (rp *HttpReverseProxy) UnRegister(domain string, location string) {
  99. rp.cfgMu.Lock()
  100. defer rp.cfgMu.Unlock()
  101. rp.vhostRouter.Del(domain, location)
  102. }
  103. func (rp *HttpReverseProxy) GetRealHost(domain string, location string) (host string) {
  104. vr, ok := rp.getVhost(domain, location)
  105. if ok {
  106. host = vr.payload.(*VhostRouteConfig).RewriteHost
  107. }
  108. return
  109. }
  110. func (rp *HttpReverseProxy) GetHeaders(domain string, location string) (headers map[string]string) {
  111. vr, ok := rp.getVhost(domain, location)
  112. if ok {
  113. headers = vr.payload.(*VhostRouteConfig).Headers
  114. }
  115. return
  116. }
  117. func (rp *HttpReverseProxy) CreateConnection(domain string, location string) (net.Conn, error) {
  118. vr, ok := rp.getVhost(domain, location)
  119. if ok {
  120. fn := vr.payload.(*VhostRouteConfig).CreateConnFn
  121. if fn != nil {
  122. return fn()
  123. }
  124. }
  125. return nil, ErrNoDomain
  126. }
  127. func (rp *HttpReverseProxy) CheckAuth(domain, location, user, passwd string) bool {
  128. vr, ok := rp.getVhost(domain, location)
  129. if ok {
  130. checkUser := vr.payload.(*VhostRouteConfig).Username
  131. checkPasswd := vr.payload.(*VhostRouteConfig).Password
  132. if (checkUser != "" || checkPasswd != "") && (checkUser != user || checkPasswd != passwd) {
  133. return false
  134. }
  135. }
  136. return true
  137. }
  138. func (rp *HttpReverseProxy) getVhost(domain string, location string) (vr *VhostRouter, ok bool) {
  139. rp.cfgMu.RLock()
  140. defer rp.cfgMu.RUnlock()
  141. // first we check the full hostname
  142. // if not exist, then check the wildcard_domain such as *.example.com
  143. vr, ok = rp.vhostRouter.Get(domain, location)
  144. if ok {
  145. return
  146. }
  147. domainSplit := strings.Split(domain, ".")
  148. if len(domainSplit) < 3 {
  149. return vr, false
  150. }
  151. domainSplit[0] = "*"
  152. domain = strings.Join(domainSplit, ".")
  153. vr, ok = rp.vhostRouter.Get(domain, location)
  154. return
  155. }
  156. func (rp *HttpReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  157. domain := getHostFromAddr(req.Host)
  158. location := req.URL.Path
  159. user, passwd, _ := req.BasicAuth()
  160. if !rp.CheckAuth(domain, location, user, passwd) {
  161. rw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  162. http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  163. return
  164. }
  165. rp.proxy.ServeHTTP(rw, req)
  166. }
  167. type wrapPool struct{}
  168. func newWrapPool() *wrapPool { return &wrapPool{} }
  169. func (p *wrapPool) Get() []byte { return pool.GetBuf(32 * 1024) }
  170. func (p *wrapPool) Put(buf []byte) { pool.PutBuf(buf) }
  171. type wrapLogger struct{}
  172. func newWrapLogger() *wrapLogger { return &wrapLogger{} }
  173. func (l *wrapLogger) Write(p []byte) (n int, err error) {
  174. frpLog.Warn("%s", string(bytes.TrimRight(p, "\n")))
  175. return len(p), nil
  176. }