server_common.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. "strconv"
  18. "strings"
  19. ini "github.com/vaughan0/go-ini"
  20. plugin "github.com/fatedier/frp/models/plugin/server"
  21. "github.com/fatedier/frp/utils/util"
  22. )
  23. // ServerCommonConf contains information for a server service. It is
  24. // recommended to use GetDefaultServerConf instead of creating this object
  25. // directly, so that all unspecified fields have reasonable default values.
  26. type ServerCommonConf struct {
  27. // BindAddr specifies the address that the server binds to. By default,
  28. // this value is "0.0.0.0".
  29. BindAddr string `json:"bind_addr"`
  30. // BindPort specifies the port that the server listens on. By default, this
  31. // value is 7000.
  32. BindPort int `json:"bind_port"`
  33. // BindUdpPort specifies the UDP port that the server listens on. If this
  34. // value is 0, the server will not listen for UDP connections. By default,
  35. // this value is 0
  36. BindUdpPort int `json:"bind_udp_port"`
  37. // BindKcpPort specifies the KCP port that the server listens on. If this
  38. // value is 0, the server will not listen for KCP connections. By default,
  39. // this value is 0.
  40. KcpBindPort int `json:"kcp_bind_port"`
  41. // ProxyBindAddr specifies the address that the proxy binds to. This value
  42. // may be the same as BindAddr. By default, this value is "0.0.0.0".
  43. ProxyBindAddr string `json:"proxy_bind_addr"`
  44. // VhostHttpPort specifies the port that the server listens for HTTP Vhost
  45. // requests. If this value is 0, the server will not listen for HTTP
  46. // requests. By default, this value is 0.
  47. VhostHttpPort int `json:"vhost_http_port"`
  48. // VhostHttpsPort specifies the port that the server listens for HTTPS
  49. // Vhost requests. If this value is 0, the server will not listen for HTTPS
  50. // requests. By default, this value is 0.
  51. VhostHttpsPort int `json:"vhost_https_port"`
  52. // VhostHttpTimeout specifies the response header timeout for the Vhost
  53. // HTTP server, in seconds. By default, this value is 60.
  54. VhostHttpTimeout int64 `json:"vhost_http_timeout"`
  55. // DashboardAddr specifies the address that the dashboard binds to. By
  56. // default, this value is "0.0.0.0".
  57. DashboardAddr string `json:"dashboard_addr"`
  58. // DashboardPort specifies the port that the dashboard listens on. If this
  59. // value is 0, the dashboard will not be started. By default, this value is
  60. // 0.
  61. DashboardPort int `json:"dashboard_port"`
  62. // DashboardUser specifies the username that the dashboard will use for
  63. // login. By default, this value is "admin".
  64. DashboardUser string `json:"dashboard_user"`
  65. // DashboardUser specifies the password that the dashboard will use for
  66. // login. By default, this value is "admin".
  67. DashboardPwd string `json:"dashboard_pwd"`
  68. // AssetsDir specifies the local directory that the dashboard will load
  69. // resources from. If this value is "", assets will be loaded from the
  70. // bundled executable using statik. By default, this value is "".
  71. AssetsDir string `json:"asserts_dir"`
  72. // LogFile specifies a file where logs will be written to. This value will
  73. // only be used if LogWay is set appropriately. By default, this value is
  74. // "console".
  75. LogFile string `json:"log_file"`
  76. // LogWay specifies the way logging is managed. Valid values are "console"
  77. // or "file". If "console" is used, logs will be printed to stdout. If
  78. // "file" is used, logs will be printed to LogFile. By default, this value
  79. // is "console".
  80. LogWay string `json:"log_way"`
  81. // LogLevel specifies the minimum log level. Valid values are "trace",
  82. // "debug", "info", "warn", and "error". By default, this value is "info".
  83. LogLevel string `json:"log_level"`
  84. // LogMaxDays specifies the maximum number of days to store log information
  85. // before deletion. This is only used if LogWay == "file". By default, this
  86. // value is 0.
  87. LogMaxDays int64 `json:"log_max_days"`
  88. // DisableLogColor disables log colors when LogWay == "console" when set to
  89. // true. By default, this value is false.
  90. DisableLogColor bool `json:"disable_log_color"`
  91. // DetailedErrorsToClient defines whether to send the specific error (with
  92. // debug info) to frpc. By default, this value is true.
  93. DetailedErrorsToClient bool `json:"detailed_errors_to_client"`
  94. // Token specifies the authorization token used to authenticate keys
  95. // received from clients. Clients must have a matching token to be
  96. // authorized to use the server. By default, this value is "".
  97. Token string `json:"token"`
  98. // SubDomainHost specifies the domain that will be attached to sub-domains
  99. // requested by the client when using Vhost proxying. For example, if this
  100. // value is set to "frps.com" and the client requested the subdomain
  101. // "test", the resulting URL would be "test.frps.com". By default, this
  102. // value is "".
  103. SubDomainHost string `json:"subdomain_host"`
  104. // TcpMux toggles TCP stream multiplexing. This allows multiple requests
  105. // from a client to share a single TCP connection. By default, this value
  106. // is true.
  107. TcpMux bool `json:"tcp_mux"`
  108. // Custom404Page specifies a path to a custom 404 page to display. If this
  109. // value is "", a default page will be displayed. By default, this value is
  110. // "".
  111. Custom404Page string `json:"custom_404_page"`
  112. // AllowPorts specifies a set of ports that clients are able to proxy to.
  113. // If the length of this value is 0, all ports are allowed. By default,
  114. // this value is an empty set.
  115. AllowPorts map[int]struct{}
  116. // MaxPoolCount specifies the maximum pool size for each proxy. By default,
  117. // this value is 5.
  118. MaxPoolCount int64 `json:"max_pool_count"`
  119. // MaxPortsPerClient specifies the maximum number of ports a single client
  120. // may proxy to. If this value is 0, no limit will be applied. By default,
  121. // this value is 0.
  122. MaxPortsPerClient int64 `json:"max_ports_per_client"`
  123. // TlsOnly specifies whether to only accept TLS-encrypted connections. By
  124. // default, the value is false.
  125. TlsOnly bool `json:"tls_only"`
  126. // HeartBeatTimeout specifies the maximum time to wait for a heartbeat
  127. // before terminating the connection. It is not recommended to change this
  128. // value. By default, this value is 90.
  129. HeartBeatTimeout int64 `json:"heart_beat_timeout"`
  130. // UserConnTimeout specifies the maximum time to wait for a work
  131. // connection. By default, this value is 10.
  132. UserConnTimeout int64 `json:"user_conn_timeout"`
  133. // HTTPPlugins specify the server plugins support HTTP protocol.
  134. HTTPPlugins map[string]plugin.HTTPPluginOptions `json:"http_plugins"`
  135. }
  136. // GetDefaultServerConf returns a server configuration with reasonable
  137. // defaults.
  138. func GetDefaultServerConf() ServerCommonConf {
  139. return ServerCommonConf{
  140. BindAddr: "0.0.0.0",
  141. BindPort: 7000,
  142. BindUdpPort: 0,
  143. KcpBindPort: 0,
  144. ProxyBindAddr: "0.0.0.0",
  145. VhostHttpPort: 0,
  146. VhostHttpsPort: 0,
  147. VhostHttpTimeout: 60,
  148. DashboardAddr: "0.0.0.0",
  149. DashboardPort: 0,
  150. DashboardUser: "admin",
  151. DashboardPwd: "admin",
  152. AssetsDir: "",
  153. LogFile: "console",
  154. LogWay: "console",
  155. LogLevel: "info",
  156. LogMaxDays: 3,
  157. DisableLogColor: false,
  158. DetailedErrorsToClient: true,
  159. Token: "",
  160. SubDomainHost: "",
  161. TcpMux: true,
  162. AllowPorts: make(map[int]struct{}),
  163. MaxPoolCount: 5,
  164. MaxPortsPerClient: 0,
  165. TlsOnly: false,
  166. HeartBeatTimeout: 90,
  167. UserConnTimeout: 10,
  168. Custom404Page: "",
  169. HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
  170. }
  171. }
  172. // UnmarshalServerConfFromIni parses the contents of a server configuration ini
  173. // file and returns the resulting server configuration.
  174. func UnmarshalServerConfFromIni(content string) (cfg ServerCommonConf, err error) {
  175. cfg = GetDefaultServerConf()
  176. conf, err := ini.Load(strings.NewReader(content))
  177. if err != nil {
  178. err = fmt.Errorf("parse ini conf file error: %v", err)
  179. return ServerCommonConf{}, err
  180. }
  181. UnmarshalPluginsFromIni(conf, &cfg)
  182. var (
  183. tmpStr string
  184. ok bool
  185. v int64
  186. )
  187. if tmpStr, ok = conf.Get("common", "bind_addr"); ok {
  188. cfg.BindAddr = tmpStr
  189. }
  190. if tmpStr, ok = conf.Get("common", "bind_port"); ok {
  191. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  192. err = fmt.Errorf("Parse conf error: invalid bind_port")
  193. return
  194. } else {
  195. cfg.BindPort = int(v)
  196. }
  197. }
  198. if tmpStr, ok = conf.Get("common", "bind_udp_port"); ok {
  199. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  200. err = fmt.Errorf("Parse conf error: invalid bind_udp_port")
  201. return
  202. } else {
  203. cfg.BindUdpPort = int(v)
  204. }
  205. }
  206. if tmpStr, ok = conf.Get("common", "kcp_bind_port"); ok {
  207. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  208. err = fmt.Errorf("Parse conf error: invalid kcp_bind_port")
  209. return
  210. } else {
  211. cfg.KcpBindPort = int(v)
  212. }
  213. }
  214. if tmpStr, ok = conf.Get("common", "proxy_bind_addr"); ok {
  215. cfg.ProxyBindAddr = tmpStr
  216. } else {
  217. cfg.ProxyBindAddr = cfg.BindAddr
  218. }
  219. if tmpStr, ok = conf.Get("common", "vhost_http_port"); ok {
  220. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  221. err = fmt.Errorf("Parse conf error: invalid vhost_http_port")
  222. return
  223. } else {
  224. cfg.VhostHttpPort = int(v)
  225. }
  226. } else {
  227. cfg.VhostHttpPort = 0
  228. }
  229. if tmpStr, ok = conf.Get("common", "vhost_https_port"); ok {
  230. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  231. err = fmt.Errorf("Parse conf error: invalid vhost_https_port")
  232. return
  233. } else {
  234. cfg.VhostHttpsPort = int(v)
  235. }
  236. } else {
  237. cfg.VhostHttpsPort = 0
  238. }
  239. if tmpStr, ok = conf.Get("common", "vhost_http_timeout"); ok {
  240. v, errRet := strconv.ParseInt(tmpStr, 10, 64)
  241. if errRet != nil || v < 0 {
  242. err = fmt.Errorf("Parse conf error: invalid vhost_http_timeout")
  243. return
  244. } else {
  245. cfg.VhostHttpTimeout = v
  246. }
  247. }
  248. if tmpStr, ok = conf.Get("common", "dashboard_addr"); ok {
  249. cfg.DashboardAddr = tmpStr
  250. } else {
  251. cfg.DashboardAddr = cfg.BindAddr
  252. }
  253. if tmpStr, ok = conf.Get("common", "dashboard_port"); ok {
  254. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  255. err = fmt.Errorf("Parse conf error: invalid dashboard_port")
  256. return
  257. } else {
  258. cfg.DashboardPort = int(v)
  259. }
  260. } else {
  261. cfg.DashboardPort = 0
  262. }
  263. if tmpStr, ok = conf.Get("common", "dashboard_user"); ok {
  264. cfg.DashboardUser = tmpStr
  265. }
  266. if tmpStr, ok = conf.Get("common", "dashboard_pwd"); ok {
  267. cfg.DashboardPwd = tmpStr
  268. }
  269. if tmpStr, ok = conf.Get("common", "assets_dir"); ok {
  270. cfg.AssetsDir = tmpStr
  271. }
  272. if tmpStr, ok = conf.Get("common", "log_file"); ok {
  273. cfg.LogFile = tmpStr
  274. if cfg.LogFile == "console" {
  275. cfg.LogWay = "console"
  276. } else {
  277. cfg.LogWay = "file"
  278. }
  279. }
  280. if tmpStr, ok = conf.Get("common", "log_level"); ok {
  281. cfg.LogLevel = tmpStr
  282. }
  283. if tmpStr, ok = conf.Get("common", "log_max_days"); ok {
  284. v, err = strconv.ParseInt(tmpStr, 10, 64)
  285. if err == nil {
  286. cfg.LogMaxDays = v
  287. }
  288. }
  289. if tmpStr, ok = conf.Get("common", "disable_log_color"); ok && tmpStr == "true" {
  290. cfg.DisableLogColor = true
  291. }
  292. if tmpStr, ok = conf.Get("common", "detailed_errors_to_client"); ok && tmpStr == "false" {
  293. cfg.DetailedErrorsToClient = false
  294. } else {
  295. cfg.DetailedErrorsToClient = true
  296. }
  297. cfg.Token, _ = conf.Get("common", "token")
  298. if allowPortsStr, ok := conf.Get("common", "allow_ports"); ok {
  299. // e.g. 1000-2000,2001,2002,3000-4000
  300. ports, errRet := util.ParseRangeNumbers(allowPortsStr)
  301. if errRet != nil {
  302. err = fmt.Errorf("Parse conf error: allow_ports: %v", errRet)
  303. return
  304. }
  305. for _, port := range ports {
  306. cfg.AllowPorts[int(port)] = struct{}{}
  307. }
  308. }
  309. if tmpStr, ok = conf.Get("common", "max_pool_count"); ok {
  310. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  311. err = fmt.Errorf("Parse conf error: invalid max_pool_count")
  312. return
  313. } else {
  314. if v < 0 {
  315. err = fmt.Errorf("Parse conf error: invalid max_pool_count")
  316. return
  317. }
  318. cfg.MaxPoolCount = v
  319. }
  320. }
  321. if tmpStr, ok = conf.Get("common", "max_ports_per_client"); ok {
  322. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  323. err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
  324. return
  325. } else {
  326. if v < 0 {
  327. err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
  328. return
  329. }
  330. cfg.MaxPortsPerClient = v
  331. }
  332. }
  333. if tmpStr, ok = conf.Get("common", "subdomain_host"); ok {
  334. cfg.SubDomainHost = strings.ToLower(strings.TrimSpace(tmpStr))
  335. }
  336. if tmpStr, ok = conf.Get("common", "tcp_mux"); ok && tmpStr == "false" {
  337. cfg.TcpMux = false
  338. } else {
  339. cfg.TcpMux = true
  340. }
  341. if tmpStr, ok = conf.Get("common", "custom_404_page"); ok {
  342. cfg.Custom404Page = tmpStr
  343. }
  344. if tmpStr, ok = conf.Get("common", "heartbeat_timeout"); ok {
  345. v, errRet := strconv.ParseInt(tmpStr, 10, 64)
  346. if errRet != nil {
  347. err = fmt.Errorf("Parse conf error: heartbeat_timeout is incorrect")
  348. return
  349. } else {
  350. cfg.HeartBeatTimeout = v
  351. }
  352. }
  353. if tmpStr, ok = conf.Get("common", "tls_only"); ok && tmpStr == "true" {
  354. cfg.TlsOnly = true
  355. } else {
  356. cfg.TlsOnly = false
  357. }
  358. return
  359. }
  360. func UnmarshalPluginsFromIni(sections ini.File, cfg *ServerCommonConf) {
  361. for name, section := range sections {
  362. if strings.HasPrefix(name, "plugin.") {
  363. name = strings.TrimSpace(strings.TrimPrefix(name, "plugin."))
  364. options := plugin.HTTPPluginOptions{
  365. Name: name,
  366. Addr: section["addr"],
  367. Path: section["path"],
  368. Ops: strings.Split(section["ops"], ","),
  369. }
  370. for i, _ := range options.Ops {
  371. options.Ops[i] = strings.TrimSpace(options.Ops[i])
  372. }
  373. cfg.HTTPPlugins[name] = options
  374. }
  375. }
  376. }
  377. func (cfg *ServerCommonConf) Check() (err error) {
  378. return
  379. }