client.go 15 KB

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