newhttp.go 5.3 KB

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