server_common.go 16.2 KB
Newer Older
F
fatedier 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright 2016 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package config

import (
	"fmt"
	"strconv"
	"strings"

F
fatedier 已提交
22 23 24
	"github.com/fatedier/frp/pkg/auth"
	plugin "github.com/fatedier/frp/pkg/plugin/server"
	"github.com/fatedier/frp/pkg/util/util"
25

F
fatedier 已提交
26
	ini "github.com/vaughan0/go-ini"
F
fatedier 已提交
27 28
)

29 30 31
// ServerCommonConf contains information for a server service. It is
// recommended to use GetDefaultServerConf instead of creating this object
// directly, so that all unspecified fields have reasonable default values.
F
fatedier 已提交
32
type ServerCommonConf struct {
F
fatedier 已提交
33
	auth.ServerConfig
34 35 36 37 38 39
	// BindAddr specifies the address that the server binds to. By default,
	// this value is "0.0.0.0".
	BindAddr string `json:"bind_addr"`
	// BindPort specifies the port that the server listens on. By default, this
	// value is 7000.
	BindPort int `json:"bind_port"`
F
fatedier 已提交
40
	// BindUDPPort specifies the UDP port that the server listens on. If this
41 42
	// value is 0, the server will not listen for UDP connections. By default,
	// this value is 0
F
fatedier 已提交
43 44
	BindUDPPort int `json:"bind_udp_port"`
	// KCPBindPort specifies the KCP port that the server listens on. If this
45 46
	// value is 0, the server will not listen for KCP connections. By default,
	// this value is 0.
F
fatedier 已提交
47
	KCPBindPort int `json:"kcp_bind_port"`
48 49
	// ProxyBindAddr specifies the address that the proxy binds to. This value
	// may be the same as BindAddr. By default, this value is "0.0.0.0".
F
fatedier 已提交
50
	ProxyBindAddr string `json:"proxy_bind_addr"`
F
fatedier 已提交
51
	// VhostHTTPPort specifies the port that the server listens for HTTP Vhost
52 53
	// requests. If this value is 0, the server will not listen for HTTP
	// requests. By default, this value is 0.
F
fatedier 已提交
54 55
	VhostHTTPPort int `json:"vhost_http_port"`
	// VhostHTTPSPort specifies the port that the server listens for HTTPS
56 57
	// Vhost requests. If this value is 0, the server will not listen for HTTPS
	// requests. By default, this value is 0.
F
fatedier 已提交
58 59
	VhostHTTPSPort int `json:"vhost_https_port"`
	// TCPMuxHTTPConnectPort specifies the port that the server listens for TCP
60 61 62
	// HTTP CONNECT requests. If the value is 0, the server will not multiplex TCP
	// requests on one single port. If it's not - it will listen on this value for
	// HTTP CONNECT requests. By default, this value is 0.
F
fatedier 已提交
63 64
	TCPMuxHTTPConnectPort int `json:"tcpmux_httpconnect_port"`
	// VhostHTTPTimeout specifies the response header timeout for the Vhost
65
	// HTTP server, in seconds. By default, this value is 60.
F
fatedier 已提交
66
	VhostHTTPTimeout int64 `json:"vhost_http_timeout"`
67 68
	// DashboardAddr specifies the address that the dashboard binds to. By
	// default, this value is "0.0.0.0".
F
fatedier 已提交
69
	DashboardAddr string `json:"dashboard_addr"`
70 71 72 73 74 75 76 77 78 79
	// DashboardPort specifies the port that the dashboard listens on. If this
	// value is 0, the dashboard will not be started. By default, this value is
	// 0.
	DashboardPort int `json:"dashboard_port"`
	// DashboardUser specifies the username that the dashboard will use for
	// login. By default, this value is "admin".
	DashboardUser string `json:"dashboard_user"`
	// DashboardUser specifies the password that the dashboard will use for
	// login. By default, this value is "admin".
	DashboardPwd string `json:"dashboard_pwd"`
80 81 82
	// EnablePrometheus will export prometheus metrics on {dashboard_addr}:{dashboard_port}
	// in /metrics api.
	EnablePrometheus bool `json:"enable_prometheus"`
83 84 85
	// AssetsDir specifies the local directory that the dashboard will load
	// resources from. If this value is "", assets will be loaded from the
	// bundled executable using statik. By default, this value is "".
Y
yuyulei 已提交
86
	AssetsDir string `json:"assets_dir"`
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	// LogFile specifies a file where logs will be written to. This value will
	// only be used if LogWay is set appropriately. By default, this value is
	// "console".
	LogFile string `json:"log_file"`
	// LogWay specifies the way logging is managed. Valid values are "console"
	// or "file". If "console" is used, logs will be printed to stdout. If
	// "file" is used, logs will be printed to LogFile. By default, this value
	// is "console".
	LogWay string `json:"log_way"`
	// LogLevel specifies the minimum log level. Valid values are "trace",
	// "debug", "info", "warn", and "error". By default, this value is "info".
	LogLevel string `json:"log_level"`
	// LogMaxDays specifies the maximum number of days to store log information
	// before deletion. This is only used if LogWay == "file". By default, this
	// value is 0.
	LogMaxDays int64 `json:"log_max_days"`
	// DisableLogColor disables log colors when LogWay == "console" when set to
	// true. By default, this value is false.
	DisableLogColor bool `json:"disable_log_color"`
106 107 108
	// DetailedErrorsToClient defines whether to send the specific error (with
	// debug info) to frpc. By default, this value is true.
	DetailedErrorsToClient bool `json:"detailed_errors_to_client"`
109

110 111 112 113 114 115
	// SubDomainHost specifies the domain that will be attached to sub-domains
	// requested by the client when using Vhost proxying. For example, if this
	// value is set to "frps.com" and the client requested the subdomain
	// "test", the resulting URL would be "test.frps.com". By default, this
	// value is "".
	SubDomainHost string `json:"subdomain_host"`
F
fatedier 已提交
116
	// TCPMux toggles TCP stream multiplexing. This allows multiple requests
117 118
	// from a client to share a single TCP connection. By default, this value
	// is true.
F
fatedier 已提交
119
	TCPMux bool `json:"tcp_mux"`
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
	// Custom404Page specifies a path to a custom 404 page to display. If this
	// value is "", a default page will be displayed. By default, this value is
	// "".
	Custom404Page string `json:"custom_404_page"`

	// AllowPorts specifies a set of ports that clients are able to proxy to.
	// If the length of this value is 0, all ports are allowed. By default,
	// this value is an empty set.
	AllowPorts map[int]struct{}
	// MaxPoolCount specifies the maximum pool size for each proxy. By default,
	// this value is 5.
	MaxPoolCount int64 `json:"max_pool_count"`
	// MaxPortsPerClient specifies the maximum number of ports a single client
	// may proxy to. If this value is 0, no limit will be applied. By default,
	// this value is 0.
F
fatedier 已提交
135
	MaxPortsPerClient int64 `json:"max_ports_per_client"`
136 137
	// TLSOnly specifies whether to only accept TLS-encrypted connections.
	// By default, the value is false.
F
fatedier 已提交
138
	TLSOnly bool `json:"tls_only"`
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
	// TLSCertFile specifies the path of the cert file that the server will
	// load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
	// supplied tls configuration. Otherwise, the server will use the tls
	// configuration generated by itself.
	TLSCertFile string `json:"tls_cert_file"`
	// TLSKeyFile specifies the path of the secret key that the server will
	// load. If "tls_cert_file", "tls_key_file" are valid, the server will use this
	// supplied tls configuration. Otherwise, the server will use the tls
	// configuration generated by itself.
	TLSKeyFile string `json:"tls_key_file"`
	// TLSTrustedCaFile specifies the paths of the client cert files that the
	// server will load. It only works when "tls_only" is true. If
	// "tls_trusted_ca_file" is valid, the server will verify each client's
	// certificate.
	TLSTrustedCaFile string `json:"tls_trusted_ca_file"`
154 155 156
	// HeartBeatTimeout specifies the maximum time to wait for a heartbeat
	// before terminating the connection. It is not recommended to change this
	// value. By default, this value is 90.
Y
yuyulei 已提交
157
	HeartbeatTimeout int64 `json:"heartbeat_timeout"`
158 159 160
	// UserConnTimeout specifies the maximum time to wait for a work
	// connection. By default, this value is 10.
	UserConnTimeout int64 `json:"user_conn_timeout"`
F
fatedier 已提交
161 162
	// HTTPPlugins specify the server plugins support HTTP protocol.
	HTTPPlugins map[string]plugin.HTTPPluginOptions `json:"http_plugins"`
F
fatedier 已提交
163
	// UDPPacketSize specifies the UDP packet size
164
	// By default, this value is 1500
F
fatedier 已提交
165
	UDPPacketSize int64 `json:"udp_packet_size"`
F
fatedier 已提交
166 167
}

