server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. "github.com/go-playground/validator/v10"
  22. "gopkg.in/ini.v1"
  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 `ini:",extends"`
  29. // BindAddr specifies the address that the server binds to. By default,
  30. // this value is "0.0.0.0".
  31. BindAddr string `ini:"bind_addr" json:"bind_addr"`
  32. // BindPort specifies the port that the server listens on. By default, this
  33. // value is 7000.
  34. BindPort int `ini:"bind_port" json:"bind_port" validate:"gte=0,lte=65535"`
  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 `ini:"bind_udp_port" json:"bind_udp_port" validate:"gte=0,lte=65535"`
  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 `ini:"kcp_bind_port" json:"kcp_bind_port" validate:"gte=0,lte=65535"`
  43. // ProxyBindAddr specifies the address that the proxy binds to. This value
  44. // may be the same as BindAddr.
  45. ProxyBindAddr string `ini:"proxy_bind_addr" 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 `ini:"vhost_http_port" json:"vhost_http_port" validate:"gte=0,lte=65535"`
  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 `ini:"vhost_https_port" json:"vhost_https_port" validate:"gte=0,lte=65535"`
  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 `ini:"tcpmux_httpconnect_port" json:"tcpmux_httpconnect_port" validate:"gte=0,lte=65535"`
  59. // VhostHTTPTimeout specifies the response header timeout for the Vhost
  60. // HTTP server, in seconds. By default, this value is 60.
  61. VhostHTTPTimeout int64 `ini:"vhost_http_timeout" 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 `ini:"dashboard_addr" 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 `ini:"dashboard_port" json:"dashboard_port" validate:"gte=0,lte=65535"`
  69. // DashboardUser specifies the username that the dashboard will use for
  70. // login.
  71. DashboardUser string `ini:"dashboard_user" json:"dashboard_user"`
  72. // DashboardPwd specifies the password that the dashboard will use for
  73. // login.
  74. DashboardPwd string `ini:"dashboard_pwd" json:"dashboard_pwd"`
  75. // EnablePrometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port}
  76. // in /metrics api.
  77. EnablePrometheus bool `ini:"enable_prometheus" 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 `ini:"assets_dir" json:"assets_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 `ini:"log_file" 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 `ini:"log_way" 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 `ini:"log_level" 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 `ini:"log_max_days" 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 `ini:"disable_log_color" 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 `ini:"detailed_errors_to_client" 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 `ini:"subdomain_host" 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 `ini:"tcp_mux" json:"tcp_mux"`
  114. // TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multipler.
  115. // If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
  116. TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"`
  117. // Custom404Page specifies a path to a custom 404 page to display. If this
  118. // value is "", a default page will be displayed. By default, this value is
  119. // "".
  120. Custom404Page string `ini:"custom_404_page" json:"custom_404_page"`
  121. // AllowPorts specifies a set of ports that clients are able to proxy to.
  122. // If the length of this value is 0, all ports are allowed. By default,
  123. // this value is an empty set.
  124. AllowPorts map[int]struct{} `ini:"-" json:"-"`
  125. // MaxPoolCount specifies the maximum pool size for each proxy. By default,
  126. // this value is 5.
  127. MaxPoolCount int64 `ini:"max_pool_count" json:"max_pool_count"`
  128. // MaxPortsPerClient specifies the maximum number of ports a single client
  129. // may proxy to. If this value is 0, no limit will be applied. By default,
  130. // this value is 0.
  131. MaxPortsPerClient int64 `ini:"max_ports_per_client" json:"max_ports_per_client"`
  132. // TLSOnly specifies whether to only accept TLS-encrypted connections.
  133. // By default, the value is false.
  134. TLSOnly bool `ini:"tls_only" json:"tls_only"`
  135. // TLSCertFile specifies the path of the cert file that the server will
  136. // load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
  137. // supplied tls configuration. Otherwise, the server will use the tls
  138. // configuration generated by itself.
  139. TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
  140. // TLSKeyFile specifies the path of the secret key that the server will
  141. // load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
  142. // supplied tls configuration. Otherwise, the server will use the tls
  143. // configuration generated by itself.
  144. TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
  145. // TLSTrustedCaFile specifies the paths of the client cert files that the
  146. // server will load. It only works when "tls_only" is true. If
  147. // "tls_trusted_ca_file" is valid, the server will verify each client's
  148. // certificate.
  149. TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
  150. // HeartBeatTimeout specifies the maximum time to wait for a heartbeat
  151. // before terminating the connection. It is not recommended to change this
  152. // value. By default, this value is 90. Set negative value to disable it.
  153. HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
  154. // UserConnTimeout specifies the maximum time to wait for a work
  155. // connection. By default, this value is 10.
  156. UserConnTimeout int64 `ini:"user_conn_timeout" json:"user_conn_timeout"`
  157. // HTTPPlugins specify the server plugins support HTTP protocol.
  158. HTTPPlugins map[string]plugin.HTTPPluginOptions `ini:"-" json:"http_plugins"`
  159. // UDPPacketSize specifies the UDP packet size
  160. // By default, this value is 1500
  161. UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
  162. }
  163. // GetDefaultServerConf returns a server configuration with reasonable
  164. // defaults.
  165. func GetDefaultServerConf() ServerCommonConf {
  166. return ServerCommonConf{
  167. ServerConfig: auth.GetDefaultServerConf(),
  168. BindAddr: "0.0.0.0",
  169. BindPort: 7000,
  170. BindUDPPort: 0,
  171. KCPBindPort: 0,
  172. ProxyBindAddr: "",
  173. VhostHTTPPort: 0,
  174. VhostHTTPSPort: 0,
  175. TCPMuxHTTPConnectPort: 0,
  176. VhostHTTPTimeout: 60,
  177. DashboardAddr: "0.0.0.0",
  178. DashboardPort: 0,
  179. DashboardUser: "",
  180. DashboardPwd: "",
  181. EnablePrometheus: false,
  182. AssetsDir: "",
  183. LogFile: "console",
  184. LogWay: "console",
  185. LogLevel: "info",
  186. LogMaxDays: 3,
  187. DisableLogColor: false,
  188. DetailedErrorsToClient: true,
  189. SubDomainHost: "",
  190. TCPMux: true,
  191. TCPMuxKeepaliveInterval: 60,
  192. AllowPorts: make(map[int]struct{}),
  193. MaxPoolCount: 5,
  194. MaxPortsPerClient: 0,
  195. TLSOnly: false,
  196. TLSCertFile: "",
  197. TLSKeyFile: "",
  198. TLSTrustedCaFile: "",
  199. HeartbeatTimeout: 90,
  200. UserConnTimeout: 10,
  201. Custom404Page: "",
  202. HTTPPlugins: make(map[string]plugin.HTTPPluginOptions),
  203. UDPPacketSize: 1500,
  204. }
  205. }
  206. func UnmarshalServerConfFromIni(source interface{}) (ServerCommonConf, error) {
  207. f, err := ini.LoadSources(ini.LoadOptions{
  208. Insensitive: false,
  209. InsensitiveSections: false,
  210. InsensitiveKeys: false,
  211. IgnoreInlineComment: true,
  212. AllowBooleanKeys: true,
  213. }, source)
  214. if err != nil {
  215. return ServerCommonConf{}, err
  216. }
  217. s, err := f.GetSection("common")
  218. if err != nil {
  219. return ServerCommonConf{}, err
  220. }
  221. common := GetDefaultServerConf()
  222. err = s.MapTo(&common)
  223. if err != nil {
  224. return ServerCommonConf{}, err
  225. }
  226. // allow_ports
  227. allowPortStr := s.Key("allow_ports").String()
  228. if allowPortStr != "" {
  229. allowPorts, err := util.ParseRangeNumbers(allowPortStr)
  230. if err != nil {
  231. return ServerCommonConf{}, fmt.Errorf("invalid allow_ports: %v", err)
  232. }
  233. for _, port := range allowPorts {
  234. common.AllowPorts[int(port)] = struct{}{}
  235. }
  236. }
  237. // plugin.xxx
  238. pluginOpts := make(map[string]plugin.HTTPPluginOptions)
  239. for _, section := range f.Sections() {
  240. name := section.Name()
  241. if !strings.HasPrefix(name, "plugin.") {
  242. continue
  243. }
  244. opt, err := loadHTTPPluginOpt(section)
  245. if err != nil {
  246. return ServerCommonConf{}, err
  247. }
  248. pluginOpts[opt.Name] = *opt
  249. }
  250. common.HTTPPlugins = pluginOpts
  251. return common, nil
  252. }
  253. func (cfg *ServerCommonConf) Complete() {
  254. if cfg.LogFile == "console" {
  255. cfg.LogWay = "console"
  256. } else {
  257. cfg.LogWay = "file"
  258. }
  259. if cfg.ProxyBindAddr == "" {
  260. cfg.ProxyBindAddr = cfg.BindAddr
  261. }
  262. if cfg.TLSTrustedCaFile != "" {
  263. cfg.TLSOnly = true
  264. }
  265. }
  266. func (cfg *ServerCommonConf) Validate() error {
  267. return validator.New().Struct(cfg)
  268. }
  269. func loadHTTPPluginOpt(section *ini.Section) (*plugin.HTTPPluginOptions, error) {
  270. name := strings.TrimSpace(strings.TrimPrefix(section.Name(), "plugin."))
  271. opt := new(plugin.HTTPPluginOptions)
  272. err := section.MapTo(opt)
  273. if err != nil {
  274. return nil, err
  275. }
  276. opt.Name = name
  277. return opt, nil
  278. }