proxy.go 14 KB

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