newhttp.go 4.9 KB

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