server_common.go 15 KB

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