http.go 5.8 KB

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