1
0

proxy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. "bytes"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "reflect"
  21. "github.com/samber/lo"
  22. "github.com/fatedier/frp/pkg/config/types"
  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. Annotations map[string]string `json:"annotations,omitempty"`
  100. Transport ProxyTransport `json:"transport,omitempty"`
  101. // metadata info for each proxy
  102. Metadatas map[string]string `json:"metadatas,omitempty"`
  103. LoadBalancer LoadBalancerConfig `json:"loadBalancer,omitempty"`
  104. HealthCheck HealthCheckConfig `json:"healthCheck,omitempty"`
  105. ProxyBackend
  106. }
  107. func (c *ProxyBaseConfig) GetBaseConfig() *ProxyBaseConfig {
  108. return c
  109. }
  110. func (c *ProxyBaseConfig) Complete(namePrefix string) {
  111. c.Name = lo.Ternary(namePrefix == "", "", namePrefix+".") + c.Name
  112. c.LocalIP = util.EmptyOr(c.LocalIP, "127.0.0.1")
  113. c.Transport.BandwidthLimitMode = util.EmptyOr(c.Transport.BandwidthLimitMode, types.BandwidthLimitModeClient)
  114. }
  115. func (c *ProxyBaseConfig) MarshalToMsg(m *msg.NewProxy) {
  116. m.ProxyName = c.Name
  117. m.ProxyType = c.Type
  118. m.UseEncryption = c.Transport.UseEncryption
  119. m.UseCompression = c.Transport.UseCompression
  120. m.BandwidthLimit = c.Transport.BandwidthLimit.String()
  121. // leave it empty for default value to reduce traffic
  122. if c.Transport.BandwidthLimitMode != "client" {
  123. m.BandwidthLimitMode = c.Transport.BandwidthLimitMode
  124. }
  125. m.Group = c.LoadBalancer.Group
  126. m.GroupKey = c.LoadBalancer.GroupKey
  127. m.Metas = c.Metadatas
  128. m.Annotations = c.Annotations
  129. }
  130. func (c *ProxyBaseConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  131. c.Name = m.ProxyName
  132. c.Type = m.ProxyType
  133. c.Transport.UseEncryption = m.UseEncryption
  134. c.Transport.UseCompression = m.UseCompression
  135. if m.BandwidthLimit != "" {
  136. c.Transport.BandwidthLimit, _ = types.NewBandwidthQuantity(m.BandwidthLimit)
  137. }
  138. if m.BandwidthLimitMode != "" {
  139. c.Transport.BandwidthLimitMode = m.BandwidthLimitMode
  140. }
  141. c.LoadBalancer.Group = m.Group
  142. c.LoadBalancer.GroupKey = m.GroupKey
  143. c.Metadatas = m.Metas
  144. c.Annotations = m.Annotations
  145. }
  146. type TypedProxyConfig struct {
  147. Type string `json:"type"`
  148. ProxyConfigurer
  149. }
  150. func (c *TypedProxyConfig) UnmarshalJSON(b []byte) error {
  151. if len(b) == 4 && string(b) == "null" {
  152. return errors.New("type is required")
  153. }
  154. typeStruct := struct {
  155. Type string `json:"type"`
  156. }{}
  157. if err := json.Unmarshal(b, &typeStruct); err != nil {
  158. return err
  159. }
  160. c.Type = typeStruct.Type
  161. configurer := NewProxyConfigurerByType(ProxyType(typeStruct.Type))
  162. if configurer == nil {
  163. return fmt.Errorf("unknown proxy type: %s", typeStruct.Type)
  164. }
  165. decoder := json.NewDecoder(bytes.NewBuffer(b))
  166. if DisallowUnknownFields {
  167. decoder.DisallowUnknownFields()
  168. }
  169. if err := decoder.Decode(configurer); err != nil {
  170. return err
  171. }
  172. c.ProxyConfigurer = configurer
  173. return nil
  174. }
  175. type ProxyConfigurer interface {
  176. Complete(namePrefix string)
  177. GetBaseConfig() *ProxyBaseConfig
  178. // MarshalToMsg marshals this config into a msg.NewProxy message. This
  179. // function will be called on the frpc side.
  180. MarshalToMsg(*msg.NewProxy)
  181. // UnmarshalFromMsg unmarshal a msg.NewProxy message into this config.
  182. // This function will be called on the frps side.
  183. UnmarshalFromMsg(*msg.NewProxy)
  184. }
  185. type ProxyType string
  186. const (
  187. ProxyTypeTCP ProxyType = "tcp"
  188. ProxyTypeUDP ProxyType = "udp"
  189. ProxyTypeTCPMUX ProxyType = "tcpmux"
  190. ProxyTypeHTTP ProxyType = "http"
  191. ProxyTypeHTTPS ProxyType = "https"
  192. ProxyTypeSTCP ProxyType = "stcp"
  193. ProxyTypeXTCP ProxyType = "xtcp"
  194. ProxyTypeSUDP ProxyType = "sudp"
  195. )
  196. var proxyConfigTypeMap = map[ProxyType]reflect.Type{
  197. ProxyTypeTCP: reflect.TypeOf(TCPProxyConfig{}),
  198. ProxyTypeUDP: reflect.TypeOf(UDPProxyConfig{}),
  199. ProxyTypeHTTP: reflect.TypeOf(HTTPProxyConfig{}),
  200. ProxyTypeHTTPS: reflect.TypeOf(HTTPSProxyConfig{}),
  201. ProxyTypeTCPMUX: reflect.TypeOf(TCPMuxProxyConfig{}),
  202. ProxyTypeSTCP: reflect.TypeOf(STCPProxyConfig{}),
  203. ProxyTypeXTCP: reflect.TypeOf(XTCPProxyConfig{}),
  204. ProxyTypeSUDP: reflect.TypeOf(SUDPProxyConfig{}),
  205. }
  206. func NewProxyConfigurerByType(proxyType ProxyType) ProxyConfigurer {
  207. v, ok := proxyConfigTypeMap[proxyType]
  208. if !ok {
  209. return nil
  210. }
  211. pc := reflect.New(v).Interface().(ProxyConfigurer)
  212. pc.GetBaseConfig().Type = string(proxyType)
  213. return pc
  214. }
  215. var _ ProxyConfigurer = &TCPProxyConfig{}
  216. type TCPProxyConfig struct {
  217. ProxyBaseConfig
  218. RemotePort int `json:"remotePort,omitempty"`
  219. }
  220. func (c *TCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  221. c.ProxyBaseConfig.MarshalToMsg(m)
  222. m.RemotePort = c.RemotePort
  223. }
  224. func (c *TCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  225. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  226. c.RemotePort = m.RemotePort
  227. }
  228. var _ ProxyConfigurer = &UDPProxyConfig{}
  229. type UDPProxyConfig struct {
  230. ProxyBaseConfig
  231. RemotePort int `json:"remotePort,omitempty"`
  232. }
  233. func (c *UDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  234. c.ProxyBaseConfig.MarshalToMsg(m)
  235. m.RemotePort = c.RemotePort
  236. }
  237. func (c *UDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  238. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  239. c.RemotePort = m.RemotePort
  240. }
  241. var _ ProxyConfigurer = &HTTPProxyConfig{}
  242. type HTTPProxyConfig struct {
  243. ProxyBaseConfig
  244. DomainConfig
  245. Locations []string `json:"locations,omitempty"`
  246. HTTPUser string `json:"httpUser,omitempty"`
  247. HTTPPassword string `json:"httpPassword,omitempty"`
  248. HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
  249. RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
  250. RouteByHTTPUser string `json:"routeByHTTPUser,omitempty"`
  251. }
  252. func (c *HTTPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  253. c.ProxyBaseConfig.MarshalToMsg(m)
  254. m.CustomDomains = c.CustomDomains
  255. m.SubDomain = c.SubDomain
  256. m.Locations = c.Locations
  257. m.HostHeaderRewrite = c.HostHeaderRewrite
  258. m.HTTPUser = c.HTTPUser
  259. m.HTTPPwd = c.HTTPPassword
  260. m.Headers = c.RequestHeaders.Set
  261. m.RouteByHTTPUser = c.RouteByHTTPUser
  262. }
  263. func (c *HTTPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  264. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  265. c.CustomDomains = m.CustomDomains
  266. c.SubDomain = m.SubDomain
  267. c.Locations = m.Locations
  268. c.HostHeaderRewrite = m.HostHeaderRewrite
  269. c.HTTPUser = m.HTTPUser
  270. c.HTTPPassword = m.HTTPPwd
  271. c.RequestHeaders.Set = m.Headers
  272. c.RouteByHTTPUser = m.RouteByHTTPUser
  273. }
  274. var _ ProxyConfigurer = &HTTPSProxyConfig{}
  275. type HTTPSProxyConfig struct {
  276. ProxyBaseConfig
  277. DomainConfig
  278. }
  279. func (c *HTTPSProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  280. c.ProxyBaseConfig.MarshalToMsg(m)
  281. m.CustomDomains = c.CustomDomains
  282. m.SubDomain = c.SubDomain
  283. }
  284. func (c *HTTPSProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  285. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  286. c.CustomDomains = m.CustomDomains
  287. c.SubDomain = m.SubDomain
  288. }
  289. type TCPMultiplexerType string
  290. const (
  291. TCPMultiplexerHTTPConnect TCPMultiplexerType = "httpconnect"
  292. )
  293. var _ ProxyConfigurer = &TCPMuxProxyConfig{}
  294. type TCPMuxProxyConfig struct {
  295. ProxyBaseConfig
  296. DomainConfig
  297. HTTPUser string `json:"httpUser,omitempty"`
  298. HTTPPassword string `json:"httpPassword,omitempty"`
  299. RouteByHTTPUser string `json:"routeByHTTPUser,omitempty"`
  300. Multiplexer string `json:"multiplexer,omitempty"`
  301. }
  302. func (c *TCPMuxProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  303. c.ProxyBaseConfig.MarshalToMsg(m)
  304. m.CustomDomains = c.CustomDomains
  305. m.SubDomain = c.SubDomain
  306. m.Multiplexer = c.Multiplexer
  307. m.HTTPUser = c.HTTPUser
  308. m.HTTPPwd = c.HTTPPassword
  309. m.RouteByHTTPUser = c.RouteByHTTPUser
  310. }
  311. func (c *TCPMuxProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  312. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  313. c.CustomDomains = m.CustomDomains
  314. c.SubDomain = m.SubDomain
  315. c.Multiplexer = m.Multiplexer
  316. c.HTTPUser = m.HTTPUser
  317. c.HTTPPassword = m.HTTPPwd
  318. c.RouteByHTTPUser = m.RouteByHTTPUser
  319. }
  320. var _ ProxyConfigurer = &STCPProxyConfig{}
  321. type STCPProxyConfig struct {
  322. ProxyBaseConfig
  323. Secretkey string `json:"secretKey,omitempty"`
  324. AllowUsers []string `json:"allowUsers,omitempty"`
  325. }
  326. func (c *STCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  327. c.ProxyBaseConfig.MarshalToMsg(m)
  328. m.Sk = c.Secretkey
  329. m.AllowUsers = c.AllowUsers
  330. }
  331. func (c *STCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  332. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  333. c.Secretkey = m.Sk
  334. c.AllowUsers = m.AllowUsers
  335. }
  336. var _ ProxyConfigurer = &XTCPProxyConfig{}
  337. type XTCPProxyConfig struct {
  338. ProxyBaseConfig
  339. Secretkey string `json:"secretKey,omitempty"`
  340. AllowUsers []string `json:"allowUsers,omitempty"`
  341. }
  342. func (c *XTCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  343. c.ProxyBaseConfig.MarshalToMsg(m)
  344. m.Sk = c.Secretkey
  345. m.AllowUsers = c.AllowUsers
  346. }
  347. func (c *XTCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  348. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  349. c.Secretkey = m.Sk
  350. c.AllowUsers = m.AllowUsers
  351. }
  352. var _ ProxyConfigurer = &SUDPProxyConfig{}
  353. type SUDPProxyConfig struct {
  354. ProxyBaseConfig
  355. Secretkey string `json:"secretKey,omitempty"`
  356. AllowUsers []string `json:"allowUsers,omitempty"`
  357. }
  358. func (c *SUDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  359. c.ProxyBaseConfig.MarshalToMsg(m)
  360. m.Sk = c.Secretkey
  361. m.AllowUsers = c.AllowUsers
  362. }
  363. func (c *SUDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  364. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  365. c.Secretkey = m.Sk
  366. c.AllowUsers = m.AllowUsers
  367. }