http.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright 2019 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 proxy
  15. import (
  16. "io"
  17. "net"
  18. "reflect"
  19. "strings"
  20. libio "github.com/fatedier/golib/io"
  21. v1 "github.com/fatedier/frp/pkg/config/v1"
  22. "github.com/fatedier/frp/pkg/util/limit"
  23. netpkg "github.com/fatedier/frp/pkg/util/net"
  24. "github.com/fatedier/frp/pkg/util/util"
  25. "github.com/fatedier/frp/pkg/util/vhost"
  26. "github.com/fatedier/frp/server/metrics"
  27. )
  28. func init() {
  29. RegisterProxyFactory(reflect.TypeOf(&v1.HTTPProxyConfig{}), NewHTTPProxy)
  30. }
  31. type HTTPProxy struct {
  32. *BaseProxy
  33. cfg *v1.HTTPProxyConfig
  34. closeFuncs []func()
  35. }
  36. func NewHTTPProxy(baseProxy *BaseProxy) Proxy {
  37. unwrapped, ok := baseProxy.GetConfigurer().(*v1.HTTPProxyConfig)
  38. if !ok {
  39. return nil
  40. }
  41. return &HTTPProxy{
  42. BaseProxy: baseProxy,
  43. cfg: unwrapped,
  44. }
  45. }
  46. func (pxy *HTTPProxy) Run() (remoteAddr string, err error) {
  47. xl := pxy.xl
  48. routeConfig := vhost.RouteConfig{
  49. RewriteHost: pxy.cfg.HostHeaderRewrite,
  50. RouteByHTTPUser: pxy.cfg.RouteByHTTPUser,
  51. Headers: pxy.cfg.RequestHeaders.Set,
  52. ResponseHeaders: pxy.cfg.ResponseHeaders.Set,
  53. Username: pxy.cfg.HTTPUser,
  54. Password: pxy.cfg.HTTPPassword,
  55. CreateConnFn: pxy.GetRealConn,
  56. }
  57. locations := pxy.cfg.Locations
  58. if len(locations) == 0 {
  59. locations = []string{""}
  60. }
  61. defer func() {
  62. if err != nil {
  63. pxy.Close()
  64. }
  65. }()
  66. addrs := make([]string, 0)
  67. for _, domain := range pxy.cfg.CustomDomains {
  68. if domain == "" {
  69. continue
  70. }
  71. routeConfig.Domain = domain
  72. for _, location := range locations {
  73. routeConfig.Location = location
  74. tmpRouteConfig := routeConfig
  75. // handle group
  76. if pxy.cfg.LoadBalancer.Group != "" {
  77. err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, routeConfig)
  78. if err != nil {
  79. return
  80. }
  81. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  82. pxy.rc.HTTPGroupCtl.UnRegister(pxy.name, pxy.cfg.LoadBalancer.Group, tmpRouteConfig)
  83. })
  84. } else {
  85. // no group
  86. err = pxy.rc.HTTPReverseProxy.Register(routeConfig)
  87. if err != nil {
  88. return
  89. }
  90. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  91. pxy.rc.HTTPReverseProxy.UnRegister(tmpRouteConfig)
  92. })
  93. }
  94. addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, pxy.serverCfg.VhostHTTPPort))
  95. xl.Infof("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]",
  96. routeConfig.Domain, routeConfig.Location, pxy.cfg.LoadBalancer.Group, pxy.cfg.RouteByHTTPUser)
  97. }
  98. }
  99. if pxy.cfg.SubDomain != "" {
  100. routeConfig.Domain = pxy.cfg.SubDomain + "." + pxy.serverCfg.SubDomainHost
  101. for _, location := range locations {
  102. routeConfig.Location = location
  103. tmpRouteConfig := routeConfig
  104. // handle group
  105. if pxy.cfg.LoadBalancer.Group != "" {
  106. err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, routeConfig)
  107. if err != nil {
  108. return
  109. }
  110. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  111. pxy.rc.HTTPGroupCtl.UnRegister(pxy.name, pxy.cfg.LoadBalancer.Group, tmpRouteConfig)
  112. })
  113. } else {
  114. err = pxy.rc.HTTPReverseProxy.Register(routeConfig)
  115. if err != nil {
  116. return
  117. }
  118. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  119. pxy.rc.HTTPReverseProxy.UnRegister(tmpRouteConfig)
  120. })
  121. }
  122. addrs = append(addrs, util.CanonicalAddr(tmpRouteConfig.Domain, pxy.serverCfg.VhostHTTPPort))
  123. xl.Infof("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]",
  124. routeConfig.Domain, routeConfig.Location, pxy.cfg.LoadBalancer.Group, pxy.cfg.RouteByHTTPUser)
  125. }
  126. }
  127. remoteAddr = strings.Join(addrs, ",")
  128. return
  129. }
  130. func (pxy *HTTPProxy) GetRealConn(remoteAddr string) (workConn net.Conn, err error) {
  131. xl := pxy.xl
  132. rAddr, errRet := net.ResolveTCPAddr("tcp", remoteAddr)
  133. if errRet != nil {
  134. xl.Warnf("resolve TCP addr [%s] error: %v", remoteAddr, errRet)
  135. // we do not return error here since remoteAddr is not necessary for proxies without proxy protocol enabled
  136. }
  137. tmpConn, errRet := pxy.GetWorkConnFromPool(rAddr, nil)
  138. if errRet != nil {
  139. err = errRet
  140. return
  141. }
  142. var rwc io.ReadWriteCloser = tmpConn
  143. if pxy.cfg.Transport.UseEncryption {
  144. rwc, err = libio.WithEncryption(rwc, []byte(pxy.serverCfg.Auth.Token))
  145. if err != nil {
  146. xl.Errorf("create encryption stream error: %v", err)
  147. return
  148. }
  149. }
  150. if pxy.cfg.Transport.UseCompression {
  151. rwc = libio.WithCompression(rwc)
  152. }
  153. if pxy.GetLimiter() != nil {
  154. rwc = libio.WrapReadWriteCloser(limit.NewReader(rwc, pxy.GetLimiter()), limit.NewWriter(rwc, pxy.GetLimiter()), func() error {
  155. return rwc.Close()
  156. })
  157. }
  158. workConn = netpkg.WrapReadWriteCloserToConn(rwc, tmpConn)
  159. workConn = netpkg.WrapStatsConn(workConn, pxy.updateStatsAfterClosedConn)
  160. metrics.Server.OpenConnection(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type)
  161. return
  162. }
  163. func (pxy *HTTPProxy) updateStatsAfterClosedConn(totalRead, totalWrite int64) {
  164. name := pxy.GetName()
  165. proxyType := pxy.GetConfigurer().GetBaseConfig().Type
  166. metrics.Server.CloseConnection(name, proxyType)
  167. metrics.Server.AddTrafficIn(name, proxyType, totalWrite)
  168. metrics.Server.AddTrafficOut(name, proxyType, totalRead)
  169. }
  170. func (pxy *HTTPProxy) Close() {
  171. pxy.BaseProxy.Close()
  172. for _, closeFn := range pxy.closeFuncs {
  173. closeFn()
  174. }
  175. }