http.go 5.8 KB

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