newhttp.go 4.3 KB

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