1
0

proxy.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. func (c *TypedProxyConfig) MarshalJSON() ([]byte, error) {
  179. return json.Marshal(c.ProxyConfigurer)
  180. }
  181. type ProxyConfigurer interface {
  182. Complete(namePrefix string)
  183. GetBaseConfig() *ProxyBaseConfig
  184. // MarshalToMsg marshals this config into a msg.NewProxy message. This
  185. // function will be called on the frpc side.
  186. MarshalToMsg(*msg.NewProxy)
  187. // UnmarshalFromMsg unmarshal a msg.NewProxy message into this config.
  188. // This function will be called on the frps side.
  189. UnmarshalFromMsg(*msg.NewProxy)
  190. }
  191. type ProxyType string
  192. const (
  193. ProxyTypeTCP ProxyType = "tcp"
  194. ProxyTypeUDP ProxyType = "udp"
  195. ProxyTypeTCPMUX ProxyType = "tcpmux"
  196. ProxyTypeHTTP ProxyType = "http"
  197. ProxyTypeHTTPS ProxyType = "https"
  198. ProxyTypeSTCP ProxyType = "stcp"
  199. ProxyTypeXTCP ProxyType = "xtcp"
  200. ProxyTypeSUDP ProxyType = "sudp"
  201. )
  202. var proxyConfigTypeMap = map[ProxyType]reflect.Type{
  203. ProxyTypeTCP: reflect.TypeOf(TCPProxyConfig{}),
  204. ProxyTypeUDP: reflect.TypeOf(UDPProxyConfig{}),
  205. ProxyTypeHTTP: reflect.TypeOf(HTTPProxyConfig{}),
  206. ProxyTypeHTTPS: reflect.TypeOf(HTTPSProxyConfig{}),
  207. ProxyTypeTCPMUX: reflect.TypeOf(TCPMuxProxyConfig{}),
  208. ProxyTypeSTCP: reflect.TypeOf(STCPProxyConfig{}),
  209. ProxyTypeXTCP: reflect.TypeOf(XTCPProxyConfig{}),
  210. ProxyTypeSUDP: reflect.TypeOf(SUDPProxyConfig{}),
  211. }
  212. func NewProxyConfigurerByType(proxyType ProxyType) ProxyConfigurer {
  213. v, ok := proxyConfigTypeMap[proxyType]
  214. if !ok {
  215. return nil
  216. }
  217. pc := reflect.New(v).Interface().(ProxyConfigurer)
  218. pc.GetBaseConfig().Type = string(proxyType)
  219. return pc
  220. }
  221. var _ ProxyConfigurer = &TCPProxyConfig{}
  222. type TCPProxyConfig struct {
  223. ProxyBaseConfig
  224. RemotePort int `json:"remotePort,omitempty"`
  225. }
  226. func (c *TCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  227. c.ProxyBaseConfig.MarshalToMsg(m)
  228. m.RemotePort = c.RemotePort
  229. }
  230. func (c *TCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  231. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  232. c.RemotePort = m.RemotePort
  233. }
  234. var _ ProxyConfigurer = &UDPProxyConfig{}
  235. type UDPProxyConfig struct {
  236. ProxyBaseConfig
  237. RemotePort int `json:"remotePort,omitempty"`
  238. }
  239. func (c *UDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  240. c.ProxyBaseConfig.MarshalToMsg(m)
  241. m.RemotePort = c.RemotePort
  242. }
  243. func (c *UDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  244. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  245. c.RemotePort = m.RemotePort
  246. }
  247. var _ ProxyConfigurer = &HTTPProxyConfig{}
  248. type HTTPProxyConfig struct {
  249. ProxyBaseConfig
  250. DomainConfig
  251. Locations []string `json:"locations,omitempty"`
  252. HTTPUser string `json:"httpUser,omitempty"`
  253. HTTPPassword string `json:"httpPassword,omitempty"`
  254. HostHeaderRewrite string `json:"hostHeaderRewrite,omitempty"`
  255. RequestHeaders HeaderOperations `json:"requestHeaders,omitempty"`
  256. ResponseHeaders HeaderOperations `json:"responseHeaders,omitempty"`
  257. RouteByHTTPUser string `json:"routeByHTTPUser,omitempty"`
  258. }
  259. func (c *HTTPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  260. c.ProxyBaseConfig.MarshalToMsg(m)
  261. m.CustomDomains = c.CustomDomains
  262. m.SubDomain = c.SubDomain
  263. m.Locations = c.Locations
  264. m.HostHeaderRewrite = c.HostHeaderRewrite
  265. m.HTTPUser = c.HTTPUser
  266. m.HTTPPwd = c.HTTPPassword
  267. m.Headers = c.RequestHeaders.Set
  268. m.ResponseHeaders = c.ResponseHeaders.Set
  269. m.RouteByHTTPUser = c.RouteByHTTPUser
  270. }
  271. func (c *HTTPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  272. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  273. c.CustomDomains = m.CustomDomains
  274. c.SubDomain = m.SubDomain
  275. c.Locations = m.Locations
  276. c.HostHeaderRewrite = m.HostHeaderRewrite
  277. c.HTTPUser = m.HTTPUser
  278. c.HTTPPassword = m.HTTPPwd
  279. c.RequestHeaders.Set = m.Headers
  280. c.ResponseHeaders.Set = m.ResponseHeaders
  281. c.RouteByHTTPUser = m.RouteByHTTPUser
  282. }
  283. var _ ProxyConfigurer = &HTTPSProxyConfig{}
  284. type HTTPSProxyConfig struct {
  285. ProxyBaseConfig
  286. DomainConfig
  287. }
  288. func (c *HTTPSProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  289. c.ProxyBaseConfig.MarshalToMsg(m)
  290. m.CustomDomains = c.CustomDomains
  291. m.SubDomain = c.SubDomain
  292. }
  293. func (c *HTTPSProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  294. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  295. c.CustomDomains = m.CustomDomains
  296. c.SubDomain = m.SubDomain
  297. }
  298. type TCPMultiplexerType string
  299. const (
  300. TCPMultiplexerHTTPConnect TCPMultiplexerType = "httpconnect"
  301. )
  302. var _ ProxyConfigurer = &TCPMuxProxyConfig{}
  303. type TCPMuxProxyConfig struct {
  304. ProxyBaseConfig
  305. DomainConfig
  306. HTTPUser string `json:"httpUser,omitempty"`
  307. HTTPPassword string `json:"httpPassword,omitempty"`
  308. RouteByHTTPUser string `json:"routeByHTTPUser,omitempty"`
  309. Multiplexer string `json:"multiplexer,omitempty"`
  310. }
  311. func (c *TCPMuxProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  312. c.ProxyBaseConfig.MarshalToMsg(m)
  313. m.CustomDomains = c.CustomDomains
  314. m.SubDomain = c.SubDomain
  315. m.Multiplexer = c.Multiplexer
  316. m.HTTPUser = c.HTTPUser
  317. m.HTTPPwd = c.HTTPPassword
  318. m.RouteByHTTPUser = c.RouteByHTTPUser
  319. }
  320. func (c *TCPMuxProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  321. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  322. c.CustomDomains = m.CustomDomains
  323. c.SubDomain = m.SubDomain
  324. c.Multiplexer = m.Multiplexer
  325. c.HTTPUser = m.HTTPUser
  326. c.HTTPPassword = m.HTTPPwd
  327. c.RouteByHTTPUser = m.RouteByHTTPUser
  328. }
  329. var _ ProxyConfigurer = &STCPProxyConfig{}
  330. type STCPProxyConfig struct {
  331. ProxyBaseConfig
  332. Secretkey string `json:"secretKey,omitempty"`
  333. AllowUsers []string `json:"allowUsers,omitempty"`
  334. }
  335. func (c *STCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  336. c.ProxyBaseConfig.MarshalToMsg(m)
  337. m.Sk = c.Secretkey
  338. m.AllowUsers = c.AllowUsers
  339. }
  340. func (c *STCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  341. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  342. c.Secretkey = m.Sk
  343. c.AllowUsers = m.AllowUsers
  344. }
  345. var _ ProxyConfigurer = &XTCPProxyConfig{}
  346. type XTCPProxyConfig struct {
  347. ProxyBaseConfig
  348. Secretkey string `json:"secretKey,omitempty"`
  349. AllowUsers []string `json:"allowUsers,omitempty"`
  350. }
  351. func (c *XTCPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  352. c.ProxyBaseConfig.MarshalToMsg(m)
  353. m.Sk = c.Secretkey
  354. m.AllowUsers = c.AllowUsers
  355. }
  356. func (c *XTCPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  357. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  358. c.Secretkey = m.Sk
  359. c.AllowUsers = m.AllowUsers
  360. }
  361. var _ ProxyConfigurer = &SUDPProxyConfig{}
  362. type SUDPProxyConfig struct {
  363. ProxyBaseConfig
  364. Secretkey string `json:"secretKey,omitempty"`
  365. AllowUsers []string `json:"allowUsers,omitempty"`
  366. }
  367. func (c *SUDPProxyConfig) MarshalToMsg(m *msg.NewProxy) {
  368. c.ProxyBaseConfig.MarshalToMsg(m)
  369. m.Sk = c.Secretkey
  370. m.AllowUsers = c.AllowUsers
  371. }
  372. func (c *SUDPProxyConfig) UnmarshalFromMsg(m *msg.NewProxy) {
  373. c.ProxyBaseConfig.UnmarshalFromMsg(m)
  374. c.Secretkey = m.Sk
  375. c.AllowUsers = m.AllowUsers
  376. }