server_common.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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.ServerConfig
  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. // KCPBindPort 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. // UDPPacketSize specifies the UDP packet size
  142. // By default, this value is 1500
  143. UDPPacketSize int64 `json:"udp_packet_size"`
  144. }
  145. // GetDefaultServerConf returns a server configuration with reasonable
  146. // defaults.
  147. func GetDefaultServerConf() ServerCommonConf {
  148. return ServerCommonConf{
  149. BindAddr: "0.0.0.0",
  150. BindPort: 7000,
  151. BindUDPPort: 0,
  152. KCPBindPort: 0,
  153. ProxyBindAddr: "0.0.0.0",
  154. VhostHTTPPort: 0,
  155. VhostHTTPSPort: 0,
  156. TCPMuxHTTPConnectPort: 0,
  157. VhostHTTPTimeout: 60,
  158. DashboardAddr: "0.0.0.0",
  159. DashboardPort: 0,
  160. DashboardUser: "admin",
  161. DashboardPwd: "admin",
  162. EnablePrometheus: false,
  163. AssetsDir: "",
  164. LogFile: "console",
  165. LogWay: "console",
  166. LogLevel: "info",
  167. LogMaxDays: 3,
  168. DisableLogColor: false,
  169. DetailedErrorsToClient: true,
  170. SubDomainHost: "",
  171. TCPMux: true,
  172. AllowPorts: make(map[int]struct{}),
  173. MaxPoolCount: 5,
  174. MaxPortsPerClient: 0,
  175. TLSOnly: false,
  176. HeartBeatTimeout: 90,
  177. UserConnTimeout: 10,
  178. Custom404Page: "",
  179. HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
  180. UDPPacketSize: 1500,
  181. }
  182. }
  183. // UnmarshalServerConfFromIni parses the contents of a server configuration ini
  184. // file and returns the resulting server configuration.
  185. func UnmarshalServerConfFromIni(content string) (cfg ServerCommonConf, err error) {
  186. cfg = GetDefaultServerConf()
  187. conf, err := ini.Load(strings.NewReader(content))
  188. if err != nil {
  189. err = fmt.Errorf("parse ini conf file error: %v", err)
  190. return ServerCommonConf{}, err
  191. }
  192. UnmarshalPluginsFromIni(conf, &cfg)
  193. cfg.ServerConfig = auth.UnmarshalServerConfFromIni(conf)
  194. var (
  195. tmpStr string
  196. ok bool
  197. v int64
  198. )
  199. if tmpStr, ok = conf.Get("common", "bind_addr"); ok {
  200. cfg.BindAddr = tmpStr
  201. }
  202. if tmpStr, ok = conf.Get("common", "bind_port"); ok {
  203. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  204. err = fmt.Errorf("Parse conf error: invalid bind_port")
  205. return
  206. }
  207. cfg.BindPort = int(v)
  208. }
  209. if tmpStr, ok = conf.Get("common", "bind_udp_port"); ok {
  210. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  211. err = fmt.Errorf("Parse conf error: invalid bind_udp_port")
  212. return
  213. }
  214. cfg.BindUDPPort = int(v)
  215. }
  216. if tmpStr, ok = conf.Get("common", "kcp_bind_port"); ok {
  217. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  218. err = fmt.Errorf("Parse conf error: invalid kcp_bind_port")
  219. return
  220. }
  221. cfg.KCPBindPort = int(v)
  222. }
  223. if tmpStr, ok = conf.Get("common", "proxy_bind_addr"); ok {
  224. cfg.ProxyBindAddr = tmpStr
  225. } else {
  226. cfg.ProxyBindAddr = cfg.BindAddr
  227. }
  228. if tmpStr, ok = conf.Get("common", "vhost_http_port"); ok {
  229. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  230. err = fmt.Errorf("Parse conf error: invalid vhost_http_port")
  231. return
  232. }
  233. cfg.VhostHTTPPort = int(v)
  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. }
  242. cfg.VhostHTTPSPort = int(v)
  243. } else {
  244. cfg.VhostHTTPSPort = 0
  245. }
  246. if tmpStr, ok = conf.Get("common", "tcpmux_httpconnect_port"); ok {
  247. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  248. err = fmt.Errorf("Parse conf error: invalid tcpmux_httpconnect_port")
  249. return
  250. }
  251. cfg.TCPMuxHTTPConnectPort = int(v)
  252. } else {
  253. cfg.TCPMuxHTTPConnectPort = 0
  254. }
  255. if tmpStr, ok = conf.Get("common", "vhost_http_timeout"); ok {
  256. v, errRet := strconv.ParseInt(tmpStr, 10, 64)
  257. if errRet != nil || v < 0 {
  258. err = fmt.Errorf("Parse conf error: invalid vhost_http_timeout")
  259. return
  260. }
  261. cfg.VhostHTTPTimeout = v
  262. }
  263. if tmpStr, ok = conf.Get("common", "dashboard_addr"); ok {
  264. cfg.DashboardAddr = tmpStr
  265. } else {
  266. cfg.DashboardAddr = cfg.BindAddr
  267. }
  268. if tmpStr, ok = conf.Get("common", "dashboard_port"); ok {
  269. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  270. err = fmt.Errorf("Parse conf error: invalid dashboard_port")
  271. return
  272. }
  273. cfg.DashboardPort = int(v)
  274. } else {
  275. cfg.DashboardPort = 0
  276. }
  277. if tmpStr, ok = conf.Get("common", "dashboard_user"); ok {
  278. cfg.DashboardUser = tmpStr
  279. }
  280. if tmpStr, ok = conf.Get("common", "dashboard_pwd"); ok {
  281. cfg.DashboardPwd = tmpStr
  282. }
  283. if tmpStr, ok = conf.Get("common", "enable_prometheus"); ok && tmpStr == "true" {
  284. cfg.EnablePrometheus = true
  285. }
  286. if tmpStr, ok = conf.Get("common", "assets_dir"); ok {
  287. cfg.AssetsDir = tmpStr
  288. }
  289. if tmpStr, ok = conf.Get("common", "log_file"); ok {
  290. cfg.LogFile = tmpStr
  291. if cfg.LogFile == "console" {
  292. cfg.LogWay = "console"
  293. } else {
  294. cfg.LogWay = "file"
  295. }
  296. }
  297. if tmpStr, ok = conf.Get("common", "log_level"); ok {
  298. cfg.LogLevel = tmpStr
  299. }
  300. if tmpStr, ok = conf.Get("common", "log_max_days"); ok {
  301. v, err = strconv.ParseInt(tmpStr, 10, 64)
  302. if err == nil {
  303. cfg.LogMaxDays = v
  304. }
  305. }
  306. if tmpStr, ok = conf.Get("common", "disable_log_color"); ok && tmpStr == "true" {
  307. cfg.DisableLogColor = true
  308. }
  309. if tmpStr, ok = conf.Get("common", "detailed_errors_to_client"); ok && tmpStr == "false" {
  310. cfg.DetailedErrorsToClient = false
  311. } else {
  312. cfg.DetailedErrorsToClient = true
  313. }
  314. if allowPortsStr, ok := conf.Get("common", "allow_ports"); ok {
  315. // e.g. 1000-2000,2001,2002,3000-4000
  316. ports, errRet := util.ParseRangeNumbers(allowPortsStr)
  317. if errRet != nil {
  318. err = fmt.Errorf("Parse conf error: allow_ports: %v", errRet)
  319. return
  320. }
  321. for _, port := range ports {
  322. cfg.AllowPorts[int(port)] = struct{}{}
  323. }
  324. }
  325. if tmpStr, ok = conf.Get("common", "max_pool_count"); ok {
  326. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  327. err = fmt.Errorf("Parse conf error: invalid max_pool_count")
  328. return
  329. }
  330. if v < 0 {
  331. err = fmt.Errorf("Parse conf error: invalid max_pool_count")
  332. return
  333. }
  334. cfg.MaxPoolCount = v
  335. }
  336. if tmpStr, ok = conf.Get("common", "max_ports_per_client"); ok {
  337. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  338. err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
  339. return
  340. }
  341. if v < 0 {
  342. err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
  343. return
  344. }
  345. cfg.MaxPortsPerClient = v
  346. }
  347. if tmpStr, ok = conf.Get("common", "subdomain_host"); ok {
  348. cfg.SubDomainHost = strings.ToLower(strings.TrimSpace(tmpStr))
  349. }
  350. if tmpStr, ok = conf.Get("common", "tcp_mux"); ok && tmpStr == "false" {
  351. cfg.TCPMux = false
  352. } else {
  353. cfg.TCPMux = true
  354. }
  355. if tmpStr, ok = conf.Get("common", "custom_404_page"); ok {
  356. cfg.Custom404Page = tmpStr
  357. }
  358. if tmpStr, ok = conf.Get("common", "heartbeat_timeout"); ok {
  359. v, errRet := strconv.ParseInt(tmpStr, 10, 64)
  360. if errRet != nil {
  361. err = fmt.Errorf("Parse conf error: heartbeat_timeout is incorrect")
  362. return
  363. }
  364. cfg.HeartBeatTimeout = v
  365. }
  366. if tmpStr, ok = conf.Get("common", "tls_only"); ok && tmpStr == "true" {
  367. cfg.TLSOnly = true
  368. } else {
  369. cfg.TLSOnly = false
  370. }
  371. if tmpStr, ok = conf.Get("common", "udp_packet_size"); ok {
  372. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  373. err = fmt.Errorf("Parse conf error: invalid udp_packet_size")
  374. return
  375. }
  376. cfg.UDPPacketSize = v
  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. }