server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright 2023 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 legacy
  15. import (
  16. "strings"
  17. "gopkg.in/ini.v1"
  18. legacyauth "github.com/fatedier/frp/pkg/auth/legacy"
  19. )
  20. type HTTPPluginOptions struct {
  21. Name string `ini:"name"`
  22. Addr string `ini:"addr"`
  23. Path string `ini:"path"`
  24. Ops []string `ini:"ops"`
  25. TLSVerify bool `ini:"tlsVerify"`
  26. }
  27. // ServerCommonConf contains information for a server service. It is
  28. // recommended to use GetDefaultServerConf instead of creating this object
  29. // directly, so that all unspecified fields have reasonable default values.
  30. type ServerCommonConf struct {
  31. legacyauth.ServerConfig `ini:",extends"`
  32. // BindAddr specifies the address that the server binds to. By default,
  33. // this value is "0.0.0.0".
  34. BindAddr string `ini:"bind_addr" json:"bind_addr"`
  35. // BindPort specifies the port that the server listens on. By default, this
  36. // value is 7000.
  37. BindPort int `ini:"bind_port" json:"bind_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. // QUICBindPort specifies the QUIC port that the server listens on.
  43. // Set this value to 0 will disable this feature.
  44. // By default, the value is 0.
  45. QUICBindPort int `ini:"quic_bind_port" json:"quic_bind_port"`
  46. // QUIC protocol options
  47. QUICKeepalivePeriod int `ini:"quic_keepalive_period" json:"quic_keepalive_period"`
  48. QUICMaxIdleTimeout int `ini:"quic_max_idle_timeout" json:"quic_max_idle_timeout"`
  49. QUICMaxIncomingStreams int `ini:"quic_max_incoming_streams" json:"quic_max_incoming_streams"`
  50. // ProxyBindAddr specifies the address that the proxy binds to. This value
  51. // may be the same as BindAddr.
  52. ProxyBindAddr string `ini:"proxy_bind_addr" json:"proxy_bind_addr"`
  53. // VhostHTTPPort specifies the port that the server listens for HTTP Vhost
  54. // requests. If this value is 0, the server will not listen for HTTP
  55. // requests. By default, this value is 0.
  56. VhostHTTPPort int `ini:"vhost_http_port" json:"vhost_http_port"`
  57. // VhostHTTPSPort specifies the port that the server listens for HTTPS
  58. // Vhost requests. If this value is 0, the server will not listen for HTTPS
  59. // requests. By default, this value is 0.
  60. VhostHTTPSPort int `ini:"vhost_https_port" json:"vhost_https_port"`
  61. // TCPMuxHTTPConnectPort specifies the port that the server listens for TCP
  62. // HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
  63. // requests on one single port. If it's not - it will listen on this value for
  64. // HTTP CONNECT requests. By default, this value is 0.
  65. TCPMuxHTTPConnectPort int `ini:"tcpmux_httpconnect_port" json:"tcpmux_httpconnect_port"`
  66. // If TCPMuxPassthrough is true, frps won't do any update on traffic.
  67. TCPMuxPassthrough bool `ini:"tcpmux_passthrough" json:"tcpmux_passthrough"`
  68. // VhostHTTPTimeout specifies the response header timeout for the Vhost
  69. // HTTP server, in seconds. By default, this value is 60.
  70. VhostHTTPTimeout int64 `ini:"vhost_http_timeout" json:"vhost_http_timeout"`
  71. // DashboardAddr specifies the address that the dashboard binds to. By
  72. // default, this value is "0.0.0.0".
  73. DashboardAddr string `ini:"dashboard_addr" json:"dashboard_addr"`
  74. // DashboardPort specifies the port that the dashboard listens on. If this
  75. // value is 0, the dashboard will not be started. By default, this value is
  76. // 0.
  77. DashboardPort int `ini:"dashboard_port" json:"dashboard_port"`
  78. // DashboardTLSCertFile specifies the path of the cert file that the server will
  79. // load. If "dashboard_tls_cert_file", "dashboard_tls_key_file" are valid, the server will use this
  80. // supplied tls configuration.
  81. DashboardTLSCertFile string `ini:"dashboard_tls_cert_file" json:"dashboard_tls_cert_file"`
  82. // DashboardTLSKeyFile specifies the path of the secret key that the server will
  83. // load. If "dashboard_tls_cert_file", "dashboard_tls_key_file" are valid, the server will use this
  84. // supplied tls configuration.
  85. DashboardTLSKeyFile string `ini:"dashboard_tls_key_file" json:"dashboard_tls_key_file"`
  86. // DashboardTLSMode specifies the mode of the dashboard between HTTP or HTTPS modes. By
  87. // default, this value is false, which is HTTP mode.
  88. DashboardTLSMode bool `ini:"dashboard_tls_mode" json:"dashboard_tls_mode"`
  89. // DashboardUser specifies the username that the dashboard will use for
  90. // login.
  91. DashboardUser string `ini:"dashboard_user" json:"dashboard_user"`
  92. // DashboardPwd specifies the password that the dashboard will use for
  93. // login.
  94. DashboardPwd string `ini:"dashboard_pwd" json:"dashboard_pwd"`
  95. // EnablePrometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port}
  96. // in /metrics api.
  97. EnablePrometheus bool `ini:"enable_prometheus" json:"enable_prometheus"`
  98. // AssetsDir specifies the local directory that the dashboard will load
  99. // resources from. If this value is "", assets will be loaded from the
  100. // bundled executable using statik. By default, this value is "".
  101. AssetsDir string `ini:"assets_dir" json:"assets_dir"`
  102. // LogFile specifies a file where logs will be written to. This value will
  103. // only be used if LogWay is set appropriately. By default, this value is
  104. // "console".
  105. LogFile string `ini:"log_file" json:"log_file"`
  106. // LogWay specifies the way logging is managed. Valid values are "console"
  107. // or "file". If "console" is used, logs will be printed to stdout. If
  108. // "file" is used, logs will be printed to LogFile. By default, this value
  109. // is "console".
  110. LogWay string `ini:"log_way" json:"log_way"`
  111. // LogLevel specifies the minimum log level. Valid values are "trace",
  112. // "debug", "info", "warn", and "error". By default, this value is "info".
  113. LogLevel string `ini:"log_level" json:"log_level"`
  114. // LogMaxDays specifies the maximum number of days to store log information
  115. // before deletion. This is only used if LogWay == "file". By default, this
  116. // value is 0.
  117. LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"`
  118. // DisableLogColor disables log colors when LogWay == "console" when set to
  119. // true. By default, this value is false.
  120. DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"`
  121. // DetailedErrorsToClient defines whether to send the specific error (with
  122. // debug info) to frpc. By default, this value is true.
  123. DetailedErrorsToClient bool `ini:"detailed_errors_to_client" json:"detailed_errors_to_client"`
  124. // SubDomainHost specifies the domain that will be attached to sub-domains
  125. // requested by the client when using Vhost proxying. For example, if this
  126. // value is set to "frps.com" and the client requested the subdomain
  127. // "test", the resulting URL would be "test.frps.com". By default, this
  128. // value is "".
  129. SubDomainHost string `ini:"subdomain_host" json:"subdomain_host"`
  130. // TCPMux toggles TCP stream multiplexing. This allows multiple requests
  131. // from a client to share a single TCP connection. By default, this value
  132. // is true.
  133. TCPMux bool `ini:"tcp_mux" json:"tcp_mux"`
  134. // TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multiplier.
  135. // If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux.
  136. TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"`
  137. // TCPKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps.
  138. // If negative, keep-alive probes are disabled.
  139. TCPKeepAlive int64 `ini:"tcp_keepalive" json:"tcp_keepalive"`
  140. // Custom404Page specifies a path to a custom 404 page to display. If this
  141. // value is "", a default page will be displayed. By default, this value is
  142. // "".
  143. Custom404Page string `ini:"custom_404_page" json:"custom_404_page"`
  144. // AllowPorts specifies a set of ports that clients are able to proxy to.
  145. // If the length of this value is 0, all ports are allowed. By default,
  146. // this value is an empty set.
  147. AllowPorts map[int]struct{} `ini:"-" json:"-"`
  148. // Original string.
  149. AllowPortsStr string `ini:"-" json:"-"`
  150. // MaxPoolCount specifies the maximum pool size for each proxy. By default,
  151. // this value is 5.
  152. MaxPoolCount int64 `ini:"max_pool_count" json:"max_pool_count"`
  153. // MaxPortsPerClient specifies the maximum number of ports a single client
  154. // may proxy to. If this value is 0, no limit will be applied. By default,
  155. // this value is 0.
  156. MaxPortsPerClient int64 `ini:"max_ports_per_client" json:"max_ports_per_client"`
  157. // TLSOnly specifies whether to only accept TLS-encrypted connections.
  158. // By default, the value is false.
  159. TLSOnly bool `ini:"tls_only" json:"tls_only"`
  160. // TLSCertFile specifies the path of the cert file that the server will
  161. // load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
  162. // supplied tls configuration. Otherwise, the server will use the tls
  163. // configuration generated by itself.
  164. TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"`
  165. // TLSKeyFile specifies the path of the secret key that the server will
  166. // load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
  167. // supplied tls configuration. Otherwise, the server will use the tls
  168. // configuration generated by itself.
  169. TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"`
  170. // TLSTrustedCaFile specifies the paths of the client cert files that the
  171. // server will load. It only works when "tls_only" is true. If
  172. // "tls_trusted_ca_file" is valid, the server will verify each client's
  173. // certificate.
  174. TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"`
  175. // HeartBeatTimeout specifies the maximum time to wait for a heartbeat
  176. // before terminating the connection. It is not recommended to change this
  177. // value. By default, this value is 90. Set negative value to disable it.
  178. HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"`
  179. // UserConnTimeout specifies the maximum time to wait for a work
  180. // connection. By default, this value is 10.
  181. UserConnTimeout int64 `ini:"user_conn_timeout" json:"user_conn_timeout"`
  182. // HTTPPlugins specify the server plugins support HTTP protocol.
  183. HTTPPlugins map[string]HTTPPluginOptions `ini:"-" json:"http_plugins"`
  184. // UDPPacketSize specifies the UDP packet size
  185. // By default, this value is 1500
  186. UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"`
  187. // Enable golang pprof handlers in dashboard listener.
  188. // Dashboard port must be set first.
  189. PprofEnable bool `ini:"pprof_enable" json:"pprof_enable"`
  190. // NatHoleAnalysisDataReserveHours specifies the hours to reserve nat hole analysis data.
  191. NatHoleAnalysisDataReserveHours int64 `ini:"nat_hole_analysis_data_reserve_hours" json:"nat_hole_analysis_data_reserve_hours"`
  192. }
  193. // GetDefaultServerConf returns a server configuration with reasonable defaults.
  194. // Note: Some default values here will be set to empty and will be converted to them
  195. // new configuration through the 'Complete' function to set them as the default
  196. // values of the new configuration.
  197. func GetDefaultServerConf() ServerCommonConf {
  198. return ServerCommonConf{
  199. ServerConfig: legacyauth.GetDefaultServerConf(),
  200. DashboardAddr: "0.0.0.0",
  201. LogFile: "console",
  202. LogWay: "console",
  203. DetailedErrorsToClient: true,
  204. TCPMux: true,
  205. AllowPorts: make(map[int]struct{}),
  206. HTTPPlugins: make(map[string]HTTPPluginOptions),
  207. }
  208. }
  209. func UnmarshalServerConfFromIni(source interface{}) (ServerCommonConf, error) {
  210. f, err := ini.LoadSources(ini.LoadOptions{
  211. Insensitive: false,
  212. InsensitiveSections: false,
  213. InsensitiveKeys: false,
  214. IgnoreInlineComment: true,
  215. AllowBooleanKeys: true,
  216. }, source)
  217. if err != nil {
  218. return ServerCommonConf{}, err
  219. }
  220. s, err := f.GetSection("common")
  221. if err != nil {
  222. return ServerCommonConf{}, err
  223. }
  224. common := GetDefaultServerConf()
  225. err = s.MapTo(&common)
  226. if err != nil {
  227. return ServerCommonConf{}, err
  228. }
  229. // allow_ports
  230. allowPortStr := s.Key("allow_ports").String()
  231. if allowPortStr != "" {
  232. common.AllowPortsStr = allowPortStr
  233. }
  234. // plugin.xxx
  235. pluginOpts := make(map[string]HTTPPluginOptions)
  236. for _, section := range f.Sections() {
  237. name := section.Name()
  238. if !strings.HasPrefix(name, "plugin.") {
  239. continue
  240. }
  241. opt, err := loadHTTPPluginOpt(section)
  242. if err != nil {
  243. return ServerCommonConf{}, err
  244. }
  245. pluginOpts[opt.Name] = *opt
  246. }
  247. common.HTTPPlugins = pluginOpts
  248. return common, nil
  249. }
  250. func loadHTTPPluginOpt(section *ini.Section) (*HTTPPluginOptions, error) {
  251. name := strings.TrimSpace(strings.TrimPrefix(section.Name(), "plugin."))
  252. opt := &HTTPPluginOptions{}
  253. err := section.MapTo(opt)
  254. if err != nil {
  255. return nil, err
  256. }
  257. opt.Name = name
  258. return opt, nil
  259. }