168 169
// GetDefaultServerConf returns a server configuration with reasonable
// defaults.
170 171
func GetDefaultServerConf() ServerCommonConf {
	return ServerCommonConf{
172 173
		BindAddr:               "0.0.0.0",
		BindPort:               7000,
F
fatedier 已提交
174 175
		BindUDPPort:            0,
		KCPBindPort:            0,
176
		ProxyBindAddr:          "0.0.0.0",
F
fatedier 已提交
177 178 179 180
		VhostHTTPPort:          0,
		VhostHTTPSPort:         0,
		TCPMuxHTTPConnectPort:  0,
		VhostHTTPTimeout:       60,
181 182 183 184
		DashboardAddr:          "0.0.0.0",
		DashboardPort:          0,
		DashboardUser:          "admin",
		DashboardPwd:           "admin",
185
		EnablePrometheus:       false,
186 187 188 189 190 191 192 193
		AssetsDir:              "",
		LogFile:                "console",
		LogWay:                 "console",
		LogLevel:               "info",
		LogMaxDays:             3,
		DisableLogColor:        false,
		DetailedErrorsToClient: true,
		SubDomainHost:          "",
F
fatedier 已提交
194
		TCPMux:                 true,
195 196 197
		AllowPorts:             make(map[int]struct{}),
		MaxPoolCount:           5,
		MaxPortsPerClient:      0,
F
fatedier 已提交
198
		TLSOnly:                false,
199 200 201
		TLSCertFile:            "",
		TLSKeyFile:             "",
		TLSTrustedCaFile:       "",
Y
yuyulei 已提交
202
		HeartbeatTimeout:       90,
203 204 205
		UserConnTimeout:        10,
		Custom404Page:          "",
		HTTPPlugins:            make(map[string]plugin.HTTPPluginOptions),
F
fatedier 已提交
206
		UDPPacketSize:          1500,
F
fatedier 已提交
207 208 209
	}
}

