proxy.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. // Copyright 2023 The frp Authors
  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 v1
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "reflect"
  20. "github.com/samber/lo"
  21. "github.com/fatedier/frp/pkg/config/types"
  22. "github.com/fatedier/frp/pkg/consts"
  23. "github.com/fatedier/frp/pkg/msg"
  24. "github.com/fatedier/frp/pkg/util/util"
  25. )
  26. type ProxyTransport struct {
  27. // UseEncryption controls whether or not communication with the server will
  28. // be encrypted. Encryption is done using the tokens supplied in the server
  29. // and client configuration.
  30. UseEncryption bool `json:"useEncryption,omitempty"`
  31. // UseCompression controls whether or not communication with the server
  32. // will be compressed.
  33. UseCompression bool `json:"useCompression,omitempty"`
  34. // BandwidthLimit limit the bandwidth
  35. // 0 means no limit
  36. BandwidthLimit types.BandwidthQuantity `json:"bandwidthLimit,omitempty"`
  37. // BandwidthLimitMode specifies whether to limit the bandwidth on the
  38. // client or server side. Valid values include "client" and "server".
  39. // By default, this value is "client".
  40. BandwidthLimitMode string `json:"bandwidthLimitMode,omitempty"`
  41. // ProxyProtocolVersion specifies which protocol version to use. Valid
  42. // values include "v1", "v2", and "". If the value is "", a protocol
  43. // version will be automatically selected. By default, this value is "".
  44. ProxyProtocolVersion string `json:"proxyProtocolVersion,omitempty"`
  45. }
  46. type LoadBalancerConfig struct {
  47. // Group specifies which group the is a part of. The server will use
  48. // this information to load balance proxies in the same group. If the value
  49. // is "", this will not be in a group.
  50. Group string `json:"group"`
  51. // GroupKey specifies a group key, which should be the same among proxies
  52. // of the same group.
  53. GroupKey string `json:"groupKey,omitempty"`
  54. }
  55. type ProxyBackend struct {
  56. // LocalIP specifies the IP address or host name of the backend.
  57. LocalIP string `json:"localIP,omitempty"`
  58. // LocalPort specifies the port of the backend.
  59. LocalPort int `json:"localPort,omitempty"`
  60. // Plugin specifies what plugin should be used for handling connections. If this value
  61. // is set, the LocalIP and LocalPort values will be ignored.
  62. Plugin TypedClientPluginOptions `json:"plugin,omitempty"`
  63. }
  64. // HealthCheckConfig configures health checking. This can be useful for load
  65. // balancing purposes to detect and remove proxies to failing services.
  66. type HealthCheckConfig struct {
  67. // Type specifies what protocol to use for health checking.
  68. // Valid values include "tcp", "http", and "". If this value is "", health
  69. // checking will not be performed.
  70. //
  71. // If the type is "tcp", a connection will be attempted to the target
  72. // server. If a connection cannot be established, the health check fails.
  73. //
  74. // If the type is "http", a GET request will be made to the endpoint
  75. // specified by HealthCheckURL. If the response is not a 200, the health
  76. // check fails.
  77. Type string `json:"type"` // tcp | http
  78. // TimeoutSeconds specifies the number of seconds to wait for a health
  79. // check attempt to connect. If the timeout is reached, this counts as a
  80. // health check failure. By default, this value is 3.
  81. TimeoutSeconds int `json:"timeoutSeconds,omitempty"`
  82. // MaxFailed specifies the number of allowed failures before the
  83. // is stopped. By default, this value is 1.
  84. MaxFailed int `json:"maxFailed,omitempty"`
  85. // IntervalSeconds specifies the time in seconds between health
  86. // checks. By default, this value is 10.
  87. IntervalSeconds int `json:"intervalSeconds"`
  88. // Path specifies the path to send health checks to if the
  89. // health check type is "http".
  90. Path string `json:"path,omitempty"`
  91. }
  92. type DomainConfig struct {
  93. CustomDomains []string `json:"customDomains,omitempty"`
  94. SubDomain string `json:"subdomain,omitempty"`
  95. }
  96. type ProxyBaseConfig struct {
  97. Name string `json:"name"`
  98. Type string `json:"type"`
  99. Transport ProxyTransport `json:"transport,omitempty"`
  100. // metadata info for each proxy
  101. Metadatas map[string]string `json:"metadatas,omitempty"`
  102. LoadBalancer LoadBalancerConfig `json:"loadBalancer,omitempty"`
  103. HealthCheck HealthCheckConfig `json:"healthCheck,omitempty"`
  104. ProxyBackend
  105. }
  106. func (c *ProxyBaseConfig) GetBaseConfig() *ProxyBaseConfig {
  107. return c
  108. }
  109. func (c *ProxyBaseConfig) Complete(namePrefix string) {
  110. c.Name = lo.Ternary(namePrefix == "", "", namePrefix+".") + c.Name
  111. c.LocalIP = util.EmptyOr(c.LocalIP, "127.0.0.1")
  112. c.Transport.BandwidthLimitMode = util.EmptyOr(c.Transport.BandwidthLimitMode, types.BandwidthLimitModeClient)
  113. }
  114. func (c *ProxyBaseConfig) MarshalToMsg(m *msg.NewProxy) {
  115. m.ProxyName = c.Name
  116. m.ProxyType = c.Type
  117. m.UseEncryption = c.Transport.UseEncryption
  118. m.UseCompression = c.Transport.UseCompression
  119. m.BandwidthLimit = c.Transport.BandwidthLimit.String()
  120. // leave it empty for default value to reduce traffic
  121. if c.Transport.BandwidthLimitMode != "client" {
  122. m.BandwidthLimitMode = c.Transport.BandwidthLimitMode
  123. }
  124. m.Group = c.LoadBalancer.Group
  125. m.GroupKey = c.LoadBalancer.GroupKey
  126. m.Metas = c.Metadatas
  127. }
  128. func (c *ProxyBaseConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  129. c.Name = m.ProxyName
  130. c.Type = m.ProxyType
  131. c.Transport.UseEncryption = m.UseEncryption
  132. c.Transport.UseCompression = m.UseCompression
  133. if m.BandwidthLimit != "" {
  134. c.Transport.BandwidthLimit, _ = types.NewBandwidthQuantity(m.BandwidthLimit)
  135. }
  136. if m.BandwidthLimitMode != "" {
  137. c.Transport.BandwidthLimitMode = m.BandwidthLimitMode
  138. }
  139. c.LoadBalancer.Group = m.Group
  140. c.LoadBalancer.GroupKey = m.GroupKey
  141. c.Metadatas = m.Metas
  142. }
  143. type TypedProxyConfig struct {
  144. Type string `json:"type"`
  145. ProxyConfigurer
  146. }
  147. func (c *TypedProxyConfig) UnmarshalJSON(b []byte) error {
  148. if len(b) == 4 && string(b) == "null" {
  149. return errors.New("type is required")
  150. }
  151. typeStruct := struct {
  152. Type string `json:"type"`
  153. }{}
  154. if err := json.Unmarshal(b, &typeStruct); err != nil {
  155. return err
  156. }
  157. c.Type = typeStruct.Type
  158. configurer := NewProxyConfigurerByType(typeStruct.Type)
  159. if configurer == nil {
  160. return fmt.Errorf("unknown proxy type: %s", typeStruct.Type)
  161. }
  162. if err := json.Unmarshal(b, configurer); err != nil {
  163. return err
  164. }
  165. c.ProxyConfigurer = configurer
  166. return nil
  167. }
  168. type ProxyConfigurer interface {
  169. Complete(namePrefix string)
  170. GetBaseConfig() *ProxyBaseConfig
  171. // MarshalToMsg marshals this config into a msg.NewProxy message. This
  172. // function will be called on the frpc side.
  173. MarshalToMsg(*msg.NewProxy)
  174. // UnmarshalFromMsg unmarshals a msg.NewProxy message into this config.
  175. // This function will be called on the frps side.
  176. UnmarshalFromMsg(*msg.NewProxy)
  177. }
  178. var proxyConfigTypeMap = map[string]reflect.Type{
  179. consts.TCPProxy: reflect.TypeOf(TCPProxyConfig{}),
  180. consts.UDPProxy: reflect.TypeOf(UDPProxyConfig{}),
  181. consts.HTTPProxy: reflect.TypeOf(HTTPProxyConfig{}),
  182. consts.HTTPSProxy: reflect.TypeOf(HTTPSProxyConfig{}),
  183. consts.TCPMuxProxy: reflect.TypeOf(TCPMuxProxyConfig{}),
  184. consts.STCPProxy: reflect.TypeOf(STCPProxyConfig{}),
  185. consts.XTCPProxy: reflect.TypeOf(XTCPProxyConfig{}),
  186. consts.SUDPProxy: reflect.TypeOf(SUDPProxyConfig{}),
  187. }
  188. func NewProxyConfigurerByType(proxyType string) ProxyConfigurer {
  189. v, ok := proxyConfigTypeMap[proxyType]
  190. if !ok {
  191. return nil
  192. }
  193. return reflect.New(v).Interface().(ProxyConfigurer)
  194. }
  195. var _ ProxyConfigurer = &TCPProxyConfig{}
  196. type TCPProxyConfig struct {
  197. ProxyBaseConfig
  198. RemotePort int `json:"remotePort,omitempty"`
  199. }
  200. func (c *TCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  201. c.ProxyBaseConfig.MarshalToMsg(m)
  202. m.RemotePort = c.RemotePort
  203. }
  204. func (c *TCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  205. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  206. c.RemotePort = m.RemotePort
  207. }
  208. var _ ProxyConfigurer = &UDPProxyConfig{}
  209. type UDPProxyConfig struct {
  210. ProxyBaseConfig
  211. RemotePort int `json:"remotePort,omitempty"`
  212. }
  213. func (c *UDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  214. c.ProxyBaseConfig.MarshalToMsg(m)
  215. m.RemotePort = c.RemotePort
  216. }
  217. func (c *UDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  218. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  219. c.RemotePort = m.RemotePort
  220. }
  221. var _ ProxyConfigurer = &HTTPProxyConfig{}
  222. type HTTPProxyConfig struct {
  223. ProxyBaseConfig
  224. DomainConfig
  225. Locations []string `json:"locations,omitempty"`
  226. HTTPUser string `json:"httpUser,omitempty"`
  227. HTTPPassword string `json:"httpPassword,omitempty"`
  228. HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
  229. RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
  230. RouteByHTTPUser string `json:"routeByHttpUser,omitempty"`
  231. }
  232. func (c *HTTPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  233. c.ProxyBaseConfig.MarshalToMsg(m)
  234. m.CustomDomains = c.CustomDomains
  235. m.SubDomain = c.SubDomain
  236. m.Locations = c.Locations
  237. m.HostHeaderRewrite = c.HostHeaderRewrite
  238. m.HTTPUser = c.HTTPUser
  239. m.HTTPPwd = c.HTTPPassword
  240. m.Headers = c.RequestHeaders.Set
  241. m.RouteByHTTPUser = c.RouteByHTTPUser
  242. }
  243. func (c *HTTPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  244. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  245. c.CustomDomains = m.CustomDomains
  246. c.SubDomain = m.SubDomain
  247. c.Locations = m.Locations
  248. c.HostHeaderRewrite = m.HostHeaderRewrite
  249. c.HTTPUser = m.HTTPUser
  250. c.HTTPPassword = m.HTTPPwd
  251. c.RequestHeaders.Set = m.Headers
  252. c.RouteByHTTPUser = m.RouteByHTTPUser
  253. }
  254. var _ ProxyConfigurer = &HTTPSProxyConfig{}
  255. type HTTPSProxyConfig struct {
  256. ProxyBaseConfig
  257. DomainConfig
  258. }
  259. func (c *HTTPSProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  260. c.ProxyBaseConfig.MarshalToMsg(m)
  261. m.CustomDomains = c.CustomDomains
  262. m.SubDomain = c.SubDomain
  263. }
  264. func (c *HTTPSProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  265. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  266. c.CustomDomains = m.CustomDomains
  267. c.SubDomain = m.SubDomain
  268. }
  269. var _ ProxyConfigurer = &TCPMuxProxyConfig{}
  270. type TCPMuxProxyConfig struct {
  271. ProxyBaseConfig
  272. DomainConfig
  273. HTTPUser string `json:"httpUser,omitempty"`
  274. HTTPPassword string `json:"httpPassword,omitempty"`
  275. RouteByHTTPUser string `json:"routeByHttpUser,omitempty"`
  276. Multiplexer string `json:"multiplexer,omitempty"`
  277. }
  278. func (c *TCPMuxProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  279. c.ProxyBaseConfig.MarshalToMsg(m)
  280. m.CustomDomains = c.CustomDomains
  281. m.SubDomain = c.SubDomain
  282. m.Multiplexer = c.Multiplexer
  283. m.HTTPUser = c.HTTPUser
  284. m.HTTPPwd = c.HTTPPassword
  285. m.RouteByHTTPUser = c.RouteByHTTPUser
  286. }
  287. func (c *TCPMuxProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  288. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  289. c.CustomDomains = m.CustomDomains
  290. c.SubDomain = m.SubDomain
  291. c.Multiplexer = m.Multiplexer
  292. c.HTTPUser = m.HTTPUser
  293. c.HTTPPassword = m.HTTPPwd
  294. c.RouteByHTTPUser = m.RouteByHTTPUser
  295. }
  296. var _ ProxyConfigurer = &STCPProxyConfig{}
  297. type STCPProxyConfig struct {
  298. ProxyBaseConfig
  299. Secretkey string `json:"secretKey,omitempty"`
  300. AllowUsers []string `json:"allowUsers,omitempty"`
  301. }
  302. func (c *STCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  303. c.ProxyBaseConfig.MarshalToMsg(m)
  304. m.Sk = c.Secretkey
  305. m.AllowUsers = c.AllowUsers
  306. }
  307. func (c *STCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  308. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  309. c.Secretkey = m.Sk
  310. c.AllowUsers = m.AllowUsers
  311. }
  312. var _ ProxyConfigurer = &XTCPProxyConfig{}
  313. type XTCPProxyConfig struct {
  314. ProxyBaseConfig
  315. Secretkey string `json:"secretKey,omitempty"`
  316. AllowUsers []string `json:"allowUsers,omitempty"`
  317. }
  318. func (c *XTCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  319. c.ProxyBaseConfig.MarshalToMsg(m)
  320. m.Sk = c.Secretkey
  321. m.AllowUsers = c.AllowUsers
  322. }
  323. func (c *XTCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  324. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  325. c.Secretkey = m.Sk
  326. c.AllowUsers = m.AllowUsers
  327. }
  328. var _ ProxyConfigurer = &SUDPProxyConfig{}
  329. type SUDPProxyConfig struct {
  330. ProxyBaseConfig
  331. Secretkey string `json:"secretKey,omitempty"`
  332. AllowUsers []string `json:"allowUsers,omitempty"`
  333. }
  334. func (c *SUDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  335. c.ProxyBaseConfig.MarshalToMsg(m)
  336. m.Sk = c.Secretkey
  337. m.AllowUsers = c.AllowUsers
  338. }
  339. func (c *SUDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  340. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  341. c.Secretkey = m.Sk
  342. c.AllowUsers = m.AllowUsers
  343. }