1
0

client.go 14 KB

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