210 211
// UnmarshalServerConfFromIni parses the contents of a server configuration ini
// file and returns the resulting server configuration.
212 213
func UnmarshalServerConfFromIni(content string) (cfg ServerCommonConf, err error) {
	cfg = GetDefaultServerConf()
F
fatedier 已提交
214 215 216 217

	conf, err := ini.Load(strings.NewReader(content))
	if err != nil {
		err = fmt.Errorf("parse ini conf file error: %v", err)
218
		return ServerCommonConf{}, err
F
fatedier 已提交
219 220
	}

F
fatedier 已提交
221 222
	UnmarshalPluginsFromIni(conf, &cfg)

F
fatedier 已提交
223
	cfg.ServerConfig = auth.UnmarshalServerConfFromIni(conf)
224

F
fatedier 已提交
225 226 227 228 229
	var (
		tmpStr string
		ok     bool
		v      int64
	)
F
fatedier 已提交
230
	if tmpStr, ok = conf.Get("common", "bind_addr"); ok {
F
fatedier 已提交
231 232 233
		cfg.BindAddr = tmpStr
	}

F
fatedier 已提交
234
	if tmpStr, ok = conf.Get("common", "bind_port"); ok {
235 236 237
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid bind_port")
			return
F
fatedier 已提交
238
		}
F
fatedier 已提交
239
		cfg.BindPort = int(v)
F
fatedier 已提交
240 241
	}

F
fatedier 已提交
242
	if tmpStr, ok = conf.Get("common", "bind_udp_port"); ok {
243 244 245
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid bind_udp_port")
			return
F
fatedier 已提交
246
		}
F
fatedier 已提交
247
		cfg.BindUDPPort = int(v)
F
fatedier 已提交
248 249
	}

F
fatedier 已提交
250
	if tmpStr, ok = conf.Get("common", "kcp_bind_port"); ok {
251 252 253
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid kcp_bind_port")
			return
F
fatedier 已提交
254
		}
F
fatedier 已提交
255
		cfg.KCPBindPort = int(v)
F
fatedier 已提交
256 257
	}

F
fatedier 已提交
258
	if tmpStr, ok = conf.Get("common", "proxy_bind_addr"); ok {
F
fatedier 已提交
259 260 261 262 263
		cfg.ProxyBindAddr = tmpStr
	} else {
		cfg.ProxyBindAddr = cfg.BindAddr
	}

F
fatedier 已提交
264
	if tmpStr, ok = conf.Get("common", "vhost_http_port"); ok {
265 266
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid vhost_http_port")
F
fatedier 已提交
267 268
			return
		}
F
fatedier 已提交
269
		cfg.VhostHTTPPort = int(v)
F
fatedier 已提交
270
	} else {
F
fatedier 已提交
271
		cfg.VhostHTTPPort = 0
F
fatedier 已提交
272 273
	}

