newhttp.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. "context"
  17. "errors"
  18. "log"
  19. "net"
  20. "net/http"
  21. "strings"
  22. "sync"
  23. "time"
  24. frpLog "github.com/fatedier/frp/utils/log"
  25. frpNet "github.com/fatedier/frp/utils/net"
  26. "github.com/fatedier/frp/utils/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 CreateConnFunc func() (frpNet.Conn, error)
  43. type ProxyOption struct {
  44. RewriteHost string
  45. DialFunc CreateConnFunc
  46. }
  47. type HttpReverseProxy struct {
  48. proxy *ReverseProxy
  49. tr *http.Transport
  50. vhostRouter *VhostRouters
  51. cfgMu sync.RWMutex
  52. }
  53. func NewHttpReverseProxy() *HttpReverseProxy {
  54. rp := &HttpReverseProxy{
  55. vhostRouter: NewVhostRouters(),
  56. }
  57. proxy := &ReverseProxy{
  58. Director: func(req *http.Request) {
  59. req.URL.Scheme = "http"
  60. url := req.Context().Value("url").(string)
  61. host := getHostFromAddr(req.Context().Value("host").(string))
  62. host = rp.GetRealHost(host, url)
  63. if host != "" {
  64. req.Host = host
  65. req.URL.Host = req.Host
  66. }
  67. },
  68. Transport: &http.Transport{
  69. ResponseHeaderTimeout: responseHeaderTimeout,
  70. DisableKeepAlives: true,
  71. DialContext: 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. },
  77. BufferPool: newWrapPool(),
  78. ErrorLog: log.New(newWrapLogger(), "", 0),
  79. }
  80. rp.proxy = proxy
  81. return rp
  82. }
  83. func (rp *HttpReverseProxy) Register(domain string, location string, rewriteHost string, fn CreateConnFunc) error {
  84. rp.cfgMu.Lock()
  85. defer rp.cfgMu.Unlock()
  86. _, ok := rp.vhostRouter.Exist(domain, location)
  87. if ok {
  88. return ErrRouterConfigConflict
  89. } else {
  90. payload := &ProxyOption{
  91. RewriteHost: rewriteHost,
  92. DialFunc: fn,
  93. }
  94. rp.vhostRouter.Add(domain, location, payload)
  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.(*ProxyOption).RewriteHost
  107. }
  108. return
  109. }
  110. func (rp *HttpReverseProxy) CreateConnection(domain string, location string) (net.Conn, error) {
  111. vr, ok := rp.getVhost(domain, location)
  112. if ok {
  113. fn := vr.payload.(*ProxyOption).DialFunc
  114. if fn != nil {
  115. return fn()
  116. }
  117. }
  118. return nil, ErrNoDomain
  119. }
  120. func (rp *HttpReverseProxy) getVhost(domain string, location string) (vr *VhostRouter, ok bool) {
  121. rp.cfgMu.RLock()
  122. defer rp.cfgMu.RUnlock()
  123. // first we check the full hostname
  124. // if not exist, then check the wildcard_domain such as *.example.com
  125. vr, ok = rp.vhostRouter.Get(domain, location)
  126. if ok {
  127. return
  128. }
  129. domainSplit := strings.Split(domain, ".")
  130. if len(domainSplit) < 3 {
  131. return vr, false
  132. }
  133. domainSplit[0] = "*"
  134. domain = strings.Join(domainSplit, ".")
  135. vr, ok = rp.vhostRouter.Get(domain, location)
  136. return
  137. }
  138. func (rp *HttpReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  139. rp.proxy.ServeHTTP(rw, req)
  140. }
  141. type wrapPool struct{}
  142. func newWrapPool() *wrapPool { return &wrapPool{} }
  143. func (p *wrapPool) Get() []byte { return pool.GetBuf(32 * 1024) }
  144. func (p *wrapPool) Put(buf []byte) { pool.PutBuf(buf) }
  145. type wrapLogger struct{}
  146. func newWrapLogger() *wrapLogger { return &wrapLogger{} }
  147. func (l *wrapLogger) Write(p []byte) (n int, err error) {
  148. frpLog.Warn("%s", string(p))
  149. return len(p), nil
  150. }