proxy.go 13 KB

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