F
fatedier 已提交
274
	if tmpStr, ok = conf.Get("common", "vhost_https_port"); ok {
275 276
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid vhost_https_port")
F
fatedier 已提交
277 278
			return
		}
F
fatedier 已提交
279
		cfg.VhostHTTPSPort = int(v)
F
fatedier 已提交
280
	} else {
F
fatedier 已提交
281
		cfg.VhostHTTPSPort = 0
F
fatedier 已提交
282 283
	}

284 285 286 287 288
	if tmpStr, ok = conf.Get("common", "tcpmux_httpconnect_port"); ok {
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid tcpmux_httpconnect_port")
			return
		}
F
fatedier 已提交
289
		cfg.TCPMuxHTTPConnectPort = int(v)
290
	} else {
F
fatedier 已提交
291
		cfg.TCPMuxHTTPConnectPort = 0
292 293
	}

F
fatedier 已提交
294 295 296 297 298 299
	if tmpStr, ok = conf.Get("common", "vhost_http_timeout"); ok {
		v, errRet := strconv.ParseInt(tmpStr, 10, 64)
		if errRet != nil || v < 0 {
			err = fmt.Errorf("Parse conf error: invalid vhost_http_timeout")
			return
		}
F
fatedier 已提交
300
		cfg.VhostHTTPTimeout = v
F
fatedier 已提交
301 302
	}

F
fatedier 已提交
303
	if tmpStr, ok = conf.Get("common", "dashboard_addr"); ok {
T
timerever 已提交
304 305 306 307 308
		cfg.DashboardAddr = tmpStr
	} else {
		cfg.DashboardAddr = cfg.BindAddr
	}

F
fatedier 已提交
309
	if tmpStr, ok = conf.Get("common", "dashboard_port"); ok {
310 311
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid dashboard_port")
F
fatedier 已提交
312 313
			return
		}
F
fatedier 已提交
314
		cfg.DashboardPort = int(v)
F
fatedier 已提交
315 316 317 318
	} else {
		cfg.DashboardPort = 0
	}

F
fatedier 已提交
319
	if tmpStr, ok = conf.Get("common", "dashboard_user"); ok {
F
fatedier 已提交
320 321 322
		cfg.DashboardUser = tmpStr
	}

F
fatedier 已提交
323
	if tmpStr, ok = conf.Get("common", "dashboard_pwd"); ok {
F
fatedier 已提交
324 325 326
		cfg.DashboardPwd = tmpStr
	}

327 328 329 330
	if tmpStr, ok = conf.Get("common", "enable_prometheus"); ok && tmpStr == "true" {
		cfg.EnablePrometheus = true
	}

F
fatedier 已提交
331
	if tmpStr, ok = conf.Get("common", "assets_dir"); ok {
F
fatedier 已提交
332 333 334
		cfg.AssetsDir = tmpStr
	}

F
fatedier 已提交
335
	if tmpStr, ok = conf.Get("common", "log_file"); ok {
F
fatedier 已提交
336 337 338 339 340 341 342 343
		cfg.LogFile = tmpStr
		if cfg.LogFile == "console" {
			cfg.LogWay = "console"
		} else {
			cfg.LogWay = "file"
		}
	}

F
fatedier 已提交
344
	if tmpStr, ok = conf.Get("common", "log_level"); ok {
F
fatedier 已提交
345 346 347
		cfg.LogLevel = tmpStr
	}

F
fatedier 已提交
348
	if tmpStr, ok = conf.Get("common", "log_max_days"); ok {
F
fatedier 已提交
349 350 351 352 353 354
		v, err = strconv.ParseInt(tmpStr, 10, 64)
		if err == nil {
			cfg.LogMaxDays = v
		}
	}

355 356 357 358
	if tmpStr, ok = conf.Get("common", "disable_log_color"); ok && tmpStr == "true" {
		cfg.DisableLogColor = true
	}

359 360 361 362 363 364
	if tmpStr, ok = conf.Get("common", "detailed_errors_to_client"); ok && tmpStr == "false" {
		cfg.DetailedErrorsToClient = false
	} else {
		cfg.DetailedErrorsToClient = true
	}

F
fatedier 已提交
365
	if allowPortsStr, ok := conf.Get("common", "allow_ports"); ok {
F
fatedier 已提交
366 367 368
		// e.g. 1000-2000,2001,2002,3000-4000
		ports, errRet := util.ParseRangeNumbers(allowPortsStr)
		if errRet != nil {
F
fatedier 已提交
369
			err = fmt.Errorf("Parse conf error: allow_ports: %v", errRet)
F
fatedier 已提交
370 371
			return
		}
372

F
fatedier 已提交
373
		for _, port := range ports {
F
fatedier 已提交
374
			cfg.AllowPorts[int(port)] = struct{}{}
F
fatedier 已提交
375 376 377
		}
	}

