client.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // Copyright 2020 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 config
  15. import (
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "github.com/samber/lo"
  21. "gopkg.in/ini.v1"
  22. "github.com/fatedier/frp/pkg/auth"
  23. "github.com/fatedier/frp/pkg/util/util"
  24. )
  25. // ClientCommonConf contains information for a client service. It is
  26. // recommended to use GetDefaultClientConf instead of creating this object
  27. // directly, so that all unspecified fields have reasonable default values.
  28. type ClientCommonConf struct {
  29. auth.ClientConfig `ini:",extends"`
  30. // ServerAddr specifies the address of the server to connect to. By
  31. // default, this value is "0.0.0.0".
  32. ServerAddr string `ini:"server_addr" json:"server_addr"`
  33. // ServerPort specifies the port to connect to the server on. By default,
  34. // this value is 7000.
  35. ServerPort int `ini:"server_port" json:"server_port"`
  36. // STUN server to help penetrate NAT hole.
  37. NatHoleSTUNServer string `ini:"nat_hole_stun_server" json:"nat_hole_stun_server"`
  38. // The maximum amount of time a dial to server will wait for a connect to complete.
  39. DialServerTimeout int64 `ini:"dial_server_timeout" json:"dial_server_timeout"`
  40. // DialServerKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
  41. // If negative, keep-alive probes are disabled.
  42. DialServerKeepAlive int64 `ini:"dial_server_keepalive" json:"dial_server_keepalive"`
  43. // ConnectServerLocalIP specifies the address of the client bind when it connect to server.
  44. // By default, this value is empty.
  45. // this value only use in TCP/Websocket protocol. Not support in KCP protocol.
  46. ConnectServerLocalIP string `ini:"connect_server_local_ip" json:"connect_server_local_ip"`
  47. // HTTPProxy specifies a proxy address to connect to the server through. If
  48. // this value is "", the server will be connected to directly. By default,
  49. // this value is read from the "http_proxy" environment variable.
  50. HTTPProxy string `ini:"http_proxy" json:"http_proxy"`
  51. // LogFile specifies a file where logs will be written to. This value will
  52. // only be used if LogWay is set appropriately. By default, this value is
  53. // "console".
  54. LogFile string `ini:"log_file" json:"log_file"`
  55. // LogWay specifies the way logging is managed. Valid values are "console"
  56. // or "file". If "console" is used, logs will be printed to stdout. If
  57. // "file" is used, logs will be printed to LogFile. By default, this value
  58. // is "console".
  59. LogWay string `ini:"log_way" json:"log_way"`
  60. // LogLevel specifies the minimum log level. Valid values are "trace",
  61. // "debug", "info", "warn", and "error". By default, this value is "info".
  62. LogLevel string `ini:"log_level" json:"log_level"`
  63. // LogMaxDays specifies the maximum number of days to store log information
  64. // before deletion. This is only used if LogWay == "file". By default, this
  65. // value is 0.
  66. LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"`
  67. // DisableLogColor disables log colors when LogWay == "console" when set to
  68. // true. By default, this value is false.
  69. DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"`
  70. // AdminAddr specifies the address that the admin server binds to. By
  71. // default, this value is "127.0.0.1".
  72. AdminAddr string `ini:"admin_addr" json:"admin_addr"`
  73. // AdminPort specifies the port for the admin server to listen on. If this
  74. // value is 0, the admin server will not be started. By default, this value
  75. // is 0.
  76. AdminPort int `ini:"admin_port" json:"admin_port"`
  77. // AdminUser specifies the username that the admin server will use for
  78. // login.
  79. AdminUser string `ini:"admin_user" json:"admin_user"`
  80. // AdminPwd specifies the password that the admin server will use for
  81. // login.
  82. AdminPwd string `ini:"admin_pwd" json:"admin_pwd"`
  83. // AssetsDir specifies the local directory that the admin server will load
  84. // resources from. If this value is "", assets will be loaded from the
  85. // bundled executable using statik. By default, this value is "".
  86. AssetsDir string `ini:"assets_dir" json:"assets_dir"`
  87. // PoolCount specifies the number of connections the client will make to
  88. // the server in advance. By default, this value is 0.
  89. PoolCount int `ini:"pool_count" json:"pool_count"`
  90. // TCPMux toggles TCP stream multiplexing. This allows multiple requests
  91. // from a client to share a single TCP connection. If this value is true,
  92. // the server must have TCP multiplexing enabled as well. By default, this
  93. // value is true.
  94. TCPMux bool `ini:"tcp_mux" json:"tcp_mux"`
  95. // TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multipler.
  96. // If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
  97. TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"`
  98. // User specifies a prefix for proxy names to distinguish them from other
  99. // clients. If this value is not "", proxy names will automatically be
  100. // changed to "{user}.{proxy_name}". By default, this value is "".
  101. User string `ini:"user" json:"user"`
  102. // DNSServer specifies a DNS server address for FRPC to use. If this value
  103. // is "", the default DNS will be used. By default, this value is "".
  104. DNSServer string `ini:"dns_server" json:"dns_server"`
  105. // LoginFailExit controls whether or not the client should exit after a
  106. // failed login attempt. If false, the client will retry until a login
  107. // attempt succeeds. By default, this value is true.
  108. LoginFailExit bool `ini:"login_fail_exit" json:"login_fail_exit"`
  109. // Start specifies a set of enabled proxies by name. If this set is empty,
  110. // all supplied proxies are enabled. By default, this value is an empty
  111. // set.
  112. Start []string `ini:"start" json:"start"`
  113. // Start map[string]struct{} `json:"start"`
  114. // Protocol specifies the protocol to use when interacting with the server.
  115. // Valid values are "tcp", "kcp", "quic", "websocket" and "wss". By default, this value
  116. // is "tcp".
  117. Protocol string `ini:"protocol" json:"protocol"`
  118. // QUIC protocol options
  119. QUICKeepalivePeriod int `ini:"quic_keepalive_period" json:"quic_keepalive_period" validate:"gte=0"`
  120. QUICMaxIdleTimeout int `ini:"quic_max_idle_timeout" json:"quic_max_idle_timeout" validate:"gte=0"`
  121. QUICMaxIncomingStreams int `ini:"quic_max_incoming_streams" json:"quic_max_incoming_streams" validate:"gte=0"`
  122. // TLSEnable specifies whether or not TLS should be used when communicating
  123. // with the server. If "tls_cert_file" and "tls_key_file" are valid,
  124. // client will load the supplied tls configuration.
  125. // Since v0.50.0, the default value has been changed to true, and tls is enabled by default.
  126. TLSEnable bool `ini:"tls_enable" json:"tls_enable"`
  127. // TLSCertPath specifies the path of the cert file that client will
  128. // load. It only works when "tls_enable" is true and "tls_key_file" is valid.
  129. TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
  130. // TLSKeyPath specifies the path of the secret key file that client
  131. // will load. It only works when "tls_enable" is true and "tls_cert_file"
  132. // are valid.
  133. TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
  134. // TLSTrustedCaFile specifies the path of the trusted ca file that will load.
  135. // It only works when "tls_enable" is valid and tls configuration of server
  136. // has been specified.
  137. TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
  138. // TLSServerName specifies the custom server name of tls certificate. By
  139. // default, server name if same to ServerAddr.
  140. TLSServerName string `ini:"tls_server_name" json:"tls_server_name"`
  141. // If the disable_custom_tls_first_byte is set to false, frpc will establish a connection with frps using the
  142. // first custom byte when tls is enabled.
  143. // Since v0.50.0, the default value has been changed to true, and the first custom byte is disabled by default.
  144. DisableCustomTLSFirstByte bool `ini:"disable_custom_tls_first_byte" json:"disable_custom_tls_first_byte"`
  145. // HeartBeatInterval specifies at what interval heartbeats are sent to the
  146. // server, in seconds. It is not recommended to change this value. By
  147. // default, this value is 30. Set negative value to disable it.
  148. HeartbeatInterval int64 `ini:"heartbeat_interval" json:"heartbeat_interval"`
  149. // HeartBeatTimeout specifies the maximum allowed heartbeat response delay
  150. // before the connection is terminated, in seconds. It is not recommended
  151. // to change this value. By default, this value is 90. Set negative value to disable it.
  152. HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
  153. // Client meta info
  154. Metas map[string]string `ini:"-" json:"metas"`
  155. // UDPPacketSize specifies the udp packet size
  156. // By default, this value is 1500
  157. UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
  158. // Include other config files for proxies.
  159. IncludeConfigFiles []string `ini:"includes" json:"includes"`
  160. // Enable golang pprof handlers in admin listener.
  161. // Admin port must be set first.
  162. PprofEnable bool `ini:"pprof_enable" json:"pprof_enable"`
  163. }
  164. // GetDefaultClientConf returns a client configuration with default values.
  165. func GetDefaultClientConf() ClientCommonConf {
  166. return ClientCommonConf{
  167. ClientConfig: auth.GetDefaultClientConf(),
  168. ServerAddr: "0.0.0.0",
  169. ServerPort: 7000,
  170. NatHoleSTUNServer: "stun.easyvoip.com:3478",
  171. DialServerTimeout: 10,
  172. DialServerKeepAlive: 7200,
  173. HTTPProxy: os.Getenv("http_proxy"),
  174. LogFile: "console",
  175. LogWay: "console",
  176. LogLevel: "info",
  177. LogMaxDays: 3,
  178. AdminAddr: "127.0.0.1",
  179. PoolCount: 1,
  180. TCPMux: true,
  181. TCPMuxKeepaliveInterval: 60,
  182. LoginFailExit: true,
  183. Start: make([]string, 0),
  184. Protocol: "tcp",
  185. QUICKeepalivePeriod: 10,
  186. QUICMaxIdleTimeout: 30,
  187. QUICMaxIncomingStreams: 100000,
  188. TLSEnable: true,
  189. DisableCustomTLSFirstByte: true,
  190. HeartbeatInterval: 30,
  191. HeartbeatTimeout: 90,
  192. Metas: make(map[string]string),
  193. UDPPacketSize: 1500,
  194. IncludeConfigFiles: make([]string, 0),
  195. }
  196. }
  197. func (cfg *ClientCommonConf) Complete() {
  198. if cfg.LogFile == "console" {
  199. cfg.LogWay = "console"
  200. } else {
  201. cfg.LogWay = "file"
  202. }
  203. }
  204. func (cfg *ClientCommonConf) Validate() error {
  205. if cfg.HeartbeatTimeout > 0 && cfg.HeartbeatInterval > 0 {
  206. if cfg.HeartbeatTimeout < cfg.HeartbeatInterval {
  207. return fmt.Errorf("invalid heartbeat_timeout, heartbeat_timeout is less than heartbeat_interval")
  208. }
  209. }
  210. if !cfg.TLSEnable {
  211. if cfg.TLSCertFile != "" {
  212. fmt.Println("WARNING! tls_cert_file is invalid when tls_enable is false")
  213. }
  214. if cfg.TLSKeyFile != "" {
  215. fmt.Println("WARNING! tls_key_file is invalid when tls_enable is false")
  216. }
  217. if cfg.TLSTrustedCaFile != "" {
  218. fmt.Println("WARNING! tls_trusted_ca_file is invalid when tls_enable is false")
  219. }
  220. }
  221. if !lo.Contains([]string{"tcp", "kcp", "quic", "websocket", "wss"}, cfg.Protocol) {
  222. return fmt.Errorf("invalid protocol")
  223. }
  224. for _, f := range cfg.IncludeConfigFiles {
  225. absDir, err := filepath.Abs(filepath.Dir(f))
  226. if err != nil {
  227. return fmt.Errorf("include: parse directory of %s failed: %v", f, absDir)
  228. }
  229. if _, err := os.Stat(absDir); os.IsNotExist(err) {
  230. return fmt.Errorf("include: directory of %s not exist", f)
  231. }
  232. }
  233. return nil
  234. }
  235. // Supported sources including: string(file path), []byte, Reader interface.
  236. func UnmarshalClientConfFromIni(source interface{}) (ClientCommonConf, error) {
  237. f, err := ini.LoadSources(ini.LoadOptions{
  238. Insensitive: false,
  239. InsensitiveSections: false,
  240. InsensitiveKeys: false,
  241. IgnoreInlineComment: true,
  242. AllowBooleanKeys: true,
  243. }, source)
  244. if err != nil {
  245. return ClientCommonConf{}, err
  246. }
  247. s, err := f.GetSection("common")
  248. if err != nil {
  249. return ClientCommonConf{}, fmt.Errorf("invalid configuration file, not found [common] section")
  250. }
  251. common := GetDefaultClientConf()
  252. err = s.MapTo(&common)
  253. if err != nil {
  254. return ClientCommonConf{}, err
  255. }
  256. common.Metas = GetMapWithoutPrefix(s.KeysHash(), "meta_")
  257. common.ClientConfig.OidcAdditionalEndpointParams = GetMapWithoutPrefix(s.KeysHash(), "oidc_additional_")
  258. return common, nil
  259. }
  260. // if len(startProxy) is 0, start all
  261. // otherwise just start proxies in startProxy map
  262. func LoadAllProxyConfsFromIni(
  263. prefix string,
  264. source interface{},
  265. start []string,
  266. ) (map[string]ProxyConf, map[string]VisitorConf, error) {
  267. f, err := ini.LoadSources(ini.LoadOptions{
  268. Insensitive: false,
  269. InsensitiveSections: false,
  270. InsensitiveKeys: false,
  271. IgnoreInlineComment: true,
  272. AllowBooleanKeys: true,
  273. }, source)
  274. if err != nil {
  275. return nil, nil, err
  276. }
  277. proxyConfs := make(map[string]ProxyConf)
  278. visitorConfs := make(map[string]VisitorConf)
  279. if prefix != "" {
  280. prefix += "."
  281. }
  282. startProxy := make(map[string]struct{})
  283. for _, s := range start {
  284. startProxy[s] = struct{}{}
  285. }
  286. startAll := true
  287. if len(startProxy) > 0 {
  288. startAll = false
  289. }
  290. // Build template sections from range section And append to ini.File.
  291. rangeSections := make([]*ini.Section, 0)
  292. for _, section := range f.Sections() {
  293. if !strings.HasPrefix(section.Name(), "range:") {
  294. continue
  295. }
  296. rangeSections = append(rangeSections, section)
  297. }
  298. for _, section := range rangeSections {
  299. err = renderRangeProxyTemplates(f, section)
  300. if err != nil {
  301. return nil, nil, fmt.Errorf("failed to render template for proxy %s: %v", section.Name(), err)
  302. }
  303. }
  304. for _, section := range f.Sections() {
  305. name := section.Name()
  306. if name == ini.DefaultSection || name == "common" || strings.HasPrefix(name, "range:") {
  307. continue
  308. }
  309. _, shouldStart := startProxy[name]
  310. if !startAll && !shouldStart {
  311. continue
  312. }
  313. roleType := section.Key("role").String()
  314. if roleType == "" {
  315. roleType = "server"
  316. }
  317. switch roleType {
  318. case "server":
  319. newConf, newErr := NewProxyConfFromIni(prefix, name, section)
  320. if newErr != nil {
  321. return nil, nil, fmt.Errorf("failed to parse proxy %s, err: %v", name, newErr)
  322. }
  323. proxyConfs[prefix+name] = newConf
  324. case "visitor":
  325. newConf, newErr := NewVisitorConfFromIni(prefix, name, section)
  326. if newErr != nil {
  327. return nil, nil, fmt.Errorf("failed to parse visitor %s, err: %v", name, newErr)
  328. }
  329. visitorConfs[prefix+name] = newConf
  330. default:
  331. return nil, nil, fmt.Errorf("proxy %s role should be 'server' or 'visitor'", name)
  332. }
  333. }
  334. return proxyConfs, visitorConfs, nil
  335. }
  336. func renderRangeProxyTemplates(f *ini.File, section *ini.Section) error {
  337. // Validation
  338. localPortStr := section.Key("local_port").String()
  339. remotePortStr := section.Key("remote_port").String()
  340. if localPortStr == "" || remotePortStr == "" {
  341. return fmt.Errorf("local_port or remote_port is empty")
  342. }
  343. localPorts, err := util.ParseRangeNumbers(localPortStr)
  344. if err != nil {
  345. return err
  346. }
  347. remotePorts, err := util.ParseRangeNumbers(remotePortStr)
  348. if err != nil {
  349. return err
  350. }
  351. if len(localPorts) != len(remotePorts) {
  352. return fmt.Errorf("local ports number should be same with remote ports number")
  353. }
  354. if len(localPorts) == 0 {
  355. return fmt.Errorf("local_port and remote_port is necessary")
  356. }
  357. // Templates
  358. prefix := strings.TrimSpace(strings.TrimPrefix(section.Name(), "range:"))
  359. for i := range localPorts {
  360. tmpname := fmt.Sprintf("%s_%d", prefix, i)
  361. tmpsection, err := f.NewSection(tmpname)
  362. if err != nil {
  363. return err
  364. }
  365. copySection(section, tmpsection)
  366. if _, err := tmpsection.NewKey("local_port", fmt.Sprintf("%d", localPorts[i])); err != nil {
  367. return fmt.Errorf("local_port new key in section error: %v", err)
  368. }
  369. if _, err := tmpsection.NewKey("remote_port", fmt.Sprintf("%d", remotePorts[i])); err != nil {
  370. return fmt.Errorf("remote_port new key in section error: %v", err)
  371. }
  372. }
  373. return nil
  374. }
  375. func copySection(source, target *ini.Section) {
  376. for key, value := range source.KeysHash() {
  377. _, _ = target.NewKey(key, value)
  378. }
  379. }