client.go 13 KB

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