F
fatedier 已提交
378
	if tmpStr, ok = conf.Get("common", "max_pool_count"); ok {
F
fatedier 已提交
379 380 381
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid max_pool_count")
			return
F
fatedier 已提交
382
		}
F
fatedier 已提交
383 384 385 386 387 388

		if v < 0 {
			err = fmt.Errorf("Parse conf error: invalid max_pool_count")
			return
		}
		cfg.MaxPoolCount = v
F
fatedier 已提交
389 390
	}

F
fatedier 已提交
391
	if tmpStr, ok = conf.Get("common", "max_ports_per_client"); ok {
F
fatedier 已提交
392 393 394 395
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
			return
		}
F
fatedier 已提交
396 397 398 399 400 401

		if v < 0 {
			err = fmt.Errorf("Parse conf error: invalid max_ports_per_client")
			return
		}
		cfg.MaxPortsPerClient = v
F
fatedier 已提交
402 403
	}

F
fatedier 已提交
404
	if tmpStr, ok = conf.Get("common", "subdomain_host"); ok {
F
fatedier 已提交
405 406 407
		cfg.SubDomainHost = strings.ToLower(strings.TrimSpace(tmpStr))
	}

F
fatedier 已提交
408
	if tmpStr, ok = conf.Get("common", "tcp_mux"); ok && tmpStr == "false" {
F
fatedier 已提交
409
		cfg.TCPMux = false
410
	} else {
F
fatedier 已提交
411
		cfg.TCPMux = true
412 413
	}

F
fatedier 已提交
414 415 416 417
	if tmpStr, ok = conf.Get("common", "custom_404_page"); ok {
		cfg.Custom404Page = tmpStr
	}

F
fatedier 已提交
418
	if tmpStr, ok = conf.Get("common", "heartbeat_timeout"); ok {
F
fatedier 已提交
419 420 421 422 423
		v, errRet := strconv.ParseInt(tmpStr, 10, 64)
		if errRet != nil {
			err = fmt.Errorf("Parse conf error: heartbeat_timeout is incorrect")
			return
		}
Y
yuyulei 已提交
424
		cfg.HeartbeatTimeout = v
F
fatedier 已提交
425
	}
426 427

	if tmpStr, ok = conf.Get("common", "tls_only"); ok && tmpStr == "true" {
F
fatedier 已提交
428
		cfg.TLSOnly = true
429
	} else {
F
fatedier 已提交
430
		cfg.TLSOnly = false
431
	}
432 433 434 435 436 437

	if tmpStr, ok = conf.Get("common", "udp_packet_size"); ok {
		if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
			err = fmt.Errorf("Parse conf error: invalid udp_packet_size")
			return
		}
F
fatedier 已提交
438
		cfg.UDPPacketSize = v
439
	}
440 441 442 443 444 445 446 447 448 449 450

	if tmpStr, ok := conf.Get("common", "tls_cert_file"); ok {
		cfg.TLSCertFile = tmpStr
	}

	if tmpStr, ok := conf.Get("common", "tls_key_file"); ok {
		cfg.TLSKeyFile = tmpStr
	}

	if tmpStr, ok := conf.Get("common", "tls_trusted_ca_file"); ok {
		cfg.TLSTrustedCaFile = tmpStr
F
fatedier 已提交
451
		cfg.TLSOnly = true
452 453
	}

F
fatedier 已提交
454 455
	return
}
F
fatedier 已提交
456

F
fatedier 已提交
457 458 459 460 461 462 463 464 465 466
func UnmarshalPluginsFromIni(sections ini.File, cfg *ServerCommonConf) {
	for name, section := range sections {
		if strings.HasPrefix(name, "plugin.") {
			name = strings.TrimSpace(strings.TrimPrefix(name, "plugin."))
			options := plugin.HTTPPluginOptions{
				Name: name,
				Addr: section["addr"],
				Path: section["path"],
				Ops:  strings.Split(section["ops"], ","),
			}
F
fatedier 已提交
467
			for i := range options.Ops {
F
fatedier 已提交
468 469 470 471 472 473 474
				options.Ops[i] = strings.TrimSpace(options.Ops[i])
			}
			cfg.HTTPPlugins[name] = options
		}
	}
}

F
fatedier 已提交
475 476
func (cfg *ServerCommonConf) Check() error {
	return nil
F
fatedier 已提交
477
}