server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "strings"
  18. "github.com/fatedier/frp/pkg/auth"
  19. plugin "github.com/fatedier/frp/pkg/plugin/server"
  20. "github.com/fatedier/frp/pkg/util/util"
  21. "gopkg.in/ini.v1"
  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. auth.ServerConfig `ini:",extends"`
  28. // BindAddr specifies the address that the server binds to. By default,
  29. // this value is "0.0.0.0".
  30. BindAddr string `ini:"bind_addr" json:"bind_addr"`
  31. // BindPort specifies the port that the server listens on. By default, this
  32. // value is 7000.
  33. BindPort int `ini:"bind_port" json:"bind_port"`
  34. // BindUDPPort specifies the UDP port that the server listens on. If this
  35. // value is 0, the server will not listen for UDP connections. By default,
  36. // this value is 0
  37. BindUDPPort int `ini:"bind_udp_port" json:"bind_udp_port"`
  38. // KCPBindPort specifies the KCP port that the server listens on. If this
  39. // value is 0, the server will not listen for KCP connections. By default,
  40. // this value is 0.
  41. KCPBindPort int `ini:"kcp_bind_port" json:"kcp_bind_port"`
  42. // ProxyBindAddr specifies the address that the proxy binds to. This value
  43. // may be the same as BindAddr.
  44. ProxyBindAddr string `ini:"proxy_bind_addr" json:"proxy_bind_addr"`
  45. // VhostHTTPPort specifies the port that the server listens for HTTP Vhost
  46. // requests. If this value is 0, the server will not listen for HTTP
  47. // requests. By default, this value is 0.
  48. VhostHTTPPort int `ini:"vhost_http_port" json:"vhost_http_port"`
  49. // VhostHTTPSPort specifies the port that the server listens for HTTPS
  50. // Vhost requests. If this value is 0, the server will not listen for HTTPS
  51. // requests. By default, this value is 0.
  52. VhostHTTPSPort int `ini:"vhost_https_port" json:"vhost_https_port"`
  53. // TCPMuxHTTPConnectPort specifies the port that the server listens for TCP
  54. // HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
  55. // requests on one single port. If it's not - it will listen on this value for
  56. // HTTP CONNECT requests. By default, this value is 0.
  57. TCPMuxHTTPConnectPort int `ini:"tcpmux_httpconnect_port" json:"tcpmux_httpconnect_port"`
  58. // VhostHTTPTimeout specifies the response header timeout for the Vhost
  59. // HTTP server, in seconds. By default, this value is 60.
  60. VhostHTTPTimeout int64 `ini:"vhost_http_timeout" json:"vhost_http_timeout"`
  61. // DashboardAddr specifies the address that the dashboard binds to. By
  62. // default, this value is "0.0.0.0".
  63. DashboardAddr string `ini:"dashboard_addr" json:"dashboard_addr"`
  64. // DashboardPort specifies the port that the dashboard listens on. If this
  65. // value is 0, the dashboard will not be started. By default, this value is
  66. // 0.
  67. DashboardPort int `ini:"dashboard_port" json:"dashboard_port"`
  68. // DashboardUser specifies the username that the dashboard will use for
  69. // login. By default, this value is "admin".
  70. DashboardUser string `ini:"dashboard_user" json:"dashboard_user"`
  71. // DashboardUser specifies the password that the dashboard will use for
  72. // login. By default, this value is "admin".
  73. DashboardPwd string `ini:"dashboard_pwd" json:"dashboard_pwd"`
  74. // EnablePrometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port}
  75. // in /metrics api.
  76. EnablePrometheus bool `ini:"enable_prometheus" json:"enable_prometheus"`
  77. // AssetsDir specifies the local directory that the dashboard will load
  78. // resources from. If this value is "", assets will be loaded from the
  79. // bundled executable using statik. By default, this value is "".
  80. AssetsDir string `ini:"assets_dir" json:"assets_dir"`
  81. // LogFile specifies a file where logs will be written to. This value will
  82. // only be used if LogWay is set appropriately. By default, this value is
  83. // "console".
  84. LogFile string `ini:"log_file" json:"log_file"`
  85. // LogWay specifies the way logging is managed. Valid values are "console"
  86. // or "file". If "console" is used, logs will be printed to stdout. If
  87. // "file" is used, logs will be printed to LogFile. By default, this value
  88. // is "console".
  89. LogWay string `ini:"log_way" json:"log_way"`
  90. // LogLevel specifies the minimum log level. Valid values are "trace",
  91. // "debug", "info", "warn", and "error". By default, this value is "info".
  92. LogLevel string `ini:"log_level" json:"log_level"`
  93. // LogMaxDays specifies the maximum number of days to store log information
  94. // before deletion. This is only used if LogWay == "file". By default, this
  95. // value is 0.
  96. LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"`
  97. // DisableLogColor disables log colors when LogWay == "console" when set to
  98. // true. By default, this value is false.
  99. DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"`
  100. // DetailedErrorsToClient defines whether to send the specific error (with
  101. // debug info) to frpc. By default, this value is true.
  102. DetailedErrorsToClient bool `ini:"detailed_errors_to_client" json:"detailed_errors_to_client"`
  103. // SubDomainHost specifies the domain that will be attached to sub-domains
  104. // requested by the client when using Vhost proxying. For example, if this
  105. // value is set to "frps.com" and the client requested the subdomain
  106. // "test", the resulting URL would be "test.frps.com". By default, this
  107. // value is "".
  108. SubDomainHost string `ini:"subdomain_host" json:"subdomain_host"`
  109. // TCPMux toggles TCP stream multiplexing. This allows multiple requests
  110. // from a client to share a single TCP connection. By default, this value
  111. // is true.
  112. TCPMux bool `ini:"tcp_mux" json:"tcp_mux"`
  113. // Custom404Page specifies a path to a custom 404 page to display. If this
  114. // value is "", a default page will be displayed. By default, this value is
  115. // "".
  116. Custom404Page string `ini:"custom_404_page" json:"custom_404_page"`
  117. // AllowPorts specifies a set of ports that clients are able to proxy to.
  118. // If the length of this value is 0, all ports are allowed. By default,
  119. // this value is an empty set.
  120. AllowPorts map[int]struct{} `ini:"-" json:"-"`
  121. // MaxPoolCount specifies the maximum pool size for each proxy. By default,
  122. // this value is 5.
  123. MaxPoolCount int64 `ini:"max_pool_count" json:"max_pool_count"`
  124. // MaxPortsPerClient specifies the maximum number of ports a single client
  125. // may proxy to. If this value is 0, no limit will be applied. By default,
  126. // this value is 0.
  127. MaxPortsPerClient int64 `ini:"max_ports_per_client" json:"max_ports_per_client"`
  128. // TLSOnly specifies whether to only accept TLS-encrypted connections.
  129. // By default, the value is false.
  130. TLSOnly bool `ini:"tls_only" json:"tls_only"`
  131. // TLSCertFile specifies the path of the cert file that the server will
  132. // load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
  133. // supplied tls configuration. Otherwise, the server will use the tls
  134. // configuration generated by itself.
  135. TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
  136. // TLSKeyFile specifies the path of the secret key that the server will
  137. // load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
  138. // supplied tls configuration. Otherwise, the server will use the tls
  139. // configuration generated by itself.
  140. TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
  141. // TLSTrustedCaFile specifies the paths of the client cert files that the
  142. // server will load. It only works when "tls_only" is true. If
  143. // "tls_trusted_ca_file" is valid, the server will verify each client's
  144. // certificate.
  145. TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
  146. // HeartBeatTimeout specifies the maximum time to wait for a heartbeat
  147. // before terminating the connection. It is not recommended to change this
  148. // value. By default, this value is 90.
  149. HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
  150. // UserConnTimeout specifies the maximum time to wait for a work
  151. // connection. By default, this value is 10.
  152. UserConnTimeout int64 `ini:"user_conn_timeout" json:"user_conn_timeout"`
  153. // HTTPPlugins specify the server plugins support HTTP protocol.
  154. HTTPPlugins map[string]plugin.HTTPPluginOptions `ini:"-" json:"http_plugins"`
  155. // UDPPacketSize specifies the UDP packet size
  156. // By default, this value is 1500
  157. UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
  158. }
  159. // GetDefaultServerConf returns a server configuration with reasonable
  160. // defaults.
  161. func GetDefaultServerConf() ServerCommonConf {
  162. return ServerCommonConf{
  163. ServerConfig: auth.GetDefaultServerConf(),
  164. BindAddr: "0.0.0.0",
  165. BindPort: 7000,
  166. BindUDPPort: 0,
  167. KCPBindPort: 0,
  168. ProxyBindAddr: "",
  169. VhostHTTPPort: 0,
  170. VhostHTTPSPort: 0,
  171. TCPMuxHTTPConnectPort: 0,
  172. VhostHTTPTimeout: 60,
  173. DashboardAddr: "0.0.0.0",
  174. DashboardPort: 0,
  175. DashboardUser: "admin",
  176. DashboardPwd: "admin",
  177. EnablePrometheus: false,
  178. AssetsDir: "",
  179. LogFile: "console",
  180. LogWay: "console",
  181. LogLevel: "info",
  182. LogMaxDays: 3,
  183. DisableLogColor: false,
  184. DetailedErrorsToClient: true,
  185. SubDomainHost: "",
  186. TCPMux: true,
  187. AllowPorts: make(map[int]struct{}),
  188. MaxPoolCount: 5,
  189. MaxPortsPerClient: 0,
  190. TLSOnly: false,
  191. TLSCertFile: "",
  192. TLSKeyFile: "",
  193. TLSTrustedCaFile: "",
  194. HeartbeatTimeout: 90,
  195. UserConnTimeout: 10,
  196. Custom404Page: "",
  197. HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
  198. UDPPacketSize: 1500,
  199. }
  200. }
  201. func UnmarshalServerConfFromIni(source interface{}) (ServerCommonConf, error) {
  202. f, err := ini.LoadSources(ini.LoadOptions{
  203. Insensitive: false,
  204. InsensitiveSections: false,
  205. InsensitiveKeys: false,
  206. IgnoreInlineComment: true,
  207. AllowBooleanKeys: true,
  208. }, source)
  209. if err != nil {
  210. return ServerCommonConf{}, err
  211. }
  212. s, err := f.GetSection("common")
  213. if err != nil {
  214. // TODO: add error info
  215. return ServerCommonConf{}, err
  216. }
  217. common := GetDefaultServerConf()
  218. err = s.MapTo(&common)
  219. if err != nil {
  220. return ServerCommonConf{}, err
  221. }
  222. // allow_ports
  223. allowPortStr := s.Key("allow_ports").String()
  224. if allowPortStr != "" {
  225. allowPorts, err := util.ParseRangeNumbers(allowPortStr)
  226. if err != nil {
  227. return ServerCommonConf{}, fmt.Errorf("invalid allow_ports: %v", err)
  228. }
  229. for _, port := range allowPorts {
  230. common.AllowPorts[int(port)] = struct{}{}
  231. }
  232. }
  233. // plugin.xxx
  234. pluginOpts := make(map[string]plugin.HTTPPluginOptions)
  235. for _, section := range f.Sections() {
  236. name := section.Name()
  237. if !strings.HasPrefix(name, "plugin.") {
  238. continue
  239. }
  240. opt, err := loadHTTPPluginOpt(section)
  241. if err != nil {
  242. return ServerCommonConf{}, err
  243. }
  244. pluginOpts[opt.Name] = *opt
  245. }
  246. common.HTTPPlugins = pluginOpts
  247. return common, nil
  248. }
  249. func (cfg *ServerCommonConf) Complete() {
  250. if cfg.LogFile == "console" {
  251. cfg.LogWay = "console"
  252. } else {
  253. cfg.LogWay = "file"
  254. }
  255. if cfg.ProxyBindAddr == "" {
  256. cfg.ProxyBindAddr = cfg.BindAddr
  257. }
  258. if cfg.TLSTrustedCaFile != "" {
  259. cfg.TLSOnly = true
  260. }
  261. }
  262. func (cfg *ServerCommonConf) Validate() error {
  263. return nil
  264. }
  265. func loadHTTPPluginOpt(section *ini.Section) (*plugin.HTTPPluginOptions, error) {
  266. name := strings.TrimSpace(strings.TrimPrefix(section.Name(), "plugin."))
  267. opt := new(plugin.HTTPPluginOptions)
  268. err := section.MapTo(opt)
  269. if err != nil {
  270. return nil, err
  271. }
  272. opt.Name = name
  273. return opt, nil
  274. }