proxy.go 13 KB

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