http.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. Username: pxy.cfg.HTTPUser,
  53. Password: pxy.cfg.HTTPPassword,
  54. CreateConnFn: pxy.GetRealConn,
  55. }
  56. locations := pxy.cfg.Locations
  57. if len(locations) == 0 {
  58. locations = []string{""}
  59. }
  60. defer func() {
  61. if err != nil {
  62. pxy.Close()
  63. }
  64. }()
  65. addrs := make([]string, 0)
  66. for _, domain := range pxy.cfg.CustomDomains {
  67. if domain == "" {
  68. continue
  69. }
  70. routeConfig.Domain = domain
  71. for _, location := range locations {
  72. routeConfig.Location = location
  73. tmpRouteConfig := routeConfig
  74. // handle group
  75. if pxy.cfg.LoadBalancer.Group != "" {
  76. err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, routeConfig)
  77. if err != nil {
  78. return
  79. }
  80. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  81. pxy.rc.HTTPGroupCtl.UnRegister(pxy.name, pxy.cfg.LoadBalancer.Group, tmpRouteConfig)
  82. })
  83. } else {
  84. // no group
  85. err = pxy.rc.HTTPReverseProxy.Register(routeConfig)
  86. if err != nil {
  87. return
  88. }
  89. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  90. pxy.rc.HTTPReverseProxy.UnRegister(tmpRouteConfig)
  91. })
  92. }
  93. addrs = append(addrs, util.CanonicalAddr(routeConfig.Domain, pxy.serverCfg.VhostHTTPPort))
  94. xl.Infof("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]",
  95. routeConfig.Domain, routeConfig.Location, pxy.cfg.LoadBalancer.Group, pxy.cfg.RouteByHTTPUser)
  96. }
  97. }
  98. if pxy.cfg.SubDomain != "" {
  99. routeConfig.Domain = pxy.cfg.SubDomain + "." + pxy.serverCfg.SubDomainHost
  100. for _, location := range locations {
  101. routeConfig.Location = location
  102. tmpRouteConfig := routeConfig
  103. // handle group
  104. if pxy.cfg.LoadBalancer.Group != "" {
  105. err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, routeConfig)
  106. if err != nil {
  107. return
  108. }
  109. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  110. pxy.rc.HTTPGroupCtl.UnRegister(pxy.name, pxy.cfg.LoadBalancer.Group, tmpRouteConfig)
  111. })
  112. } else {
  113. err = pxy.rc.HTTPReverseProxy.Register(routeConfig)
  114. if err != nil {
  115. return
  116. }
  117. pxy.closeFuncs = append(pxy.closeFuncs, func() {
  118. pxy.rc.HTTPReverseProxy.UnRegister(tmpRouteConfig)
  119. })
  120. }
  121. addrs = append(addrs, util.CanonicalAddr(tmpRouteConfig.Domain, pxy.serverCfg.VhostHTTPPort))
  122. xl.Infof("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]",
  123. routeConfig.Domain, routeConfig.Location, pxy.cfg.LoadBalancer.Group, pxy.cfg.RouteByHTTPUser)
  124. }
  125. }
  126. remoteAddr = strings.Join(addrs, ",")
  127. return
  128. }
  129. func (pxy *HTTPProxy) GetRealConn(remoteAddr string) (workConn net.Conn, err error) {
  130. xl := pxy.xl
  131. rAddr, errRet := net.ResolveTCPAddr("tcp", remoteAddr)
  132. if errRet != nil {
  133. xl.Warnf("resolve TCP addr [%s] error: %v", remoteAddr, errRet)
  134. // we do not return error here since remoteAddr is not necessary for proxies without proxy protocol enabled
  135. }
  136. tmpConn, errRet := pxy.GetWorkConnFromPool(rAddr, nil)
  137. if errRet != nil {
  138. err = errRet
  139. return
  140. }
  141. var rwc io.ReadWriteCloser = tmpConn
  142. if pxy.cfg.Transport.UseEncryption {
  143. rwc, err = libio.WithEncryption(rwc, []byte(pxy.serverCfg.Auth.Token))
  144. if err != nil {
  145. xl.Errorf("create encryption stream error: %v", err)
  146. return
  147. }
  148. }
  149. if pxy.cfg.Transport.UseCompression {
  150. rwc = libio.WithCompression(rwc)
  151. }
  152. if pxy.GetLimiter() != nil {
  153. rwc = libio.WrapReadWriteCloser(limit.NewReader(rwc, pxy.GetLimiter()), limit.NewWriter(rwc, pxy.GetLimiter()), func() error {
  154. return rwc.Close()
  155. })
  156. }
  157. workConn = netpkg.WrapReadWriteCloserToConn(rwc, tmpConn)
  158. workConn = netpkg.WrapStatsConn(workConn, pxy.updateStatsAfterClosedConn)
  159. metrics.Server.OpenConnection(pxy.GetName(), pxy.GetConfigurer().GetBaseConfig().Type)
  160. return
  161. }
  162. func (pxy *HTTPProxy) updateStatsAfterClosedConn(totalRead, totalWrite int64) {
  163. name := pxy.GetName()
  164. proxyType := pxy.GetConfigurer().GetBaseConfig().Type
  165. metrics.Server.CloseConnection(name, proxyType)
  166. metrics.Server.AddTrafficIn(name, proxyType, totalWrite)
  167. metrics.Server.AddTrafficOut(name, proxyType, totalRead)
  168. }
  169. func (pxy *HTTPProxy) Close() {
  170. pxy.BaseProxy.Close()
  171. for _, closeFn := range pxy.closeFuncs {
  172. closeFn()
  173. }
  174. }