http.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. BufferPool: newWrapPool(),
  82. ErrorLog: log.New(newWrapLogger(), "", 0),
  83. ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
  84. frpLog.Warn("do http proxy request error: %v", err)
  85. rw.WriteHeader(http.StatusNotFound)
  86. rw.Write(getNotFoundPageContent())
  87. },
  88. }
  89. rp.proxy = proxy
  90. return rp
  91. }
  92. // Register register the route config to reverse proxy
  93. // reverse proxy will use CreateConnFn from routeCfg to create a connection to the remote service
  94. func (rp *HttpReverseProxy) Register(routeCfg VhostRouteConfig) error {
  95. err := rp.vhostRouter.Add(routeCfg.Domain, routeCfg.Location, &routeCfg)
  96. if err != nil {
  97. return err
  98. }
  99. return nil
  100. }
  101. // UnRegister unregister route config by domain and location
  102. func (rp *HttpReverseProxy) UnRegister(domain string, location string) {
  103. rp.vhostRouter.Del(domain, location)
  104. }
  105. func (rp *HttpReverseProxy) GetRealHost(domain string, location string) (host string) {
  106. vr, ok := rp.getVhost(domain, location)
  107. if ok {
  108. host = vr.payload.(*VhostRouteConfig).RewriteHost
  109. }
  110. return
  111. }
  112. func (rp *HttpReverseProxy) GetHeaders(domain string, location string) (headers map[string]string) {
  113. vr, ok := rp.getVhost(domain, location)
  114. if ok {
  115. headers = vr.payload.(*VhostRouteConfig).Headers
  116. }
  117. return
  118. }
  119. // CreateConnection create a new connection by route config
  120. func (rp *HttpReverseProxy) CreateConnection(domain string, location string, remoteAddr string) (net.Conn, error) {
  121. vr, ok := rp.getVhost(domain, location)
  122. if ok {
  123. fn := vr.payload.(*VhostRouteConfig).CreateConnFn
  124. if fn != nil {
  125. return fn(remoteAddr)
  126. }
  127. }
  128. return nil, fmt.Errorf("%v: %s %s", ErrNoDomain, domain, location)
  129. }
  130. func (rp *HttpReverseProxy) CheckAuth(domain, location, user, passwd string) bool {
  131. vr, ok := rp.getVhost(domain, location)
  132. if ok {
  133. checkUser := vr.payload.(*VhostRouteConfig).Username
  134. checkPasswd := vr.payload.(*VhostRouteConfig).Password
  135. if (checkUser != "" || checkPasswd != "") && (checkUser != user || checkPasswd != passwd) {
  136. return false
  137. }
  138. }
  139. return true
  140. }
  141. // getVhost get vhost router by domain and location
  142. func (rp *HttpReverseProxy) getVhost(domain string, location string) (vr *VhostRouter, ok bool) {
  143. // first we check the full hostname
  144. // if not exist, then check the wildcard_domain such as *.example.com
  145. vr, ok = rp.vhostRouter.Get(domain, location)
  146. if ok {
  147. return
  148. }
  149. domainSplit := strings.Split(domain, ".")
  150. if len(domainSplit) < 3 {
  151. return nil, false
  152. }
  153. for {
  154. if len(domainSplit) < 3 {
  155. return nil, false
  156. }
  157. domainSplit[0] = "*"
  158. domain = strings.Join(domainSplit, ".")
  159. vr, ok = rp.vhostRouter.Get(domain, location)
  160. if ok {
  161. return vr, true
  162. }
  163. domainSplit = domainSplit[1:]
  164. }
  165. return
  166. }
  167. func (rp *HttpReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  168. domain := getHostFromAddr(req.Host)
  169. location := req.URL.Path
  170. user, passwd, _ := req.BasicAuth()
  171. if !rp.CheckAuth(domain, location, user, passwd) {
  172. rw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  173. http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  174. return
  175. }
  176. rp.proxy.ServeHTTP(rw, req)
  177. }
  178. type wrapPool struct{}
  179. func newWrapPool() *wrapPool { return &wrapPool{} }
  180. func (p *wrapPool) Get() []byte { return pool.GetBuf(32 * 1024) }
  181. func (p *wrapPool) Put(buf []byte) { pool.PutBuf(buf) }
  182. type wrapLogger struct{}
  183. func newWrapLogger() *wrapLogger { return &wrapLogger{} }
  184. func (l *wrapLogger) Write(p []byte) (n int, err error) {
  185. frpLog.Warn("%s", string(bytes.TrimRight(p, "\n")))
  186. return len(p), nil
  187. }