1
0

http.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "github.com/fatedier/frp/pkg/config"
  22. "github.com/fatedier/frp/pkg/util/limit"
  23. utilnet "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(&config.HTTPProxyConf{}), NewHTTPProxy)
  30. }
  31. type HTTPProxy struct {
  32. *BaseProxy
  33. cfg *config.HTTPProxyConf
  34. closeFuncs []func()
  35. }
  36. func NewHTTPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
  37. unwrapped, ok := cfg.(*config.HTTPProxyConf)
  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.Headers,
  52. Username: pxy.cfg.HTTPUser,
  53. Password: pxy.cfg.HTTPPwd,
  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.Group != "" {
  76. err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.Group, pxy.cfg.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.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.Info("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]",
  95. routeConfig.Domain, routeConfig.Location, pxy.cfg.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.Group != "" {
  105. err = pxy.rc.HTTPGroupCtl.Register(pxy.name, pxy.cfg.Group, pxy.cfg.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.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.Info("http proxy listen for host [%s] location [%s] group [%s], routeByHTTPUser [%s]",
  123. routeConfig.Domain, routeConfig.Location, pxy.cfg.Group, pxy.cfg.RouteByHTTPUser)
  124. }
  125. }
  126. remoteAddr = strings.Join(addrs, ",")
  127. return
  128. }
  129. func (pxy *HTTPProxy) GetConf() config.ProxyConf {
  130. return pxy.cfg
  131. }
  132. func (pxy *HTTPProxy) GetRealConn(remoteAddr string) (workConn net.Conn, err error) {
  133. xl := pxy.xl
  134. rAddr, errRet := net.ResolveTCPAddr("tcp", remoteAddr)
  135. if errRet != nil {
  136. xl.Warn("resolve TCP addr [%s] error: %v", remoteAddr, errRet)
  137. // we do not return error here since remoteAddr is not necessary for proxies without proxy protocol enabled
  138. }
  139. tmpConn, errRet := pxy.GetWorkConnFromPool(rAddr, nil)
  140. if errRet != nil {
  141. err = errRet
  142. return
  143. }
  144. var rwc io.ReadWriteCloser = tmpConn
  145. if pxy.cfg.UseEncryption {
  146. rwc, err = libio.WithEncryption(rwc, []byte(pxy.serverCfg.Token))
  147. if err != nil {
  148. xl.Error("create encryption stream error: %v", err)
  149. return
  150. }
  151. }
  152. if pxy.cfg.UseCompression {
  153. rwc = libio.WithCompression(rwc)
  154. }
  155. if pxy.GetLimiter() != nil {
  156. rwc = libio.WrapReadWriteCloser(limit.NewReader(rwc, pxy.GetLimiter()), limit.NewWriter(rwc, pxy.GetLimiter()), func() error {
  157. return rwc.Close()
  158. })
  159. }
  160. workConn = utilnet.WrapReadWriteCloserToConn(rwc, tmpConn)
  161. workConn = utilnet.WrapStatsConn(workConn, pxy.updateStatsAfterClosedConn)
  162. metrics.Server.OpenConnection(pxy.GetName(), pxy.GetConf().GetBaseConfig().ProxyType)
  163. return
  164. }
  165. func (pxy *HTTPProxy) updateStatsAfterClosedConn(totalRead, totalWrite int64) {
  166. name := pxy.GetName()
  167. proxyType := pxy.GetConf().GetBaseConfig().ProxyType
  168. metrics.Server.CloseConnection(name, proxyType)
  169. metrics.Server.AddTrafficIn(name, proxyType, totalWrite)
  170. metrics.Server.AddTrafficOut(name, proxyType, totalRead)
  171. }
  172. func (pxy *HTTPProxy) Close() {
  173. pxy.BaseProxy.Close()
  174. for _, closeFn := range pxy.closeFuncs {
  175. closeFn()
  176. }
  177. }