http.go 5.7 KB

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