http.go 6.0 KB

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