| // |
| 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 |
| 15 | package legacy |
| 16 |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "os" |
| 20 | "path/filepath" |
| 21 | "slices" |
| 22 | "strings" |
| 23 |
| 24 | "gopkg.in/ini.v1" |
| 25 |
| 26 | legacyauth "github.com/fatedier/frp/pkg/auth/legacy" |
| 27 | "github.com/fatedier/frp/pkg/util/util" |
| 28 | ) |
| 29 |
| 30 | // ClientCommonConf is the configuration parsed from ini. |
| 31 | // It contains information for a client service. It is |
| 32 | // recommended to use GetDefaultClientConf instead of creating this object |
| 33 | // directly, so that all unspecified fields have reasonable default values. |
| 34 | type ClientCommonConf struct { |
| 35 | legacyauth.ClientConfig `ini:",extends"` |
| 36 |
| 37 | // ServerAddr specifies the address of the server to connect to. By |
| 38 | // default, this value is "0.0.0.0". |
| 39 | ServerAddr string `ini:"server_addr" json:"server_addr"` |
| 40 | // ServerPort specifies the port to connect to the server on. By default, |
| 41 | // this value is 7000. |
| 42 | ServerPort int `ini:"server_port" json:"server_port"` |
| 43 | // STUN server to help penetrate NAT hole. |
| 44 | NatHoleSTUNServer string `ini:"nat_hole_stun_server" json:"nat_hole_stun_server"` |
| 45 | // The maximum amount of time a dial to server will wait for a connect to complete. |
| 46 | DialServerTimeout int64 `ini:"dial_server_timeout" json:"dial_server_timeout"` |
| 47 | // DialServerKeepAlive specifies the interval between keep-alive probes for an active network connection between frpc and frps. |
| 48 | // If negative, keep-alive probes are disabled. |
| 49 | DialServerKeepAlive int64 `ini:"dial_server_keepalive" json:"dial_server_keepalive"` |
| 50 | // ConnectServerLocalIP specifies the address of the client bind when it connect to server. |
| 51 | // By default, this value is empty. |
| 52 | // this value only use in TCP/Websocket protocol. Not support in KCP protocol. |
| 53 | ConnectServerLocalIP string `ini:"connect_server_local_ip" json:"connect_server_local_ip"` |
| 54 | // HTTPProxy specifies a proxy address to connect to the server through. If |
| 55 | // this value is "", the server will be connected to directly. By default, |
| 56 | // this value is read from the "http_proxy" environment variable. |
| 57 | HTTPProxy string `ini:"http_proxy" json:"http_proxy"` |
| 58 | // LogFile specifies a file where logs will be written to. This value will |
| 59 | // only be used if LogWay is set appropriately. By default, this value is |
| 60 | // "console". |
| 61 | LogFile string `ini:"log_file" json:"log_file"` |
| 62 | // LogWay specifies the way logging is managed. Valid values are "console" |
| 63 | // or "file". If "console" is used, logs will be printed to stdout. If |
| 64 | // "file" is used, logs will be printed to LogFile. By default, this value |
| 65 | // is "console". |
| 66 | LogWay string `ini:"log_way" json:"log_way"` |
| 67 | // LogLevel specifies the minimum log level. Valid values are "trace", |
| 68 | // "debug", "info", "warn", and "error". By default, this value is "info". |
| 69 | LogLevel string `ini:"log_level" json:"log_level"` |
| 70 | // LogMaxDays specifies the maximum number of days to store log information |
| 71 | // before deletion. This is only used if LogWay == "file". By default, this |
| 72 | // value is 0. |
| 73 | LogMaxDays int64 `ini:"log_max_days" json:"log_max_days"` |
| 74 | // DisableLogColor disables log colors when LogWay == "console" when set to |
| 75 | // true. By default, this value is false. |
| 76 | DisableLogColor bool `ini:"disable_log_color" json:"disable_log_color"` |
| 77 | // AdminAddr specifies the address that the admin server binds to. By |
| 78 | // default, this value is "127.0.0.1". |
| 79 | AdminAddr string `ini:"admin_addr" json:"admin_addr"` |
| 80 | // AdminPort specifies the port for the admin server to listen on. If this |
| 81 | // value is 0, the admin server will not be started. By default, this value |
| 82 | // is 0. |
| 83 | AdminPort int `ini:"admin_port" json:"admin_port"` |
| 84 | // AdminUser specifies the username that the admin server will use for |
| 85 | // login. |
| 86 | AdminUser string `ini:"admin_user" json:"admin_user"` |
| 87 | // AdminPwd specifies the password that the admin server will use for |
| 88 | // login. |
| 89 | AdminPwd string `ini:"admin_pwd" json:"admin_pwd"` |
| 90 | // AssetsDir specifies the local directory that the admin server will load |
| 91 | // resources from. If this value is "", assets will be loaded from the |
| 92 | // bundled executable using statik. By default, this value is "". |
| 93 | AssetsDir string `ini:"assets_dir" json:"assets_dir"` |
| 94 | // PoolCount specifies the number of connections the client will make to |
| 95 | // the server in advance. By default, this value is 0. |
| 96 | PoolCount int `ini:"pool_count" json:"pool_count"` |
| 97 | // TCPMux toggles TCP stream multiplexing. This allows multiple requests |
| 98 | // from a client to share a single TCP connection. If this value is true, |
| 99 | // the server must have TCP multiplexing enabled as well. By default, this |
| 100 | // value is true. |
| 101 | TCPMux bool `ini:"tcp_mux" json:"tcp_mux"` |
| 102 | // TCPMuxKeepaliveInterval specifies the keep alive interval for TCP stream multiplier. |
| 103 | // If TCPMux is true, heartbeat of application layer is unnecessary because it can only rely on heartbeat in TCPMux. |
| 104 | TCPMuxKeepaliveInterval int64 `ini:"tcp_mux_keepalive_interval" json:"tcp_mux_keepalive_interval"` |
| 105 | // User specifies a prefix for proxy names to distinguish them from other |
| 106 | // clients. If this value is not "", proxy names will automatically be |
| 107 | // changed to "{user}.{proxy_name}". By default, this value is "". |
| 108 | User string `ini:"user" json:"user"` |
| 109 | // DNSServer specifies a DNS server address for FRPC to use. If this value |
| 110 | // is "", the default DNS will be used. By default, this value is "". |
| 111 | DNSServer string `ini:"dns_server" json:"dns_server"` |
| 112 | // LoginFailExit controls whether or not the client should exit after a |
| 113 | // failed login attempt. If false, the client will retry until a login |
| 114 | // attempt succeeds. By default, this value is true. |
| 115 | LoginFailExit bool `ini:"login_fail_exit" json:"login_fail_exit"` |
| 116 | // Start specifies a set of enabled proxies by name. If this set is empty, |
| 117 | // all supplied proxies are enabled. By default, this value is an empty |
| 118 | // set. |
| 119 | Start []string `ini:"start" json:"start"` |
| 120 | // Start map[string]struct{} `json:"start"` |
| 121 | // Protocol specifies the protocol to use when interacting with the server. |
| 122 | // Valid values are "tcp", "kcp", "quic", "websocket" and "wss". By default, this value |
| 123 | // is "tcp". |
| 124 | Protocol string `ini:"protocol" json:"protocol"` |
| 125 | // QUIC protocol options |
| 126 | QUICKeepalivePeriod int `ini:"quic_keepalive_period" json:"quic_keepalive_period"` |
| 127 | QUICMaxIdleTimeout int `ini:"quic_max_idle_timeout" json:"quic_max_idle_timeout"` |
| 128 | QUICMaxIncomingStreams int `ini:"quic_max_incoming_streams" json:"quic_max_incoming_streams"` |
| 129 | // TLSEnable specifies whether or not TLS should be used when communicating |
| 130 | // with the server. If "tls_cert_file" and "tls_key_file" are valid, |
| 131 | // client will load the supplied tls configuration. |
| 132 | // Since v0.50.0, the default value has been changed to true, and tls is enabled by default. |
| 133 | TLSEnable bool `ini:"tls_enable" json:"tls_enable"` |
| 134 | // TLSCertPath specifies the path of the cert file that client will |
| 135 | // load. It only works when "tls_enable" is true and "tls_key_file" is valid. |
| 136 | TLSCertFile string `ini:"tls_cert_file" json:"tls_cert_file"` |
| 137 | // TLSKeyPath specifies the path of the secret key file that client |
| 138 | // will load. It only works when "tls_enable" is true and "tls_cert_file" |
| 139 | // are valid. |
| 140 | TLSKeyFile string `ini:"tls_key_file" json:"tls_key_file"` |
| 141 | // TLSTrustedCaFile specifies the path of the trusted ca file that will load. |
| 142 | // It only works when "tls_enable" is valid and tls configuration of server |
| 143 | // has been specified. |
| 144 | TLSTrustedCaFile string `ini:"tls_trusted_ca_file" json:"tls_trusted_ca_file"` |
| 145 | // TLSServerName specifies the custom server name of tls certificate. By |
| 146 | // default, server name if same to ServerAddr. |
| 147 | TLSServerName string `ini:"tls_server_name" json:"tls_server_name"` |
| 148 | // If the disable_custom_tls_first_byte is set to false, frpc will establish a connection with frps using the |
| 149 | // first custom byte when tls is enabled. |
| 150 | // Since v0.50.0, the default value has been changed to true, and the first custom byte is disabled by default. |
| 151 | DisableCustomTLSFirstByte bool `ini:"disable_custom_tls_first_byte" json:"disable_custom_tls_first_byte"` |
| 152 | // HeartBeatInterval specifies at what interval heartbeats are sent to the |
| 153 | // server, in seconds. It is not recommended to change this value. By |
| 154 | // default, this value is 30. Set negative value to disable it. |
| 155 | HeartbeatInterval int64 `ini:"heartbeat_interval" json:"heartbeat_interval"` |
| 156 | // HeartBeatTimeout specifies the maximum allowed heartbeat response delay |
| 157 | // before the connection is terminated, in seconds. It is not recommended |
| 158 | // to change this value. By default, this value is 90. Set negative value to disable it. |
| 159 | HeartbeatTimeout int64 `ini:"heartbeat_timeout" json:"heartbeat_timeout"` |
| 160 | // Client meta info |
| 161 | Metas map[string]string `ini:"-" json:"metas"` |
| 162 | // UDPPacketSize specifies the udp packet size |
| 163 | // By default, this value is 1500 |
| 164 | UDPPacketSize int64 `ini:"udp_packet_size" json:"udp_packet_size"` |
| 165 | // Include other config files for proxies. |
| 166 | IncludeConfigFiles []string `ini:"includes" json:"includes"` |
| 167 | // Enable golang pprof handlers in admin listener. |
| 168 | // Admin port must be set first. |
| 169 | PprofEnable bool `ini:"pprof_enable" json:"pprof_enable"` |
| 170 | } |
| 171 |
| 172 | // Supported sources including: string(file path), []byte, Reader interface. |
| 173 | func UnmarshalClientConfFromIni(source any) (ClientCommonConf, error) { |
| 174 | f, err := ini.LoadSources(ini.LoadOptions{ |
| 175 | Insensitive: false, |
| 176 | InsensitiveSections: false, |
| 177 | InsensitiveKeys: false, |
| 178 | IgnoreInlineComment: true, |
| 179 | AllowBooleanKeys: true, |
| 180 | }, source) |
| 181 | if err != nil { |
| 182 | return ClientCommonConf{}, err |
| 183 | } |
| 184 |
| 185 | s, err := f.GetSection("common") |
| 186 | if err != nil { |
| 187 | return ClientCommonConf{}, fmt.Errorf("invalid configuration file, not found [common] section") |
| 188 | } |
| 189 |
| 190 | common := GetDefaultClientConf() |
| 191 | err = s.MapTo(&common) |
| 192 | if err != nil { |
| 193 | return ClientCommonConf{}, err |
| 194 | } |
| 195 |
| 196 | common.Metas = GetMapWithoutPrefix(s.KeysHash(), "meta_") |
| 197 | common.OidcAdditionalEndpointParams = GetMapWithoutPrefix(s.KeysHash(), "oidc_additional_") |
| 198 |
| 199 | return common, nil |
| 200 | } |
| 201 |
| 202 | // if len(startProxy) is 0, start all |
| 203 | // otherwise just start proxies in startProxy map |
| 204 | func LoadAllProxyConfsFromIni( |
| 205 | prefix string, |
| 206 | source any, |
| 207 | start []string, |
| 208 | ) (map[string]ProxyConf, map[string]VisitorConf, error) { |
| 209 | f, err := ini.LoadSources(ini.LoadOptions{ |
| 210 | Insensitive: false, |
| 211 | InsensitiveSections: false, |
| 212 | InsensitiveKeys: false, |
| 213 | IgnoreInlineComment: true, |
| 214 | AllowBooleanKeys: true, |
| 215 | }, source) |
| 216 | if err != nil { |
| 217 | return nil, nil, err |
| 218 | } |
| 219 |
| 220 | proxyConfs := make(map[string]ProxyConf) |
| 221 | visitorConfs := make(map[string]VisitorConf) |
| 222 |
| 223 | if prefix != "" { |
| 224 | prefix += "." |
| 225 | } |
| 226 |
| 227 | startProxy := make(map[string]struct{}) |
| 228 | for _, s := range start { |
| 229 | startProxy[s] = struct{}{} |
| 230 | } |
| 231 |
| 232 | startAll := len(startProxy) == 0 |
| 233 |
| 234 | // Build template sections from range section And append to ini.File. |
| 235 | rangeSections := make([]*ini.Section, 0) |
| 236 | for _, section := range f.Sections() { |
| 237 |
| 238 | if !strings.HasPrefix(section.Name(), "range:") { |
| 239 | continue |
| 240 | } |
| 241 |
| 242 | rangeSections = append(rangeSections, section) |
| 243 | } |
| 244 |
| 245 | for _, section := range rangeSections { |
| 246 | err = renderRangeProxyTemplates(f, section) |
| 247 | if err != nil { |
| 248 | return nil, nil, fmt.Errorf("failed to render template for proxy %s: %v", section.Name(), err) |
| 249 | } |
| 250 | } |
| 251 |
| 252 | for _, section := range f.Sections() { |
| 253 | name := section.Name() |
| 254 |
| 255 | if name == ini.DefaultSection || name == "common" || strings.HasPrefix(name, "range:") { |
| 256 | continue |
| 257 | } |
| 258 |
| 259 | _, shouldStart := startProxy[name] |
| 260 | if !startAll && !shouldStart { |
| 261 | continue |
| 262 | } |
| 263 |
| 264 | roleType := section.Key("role").String() |
| 265 | if roleType == "" { |
| 266 | roleType = "server" |
| 267 | } |
| 268 |
| 269 | switch roleType { |
| 270 | case "server": |
| 271 | newConf, newErr := NewProxyConfFromIni(prefix, name, section) |
| 272 | if newErr != nil { |
| 273 | return nil, nil, fmt.Errorf("failed to parse proxy %s, err: %v", name, newErr) |
| 274 | } |
| 275 | proxyConfs[prefix+name] = newConf |
| 276 | case "visitor": |
| 277 | newConf, newErr := NewVisitorConfFromIni(prefix, name, section) |
| 278 | if newErr != nil { |
| 279 | return nil, nil, fmt.Errorf("failed to parse visitor %s, err: %v", name, newErr) |
| 280 | } |
| 281 | visitorConfs[prefix+name] = newConf |
| 282 | default: |
| 283 | return nil, nil, fmt.Errorf("proxy %s role should be 'server' or 'visitor'", name) |
| 284 | } |
| 285 | } |
| 286 | return proxyConfs, visitorConfs, nil |
| 287 | } |
| 288 |
| 289 | func renderRangeProxyTemplates(f *ini.File, section *ini.Section) error { |
| 290 | // Validation |
| 291 | localPortStr := section.Key("local_port").String() |
| 292 | remotePortStr := section.Key("remote_port").String() |
| 293 | if localPortStr == "" || remotePortStr == "" { |
| 294 | return fmt.Errorf("local_port or remote_port is empty") |
| 295 | } |
| 296 |
| 297 | localPorts, err := util.ParseRangeNumbers(localPortStr) |
| 298 | if err != nil { |
| 299 | return err |
| 300 | } |
| 301 |
| 302 | remotePorts, err := util.ParseRangeNumbers(remotePortStr) |
| 303 | if err != nil { |
| 304 | return err |
| 305 | } |
| 306 |
| 307 | if len(localPorts) != len(remotePorts) { |
| 308 | return fmt.Errorf("local ports number should be same with remote ports number") |
| 309 | } |
| 310 |
| 311 | if len(localPorts) == 0 { |
| 312 | return fmt.Errorf("local_port and remote_port is necessary") |
| 313 | } |
| 314 |
| 315 | // Templates |
| 316 | prefix := strings.TrimSpace(strings.TrimPrefix(section.Name(), "range:")) |
| 317 |
| 318 | for i := range localPorts { |
| 319 | tmpname := fmt.Sprintf("%s_%d", prefix, i) |
| 320 |
| 321 | tmpsection, err := f.NewSection(tmpname) |
| 322 | if err != nil { |
| 323 | return err |
| 324 | } |
| 325 |
| 326 | copySection(section, tmpsection) |
| 327 | if _, err := tmpsection.NewKey("local_port", fmt.Sprintf("%d", localPorts[i])); err != nil { |
| 328 | return fmt.Errorf("local_port new key in section error: %v", err) |
| 329 | } |
| 330 | if _, err := tmpsection.NewKey("remote_port", fmt.Sprintf("%d", remotePorts[i])); err != nil { |
| 331 | return fmt.Errorf("remote_port new key in section error: %v", err) |
| 332 | } |
| 333 | } |
| 334 |
| 335 | return nil |
| 336 | } |
| 337 |
| 338 | func copySection(source, target *ini.Section) { |
| 339 | for key, value := range source.KeysHash() { |
| 340 | _, _ = target.NewKey(key, value) |
| 341 | } |
| 342 | } |
| 343 |
| 344 | // GetDefaultClientConf returns a client configuration with default values. |
| 345 | // Note: Some default values here will be set to empty and will be converted to them |
| 346 | // new configuration through the 'Complete' function to set them as the default |
| 347 | // values of the new configuration. |
| 348 | func GetDefaultClientConf() ClientCommonConf { |
| 349 | return ClientCommonConf{ |
| 350 | ClientConfig: legacyauth.GetDefaultClientConf(), |
| 351 | TCPMux: true, |
| 352 | LoginFailExit: true, |
| 353 | Protocol: "tcp", |
| 354 | Start: make([]string, 0), |
| 355 | TLSEnable: true, |
| 356 | DisableCustomTLSFirstByte: true, |
| 357 | Metas: make(map[string]string), |
| 358 | IncludeConfigFiles: make([]string, 0), |
| 359 | } |
| 360 | } |
| 361 |
| 362 | func (cfg *ClientCommonConf) Validate() error { |
| 363 | if cfg.HeartbeatTimeout > 0 && cfg.HeartbeatInterval > 0 { |
| 364 | if cfg.HeartbeatTimeout < cfg.HeartbeatInterval { |
| 365 | return fmt.Errorf("invalid heartbeat_timeout, heartbeat_timeout is less than heartbeat_interval") |
| 366 | } |
| 367 | } |
| 368 |
| 369 | if !cfg.TLSEnable { |
| 370 | if cfg.TLSCertFile != "" { |
| 371 | fmt.Println("WARNING! tls_cert_file is invalid when tls_enable is false") |
| 372 | } |
| 373 |
| 374 | if cfg.TLSKeyFile != "" { |
| 375 | fmt.Println("WARNING! tls_key_file is invalid when tls_enable is false") |
| 376 | } |
| 377 |
| 378 | if cfg.TLSTrustedCaFile != "" { |
| 379 | fmt.Println("WARNING! tls_trusted_ca_file is invalid when tls_enable is false") |
| 380 | } |
| 381 | } |
| 382 |
| 383 | if !slices.Contains([]string{"tcp", "kcp", "quic", "websocket", "wss"}, cfg.Protocol) { |
| 384 | return fmt.Errorf("invalid protocol") |
| 385 | } |
| 386 |
| 387 | for _, f := range cfg.IncludeConfigFiles { |
| 388 | absDir, err := filepath.Abs(filepath.Dir(f)) |
| 389 | if err != nil { |
| 390 | return fmt.Errorf("include: parse directory of %s failed: %v", f, err) |
| 391 | } |
| 392 | if _, err := os.Stat(absDir); os.IsNotExist(err) { |
| 393 | return fmt.Errorf("include: directory of %s not exist", f) |
| 394 | } |
| 395 | } |
| 396 | return nil |
| 397 | } |