1
0

proxy.go 13 KB

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