client_common.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  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. "strconv"
  19. "strings"
  20. ini "github.com/vaughan0/go-ini"
  21. "github.com/fatedier/frp/models/auth"
  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
  28. // ServerAddr specifies the address of the server to connect to. By
  29. // default, this value is "0.0.0.0".
  30. ServerAddr string `json:"server_addr"`
  31. // ServerPort specifies the port to connect to the server on. By default,
  32. // this value is 7000.
  33. ServerPort int `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 `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 `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 `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 `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 `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 `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 `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 `json:"admin_port"`
  64. // AdminUser specifies the username that the admin server will use for
  65. // login. By default, this value is "admin".
  66. AdminUser string `json:"admin_user"`
  67. // AdminPwd specifies the password that the admin server will use for
  68. // login. By default, this value is "admin".
  69. AdminPwd string `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 `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 `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 `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 `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 `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 `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 map[string]struct{} `json:"start"`
  97. // Protocol specifies the protocol to use when interacting with the server.
  98. // Valid values are "tcp", "kcp", and "websocket". By default, this value
  99. // is "tcp".
  100. Protocol string `json:"protocol"`
  101. // TLSEnable specifies whether or not TLS should be used when communicating
  102. // with the server.
  103. TLSEnable bool `json:"tls_enable"`
  104. // HeartBeatInterval specifies at what interval heartbeats are sent to the
  105. // server, in seconds. It is not recommended to change this value. By
  106. // default, this value is 30.
  107. HeartBeatInterval int64 `json:"heartbeat_interval"`
  108. // HeartBeatTimeout specifies the maximum allowed heartbeat response delay
  109. // before the connection is terminated, in seconds. It is not recommended
  110. // to change this value. By default, this value is 90.
  111. HeartBeatTimeout int64 `json:"heartbeat_timeout"`
  112. // Client meta info
  113. Metas map[string]string `json:"metas"`
  114. // UDPPacketSize specifies the udp packet size
  115. // By default, this value is 1500
  116. UDPPacketSize int64 `json:"udp_packet_size"`
  117. }
  118. // GetDefaultClientConf returns a client configuration with default values.
  119. func GetDefaultClientConf() ClientCommonConf {
  120. return ClientCommonConf{
  121. ServerAddr: "0.0.0.0",
  122. ServerPort: 7000,
  123. HTTPProxy: os.Getenv("http_proxy"),
  124. LogFile: "console",
  125. LogWay: "console",
  126. LogLevel: "info",
  127. LogMaxDays: 3,
  128. DisableLogColor: false,
  129. AdminAddr: "127.0.0.1",
  130. AdminPort: 0,
  131. AdminUser: "",
  132. AdminPwd: "",
  133. AssetsDir: "",
  134. PoolCount: 1,
  135. TCPMux: true,
  136. User: "",
  137. DNSServer: "",
  138. LoginFailExit: true,
  139. Start: make(map[string]struct{}),
  140. Protocol: "tcp",
  141. TLSEnable: false,
  142. HeartBeatInterval: 30,
  143. HeartBeatTimeout: 90,
  144. Metas: make(map[string]string),
  145. UDPPacketSize: 1500,
  146. }
  147. }
  148. func UnmarshalClientConfFromIni(content string) (cfg ClientCommonConf, err error) {
  149. cfg = GetDefaultClientConf()
  150. conf, err := ini.Load(strings.NewReader(content))
  151. if err != nil {
  152. return ClientCommonConf{}, fmt.Errorf("parse ini conf file error: %v", err)
  153. }
  154. cfg.ClientConfig = auth.UnmarshalClientConfFromIni(conf)
  155. var (
  156. tmpStr string
  157. ok bool
  158. v int64
  159. )
  160. if tmpStr, ok = conf.Get("common", "server_addr"); ok {
  161. cfg.ServerAddr = tmpStr
  162. }
  163. if tmpStr, ok = conf.Get("common", "server_port"); ok {
  164. v, err = strconv.ParseInt(tmpStr, 10, 64)
  165. if err != nil {
  166. err = fmt.Errorf("Parse conf error: invalid server_port")
  167. return
  168. }
  169. cfg.ServerPort = int(v)
  170. }
  171. if tmpStr, ok = conf.Get("common", "disable_log_color"); ok && tmpStr == "true" {
  172. cfg.DisableLogColor = true
  173. }
  174. if tmpStr, ok = conf.Get("common", "http_proxy"); ok {
  175. cfg.HTTPProxy = tmpStr
  176. }
  177. if tmpStr, ok = conf.Get("common", "log_file"); ok {
  178. cfg.LogFile = tmpStr
  179. if cfg.LogFile == "console" {
  180. cfg.LogWay = "console"
  181. } else {
  182. cfg.LogWay = "file"
  183. }
  184. }
  185. if tmpStr, ok = conf.Get("common", "log_level"); ok {
  186. cfg.LogLevel = tmpStr
  187. }
  188. if tmpStr, ok = conf.Get("common", "log_max_days"); ok {
  189. if v, err = strconv.ParseInt(tmpStr, 10, 64); err == nil {
  190. cfg.LogMaxDays = v
  191. }
  192. }
  193. if tmpStr, ok = conf.Get("common", "admin_addr"); ok {
  194. cfg.AdminAddr = tmpStr
  195. }
  196. if tmpStr, ok = conf.Get("common", "admin_port"); ok {
  197. if v, err = strconv.ParseInt(tmpStr, 10, 64); err == nil {
  198. cfg.AdminPort = int(v)
  199. } else {
  200. err = fmt.Errorf("Parse conf error: invalid admin_port")
  201. return
  202. }
  203. }
  204. if tmpStr, ok = conf.Get("common", "admin_user"); ok {
  205. cfg.AdminUser = tmpStr
  206. }
  207. if tmpStr, ok = conf.Get("common", "admin_pwd"); ok {
  208. cfg.AdminPwd = tmpStr
  209. }
  210. if tmpStr, ok = conf.Get("common", "assets_dir"); ok {
  211. cfg.AssetsDir = tmpStr
  212. }
  213. if tmpStr, ok = conf.Get("common", "pool_count"); ok {
  214. if v, err = strconv.ParseInt(tmpStr, 10, 64); err == nil {
  215. cfg.PoolCount = int(v)
  216. }
  217. }
  218. if tmpStr, ok = conf.Get("common", "tcp_mux"); ok && tmpStr == "false" {
  219. cfg.TCPMux = false
  220. } else {
  221. cfg.TCPMux = true
  222. }
  223. if tmpStr, ok = conf.Get("common", "user"); ok {
  224. cfg.User = tmpStr
  225. }
  226. if tmpStr, ok = conf.Get("common", "dns_server"); ok {
  227. cfg.DNSServer = tmpStr
  228. }
  229. if tmpStr, ok = conf.Get("common", "start"); ok {
  230. proxyNames := strings.Split(tmpStr, ",")
  231. for _, name := range proxyNames {
  232. cfg.Start[strings.TrimSpace(name)] = struct{}{}
  233. }
  234. }
  235. if tmpStr, ok = conf.Get("common", "login_fail_exit"); ok && tmpStr == "false" {
  236. cfg.LoginFailExit = false
  237. } else {
  238. cfg.LoginFailExit = true
  239. }
  240. if tmpStr, ok = conf.Get("common", "protocol"); ok {
  241. // Now it only support tcp and kcp and websocket.
  242. if tmpStr != "tcp" && tmpStr != "kcp" && tmpStr != "websocket" {
  243. err = fmt.Errorf("Parse conf error: invalid protocol")
  244. return
  245. }
  246. cfg.Protocol = tmpStr
  247. }
  248. if tmpStr, ok = conf.Get("common", "tls_enable"); ok && tmpStr == "true" {
  249. cfg.TLSEnable = true
  250. } else {
  251. cfg.TLSEnable = false
  252. }
  253. if tmpStr, ok = conf.Get("common", "heartbeat_timeout"); ok {
  254. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  255. err = fmt.Errorf("Parse conf error: invalid heartbeat_timeout")
  256. return
  257. }
  258. cfg.HeartBeatTimeout = v
  259. }
  260. if tmpStr, ok = conf.Get("common", "heartbeat_interval"); ok {
  261. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  262. err = fmt.Errorf("Parse conf error: invalid heartbeat_interval")
  263. return
  264. }
  265. cfg.HeartBeatInterval = v
  266. }
  267. for k, v := range conf.Section("common") {
  268. if strings.HasPrefix(k, "meta_") {
  269. cfg.Metas[strings.TrimPrefix(k, "meta_")] = v
  270. }
  271. }
  272. if tmpStr, ok = conf.Get("common", "udp_packet_size"); ok {
  273. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  274. err = fmt.Errorf("Parse conf error: invalid udp_packet_size")
  275. return
  276. }
  277. cfg.UDPPacketSize = v
  278. }
  279. return
  280. }
  281. func (cfg *ClientCommonConf) Check() (err error) {
  282. if cfg.HeartBeatInterval <= 0 {
  283. err = fmt.Errorf("Parse conf error: invalid heartbeat_interval")
  284. return
  285. }
  286. if cfg.HeartBeatTimeout < cfg.HeartBeatInterval {
  287. err = fmt.Errorf("Parse conf error: invalid heartbeat_timeout, heartbeat_timeout is less than heartbeat_interval")
  288. return
  289. }
  290. return
  291. }