server_common.go 14 KB

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