| // |
| 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 config |
| 16 |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "encoding/json" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "os" |
| 23 | "path/filepath" |
| 24 | "strings" |
| 25 | "text/template" |
| 26 |
| 27 | toml "github.com/pelletier/go-toml/v2" |
| 28 | "github.com/samber/lo" |
| 29 | "gopkg.in/ini.v1" |
| 30 | "k8s.io/apimachinery/pkg/util/sets" |
| 31 | "k8s.io/apimachinery/pkg/util/yaml" |
| 32 |
| 33 | "github.com/fatedier/frp/pkg/config/legacy" |
| 34 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 35 | "github.com/fatedier/frp/pkg/config/v1/validation" |
| 36 | "github.com/fatedier/frp/pkg/msg" |
| 37 | "github.com/fatedier/frp/pkg/util/jsonx" |
| 38 | "github.com/fatedier/frp/pkg/util/util" |
| 39 | ) |
| 40 |
| 41 | var glbEnvs map[string]string |
| 42 |
| 43 | func init() { |
| 44 | glbEnvs = make(map[string]string) |
| 45 | envs := os.Environ() |
| 46 | for _, env := range envs { |
| 47 | pair := strings.SplitN(env, "=", 2) |
| 48 | if len(pair) != 2 { |
| 49 | continue |
| 50 | } |
| 51 | glbEnvs[pair[0]] = pair[1] |
| 52 | } |
| 53 | } |
| 54 |
| 55 | type Values struct { |
| 56 | Envs map[string]string // environment vars |
| 57 | } |
| 58 |
| 59 | func GetValues() *Values { |
| 60 | return &Values{ |
| 61 | Envs: glbEnvs, |
| 62 | } |
| 63 | } |
| 64 |
| 65 | func DetectLegacyINIFormat(content []byte) bool { |
| 66 | f, err := ini.Load(content) |
| 67 | if err != nil { |
| 68 | return false |
| 69 | } |
| 70 | if _, err := f.GetSection("common"); err == nil { |
| 71 | return true |
| 72 | } |
| 73 | return false |
| 74 | } |
| 75 |
| 76 | func DetectLegacyINIFormatFromFile(path string) bool { |
| 77 | b, err := os.ReadFile(path) |
| 78 | if err != nil { |
| 79 | return false |
| 80 | } |
| 81 | return DetectLegacyINIFormat(b) |
| 82 | } |
| 83 |
| 84 | func RenderWithTemplate(in []byte, values *Values) ([]byte, error) { |
| 85 | tmpl, err := template.New("frp").Funcs(template.FuncMap{ |
| 86 | "parseNumberRange": parseNumberRange, |
| 87 | "parseNumberRangePair": parseNumberRangePair, |
| 88 | }).Parse(string(in)) |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 |
| 93 | buffer := bytes.NewBufferString("") |
| 94 | if err := tmpl.Execute(buffer, values); err != nil { |
| 95 | return nil, err |
| 96 | } |
| 97 | return buffer.Bytes(), nil |
| 98 | } |
| 99 |
| 100 | func LoadFileContentWithTemplate(path string, values *Values) ([]byte, error) { |
| 101 | b, err := os.ReadFile(path) |
| 102 | if err != nil { |
| 103 | return nil, err |
| 104 | } |
| 105 | return RenderWithTemplate(b, values) |
| 106 | } |
| 107 |
| 108 | func LoadConfigureFromFile(path string, c any, strict bool) error { |
| 109 | content, err := LoadFileContentWithTemplate(path, GetValues()) |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | return LoadConfigure(content, c, strict, detectFormatFromPath(path)) |
| 114 | } |
| 115 |
| 116 | // detectFormatFromPath returns a format hint based on the file extension. |
| 117 | func detectFormatFromPath(path string) string { |
| 118 | switch strings.ToLower(filepath.Ext(path)) { |
| 119 | case ".toml": |
| 120 | return "toml" |
| 121 | case ".yaml", ".yml": |
| 122 | return "yaml" |
| 123 | case ".json": |
| 124 | return "json" |
| 125 | default: |
| 126 | return "" |
| 127 | } |
| 128 | } |
| 129 |
| 130 | // parseYAMLWithDotFieldsHandling parses YAML with dot-prefixed fields handling |
| 131 | // This function handles both cases efficiently: with or without dot fields |
| 132 | func parseYAMLWithDotFieldsHandling(content []byte, target any) error { |
| 133 | var temp any |
| 134 | if err := yaml.Unmarshal(content, &temp); err != nil { |
| 135 | return err |
| 136 | } |
| 137 |
| 138 | // Remove dot fields if it's a map |
| 139 | if tempMap, ok := temp.(map[string]any); ok { |
| 140 | for key := range tempMap { |
| 141 | if strings.HasPrefix(key, ".") { |
| 142 | delete(tempMap, key) |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 |
| 147 | // Convert to JSON and decode with strict validation |
| 148 | jsonBytes, err := jsonx.Marshal(temp) |
| 149 | if err != nil { |
| 150 | return err |
| 151 | } |
| 152 | return decodeJSONContent(jsonBytes, target, true) |
| 153 | } |
| 154 |
| 155 | func decodeJSONContent(content []byte, target any, strict bool) error { |
| 156 | if clientCfg, ok := target.(*v1.ClientConfig); ok { |
| 157 | decoded, err := v1.DecodeClientConfigJSON(content, v1.DecodeOptions{ |
| 158 | DisallowUnknownFields: strict, |
| 159 | }) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | *clientCfg = decoded |
| 164 | return nil |
| 165 | } |
| 166 |
| 167 | return jsonx.UnmarshalWithOptions(content, target, jsonx.DecodeOptions{ |
| 168 | RejectUnknownMembers: strict, |
| 169 | }) |
| 170 | } |
| 171 |
| 172 | // LoadConfigure loads configuration from bytes and unmarshal into c. |
| 173 | // Now it supports json, yaml and toml format. |
| 174 | // An optional format hint (e.g. "toml", "yaml", "json") can be provided |
| 175 | // to enable better error messages with line number information. |
| 176 | func LoadConfigure(b []byte, c any, strict bool, formats ...string) error { |
| 177 | format := "" |
| 178 | if len(formats) > 0 { |
| 179 | format = formats[0] |
| 180 | } |
| 181 |
| 182 | originalBytes := b |
| 183 | parsedFromTOML := false |
| 184 |
| 185 | var tomlObj any |
| 186 | tomlErr := toml.Unmarshal(b, &tomlObj) |
| 187 | if tomlErr == nil { |
| 188 | parsedFromTOML = true |
| 189 | var err error |
| 190 | b, err = jsonx.Marshal(&tomlObj) |
| 191 | if err != nil { |
| 192 | return err |
| 193 | } |
| 194 | } else if format == "toml" { |
| 195 | // File is known to be TOML but has syntax errors. |
| 196 | return formatTOMLError(tomlErr) |
| 197 | } |
| 198 |
| 199 | // If the buffer smells like JSON (first non-whitespace character is '{'), unmarshal as JSON directly. |
| 200 | if yaml.IsJSONBuffer(b) { |
| 201 | if err := decodeJSONContent(b, c, strict); err != nil { |
| 202 | return enhanceDecodeError(err, originalBytes, !parsedFromTOML) |
| 203 | } |
| 204 | return nil |
| 205 | } |
| 206 |
| 207 | // Handle YAML content |
| 208 | if strict { |
| 209 | // In strict mode, always use our custom handler to support YAML merge |
| 210 | if err := parseYAMLWithDotFieldsHandling(b, c); err != nil { |
| 211 | return enhanceDecodeError(err, originalBytes, !parsedFromTOML) |
| 212 | } |
| 213 | return nil |
| 214 | } |
| 215 | // Non-strict mode, parse normally |
| 216 | return yaml.Unmarshal(b, c) |
| 217 | } |
| 218 |
| 219 | // formatTOMLError extracts line/column information from TOML decode errors. |
| 220 | func formatTOMLError(err error) error { |
| 221 | var decErr *toml.DecodeError |
| 222 | if errors.As(err, &decErr) { |
| 223 | row, col := decErr.Position() |
| 224 | return fmt.Errorf("toml: line %d, column %d: %s", row, col, decErr.Error()) |
| 225 | } |
| 226 | var strictErr *toml.StrictMissingError |
| 227 | if errors.As(err, &strictErr) { |
| 228 | return strictErr |
| 229 | } |
| 230 | return err |
| 231 | } |
| 232 |
| 233 | // enhanceDecodeError tries to add field path and line number information to JSON/YAML decode errors. |
| 234 | func enhanceDecodeError(err error, originalContent []byte, includeLine bool) error { |
| 235 | var typeErr *json.UnmarshalTypeError |
| 236 | if errors.As(err, &typeErr) && typeErr.Field != "" { |
| 237 | if includeLine { |
| 238 | line := findFieldLineInContent(originalContent, typeErr.Field) |
| 239 | if line > 0 { |
| 240 | return fmt.Errorf("line %d: field \"%s\": cannot unmarshal %s into %s", line, typeErr.Field, typeErr.Value, typeErr.Type) |
| 241 | } |
| 242 | } |
| 243 | return fmt.Errorf("field \"%s\": cannot unmarshal %s into %s", typeErr.Field, typeErr.Value, typeErr.Type) |
| 244 | } |
| 245 | return err |
| 246 | } |
| 247 |
| 248 | // findFieldLineInContent searches the original config content for a field name |
| 249 | // and returns the 1-indexed line number where it appears, or 0 if not found. |
| 250 | func findFieldLineInContent(content []byte, fieldPath string) int { |
| 251 | if fieldPath == "" { |
| 252 | return 0 |
| 253 | } |
| 254 |
| 255 | // Use the last component of the field path (e.g. "proxies" from "proxies" or |
| 256 | // "protocol" from "transport.protocol"). |
| 257 | parts := strings.Split(fieldPath, ".") |
| 258 | searchKey := parts[len(parts)-1] |
| 259 |
| 260 | lines := bytes.Split(content, []byte("\n")) |
| 261 | for i, line := range lines { |
| 262 | trimmed := bytes.TrimSpace(line) |
| 263 | // Match TOML key assignments like: key = ... |
| 264 | if bytes.HasPrefix(trimmed, []byte(searchKey)) { |
| 265 | rest := bytes.TrimSpace(trimmed[len(searchKey):]) |
| 266 | if len(rest) > 0 && rest[0] == '=' { |
| 267 | return i + 1 |
| 268 | } |
| 269 | } |
| 270 | // Match TOML table array headers like: [[proxies]] |
| 271 | if bytes.Contains(trimmed, []byte("[["+searchKey+"]]")) { |
| 272 | return i + 1 |
| 273 | } |
| 274 | } |
| 275 | return 0 |
| 276 | } |
| 277 |
| 278 | func NewProxyConfigurerFromMsg(m *msg.NewProxy, serverCfg *v1.ServerConfig) (v1.ProxyConfigurer, error) { |
| 279 | m.ProxyType = util.EmptyOr(m.ProxyType, string(v1.ProxyTypeTCP)) |
| 280 |
| 281 | configurer := v1.NewProxyConfigurerByType(v1.ProxyType(m.ProxyType)) |
| 282 | if configurer == nil { |
| 283 | return nil, fmt.Errorf("unknown proxy type: %s", m.ProxyType) |
| 284 | } |
| 285 |
| 286 | configurer.UnmarshalFromMsg(m) |
| 287 | configurer.Complete() |
| 288 |
| 289 | if err := validation.ValidateProxyConfigurerForServer(configurer, serverCfg); err != nil { |
| 290 | return nil, err |
| 291 | } |
| 292 | return configurer, nil |
| 293 | } |
| 294 |
| 295 | func LoadServerConfig(path string, strict bool) (*v1.ServerConfig, bool, error) { |
| 296 | var ( |
| 297 | svrCfg *v1.ServerConfig |
| 298 | isLegacyFormat bool |
| 299 | ) |
| 300 | // detect legacy ini format |
| 301 | if DetectLegacyINIFormatFromFile(path) { |
| 302 | content, err := legacy.GetRenderedConfFromFile(path) |
| 303 | if err != nil { |
| 304 | return nil, true, err |
| 305 | } |
| 306 | legacyCfg, err := legacy.UnmarshalServerConfFromIni(content) |
| 307 | if err != nil { |
| 308 | return nil, true, err |
| 309 | } |
| 310 | svrCfg = legacy.Convert_ServerCommonConf_To_v1(&legacyCfg) |
| 311 | isLegacyFormat = true |
| 312 | } else { |
| 313 | svrCfg = &v1.ServerConfig{} |
| 314 | if err := LoadConfigureFromFile(path, svrCfg, strict); err != nil { |
| 315 | return nil, false, err |
| 316 | } |
| 317 | } |
| 318 | if svrCfg != nil { |
| 319 | if err := svrCfg.Complete(); err != nil { |
| 320 | return nil, isLegacyFormat, err |
| 321 | } |
| 322 | } |
| 323 | return svrCfg, isLegacyFormat, nil |
| 324 | } |
| 325 |
| 326 | // ClientConfigLoadResult contains the result of loading a client configuration file. |
| 327 | type ClientConfigLoadResult struct { |
| 328 | // Common contains the common client configuration. |
| 329 | Common *v1.ClientCommonConfig |
| 330 |
| 331 | // Proxies contains proxy configurations from inline [[proxies]] and includeConfigFiles. |
| 332 | // These are NOT completed (user prefix not added). |
| 333 | Proxies []v1.ProxyConfigurer |
| 334 |
| 335 | // Visitors contains visitor configurations from inline [[visitors]] and includeConfigFiles. |
| 336 | // These are NOT completed. |
| 337 | Visitors []v1.VisitorConfigurer |
| 338 |
| 339 | // IsLegacyFormat indicates whether the config file is in legacy INI format. |
| 340 | IsLegacyFormat bool |
| 341 | } |
| 342 |
| 343 | // LoadClientConfigResult loads and parses a client configuration file. |
| 344 | // It returns the raw configuration without completing proxies/visitors. |
| 345 | // The caller should call Complete on the configs manually for legacy behavior. |
| 346 | func LoadClientConfigResult(path string, strict bool) (*ClientConfigLoadResult, error) { |
| 347 | result := &ClientConfigLoadResult{ |
| 348 | Proxies: make([]v1.ProxyConfigurer, 0), |
| 349 | Visitors: make([]v1.VisitorConfigurer, 0), |
| 350 | } |
| 351 |
| 352 | if DetectLegacyINIFormatFromFile(path) { |
| 353 | legacyCommon, legacyProxyCfgs, legacyVisitorCfgs, err := legacy.ParseClientConfig(path) |
| 354 | if err != nil { |
| 355 | return nil, err |
| 356 | } |
| 357 | result.Common = legacy.Convert_ClientCommonConf_To_v1(&legacyCommon) |
| 358 | for _, c := range legacyProxyCfgs { |
| 359 | result.Proxies = append(result.Proxies, legacy.Convert_ProxyConf_To_v1(c)) |
| 360 | } |
| 361 | for _, c := range legacyVisitorCfgs { |
| 362 | result.Visitors = append(result.Visitors, legacy.Convert_VisitorConf_To_v1(c)) |
| 363 | } |
| 364 | result.IsLegacyFormat = true |
| 365 | } else { |
| 366 | allCfg := v1.ClientConfig{} |
| 367 | if err := LoadConfigureFromFile(path, &allCfg, strict); err != nil { |
| 368 | return nil, err |
| 369 | } |
| 370 | result.Common = &allCfg.ClientCommonConfig |
| 371 | for _, c := range allCfg.Proxies { |
| 372 | result.Proxies = append(result.Proxies, c.ProxyConfigurer) |
| 373 | } |
| 374 | for _, c := range allCfg.Visitors { |
| 375 | result.Visitors = append(result.Visitors, c.VisitorConfigurer) |
| 376 | } |
| 377 | } |
| 378 |
| 379 | // Load additional config from includes. |
| 380 | // legacy ini format already handle this in ParseClientConfig. |
| 381 | if len(result.Common.IncludeConfigFiles) > 0 && !result.IsLegacyFormat { |
| 382 | extProxyCfgs, extVisitorCfgs, err := LoadAdditionalClientConfigs(result.Common.IncludeConfigFiles, result.IsLegacyFormat, strict) |
| 383 | if err != nil { |
| 384 | return nil, err |
| 385 | } |
| 386 | result.Proxies = append(result.Proxies, extProxyCfgs...) |
| 387 | result.Visitors = append(result.Visitors, extVisitorCfgs...) |
| 388 | } |
| 389 |
| 390 | // Complete the common config |
| 391 | if result.Common != nil { |
| 392 | if err := result.Common.Complete(); err != nil { |
| 393 | return nil, err |
| 394 | } |
| 395 | } |
| 396 |
| 397 | if err := validateNoDuplicateNames(result.Proxies, result.Visitors); err != nil { |
| 398 | return nil, err |
| 399 | } |
| 400 |
| 401 | return result, nil |
| 402 | } |
| 403 |
| 404 | func LoadClientConfig(path string, strict bool) ( |
| 405 | *v1.ClientCommonConfig, |
| 406 | []v1.ProxyConfigurer, |
| 407 | []v1.VisitorConfigurer, |
| 408 | bool, error, |
| 409 | ) { |
| 410 | result, err := LoadClientConfigResult(path, strict) |
| 411 | if err != nil { |
| 412 | return nil, nil, nil, result != nil && result.IsLegacyFormat, err |
| 413 | } |
| 414 |
| 415 | proxyCfgs := result.Proxies |
| 416 | visitorCfgs := result.Visitors |
| 417 |
| 418 | proxyCfgs, visitorCfgs = FilterClientConfigurers(result.Common, proxyCfgs, visitorCfgs) |
| 419 | proxyCfgs = CompleteProxyConfigurers(proxyCfgs) |
| 420 | visitorCfgs = CompleteVisitorConfigurers(visitorCfgs) |
| 421 | return result.Common, proxyCfgs, visitorCfgs, result.IsLegacyFormat, nil |
| 422 | } |
| 423 |
| 424 | // validateNoDuplicateNames rejects proxies or visitors that share a name. They are |
| 425 | // keyed by name in the config sources, so a duplicate would otherwise be silently |
| 426 | // overwritten and never started, with no error or log. |
| 427 | func validateNoDuplicateNames(proxies []v1.ProxyConfigurer, visitors []v1.VisitorConfigurer) error { |
| 428 | proxyNames := make(map[string]struct{}, len(proxies)) |
| 429 | for _, p := range proxies { |
| 430 | name := p.GetBaseConfig().Name |
| 431 | if _, ok := proxyNames[name]; ok { |
| 432 | return fmt.Errorf("proxy name [%s] is duplicated", name) |
| 433 | } |
| 434 | proxyNames[name] = struct{}{} |
| 435 | } |
| 436 |
| 437 | visitorNames := make(map[string]struct{}, len(visitors)) |
| 438 | for _, v := range visitors { |
| 439 | name := v.GetBaseConfig().Name |
| 440 | if _, ok := visitorNames[name]; ok { |
| 441 | return fmt.Errorf("visitor name [%s] is duplicated", name) |
| 442 | } |
| 443 | visitorNames[name] = struct{}{} |
| 444 | } |
| 445 |
| 446 | return nil |
| 447 | } |
| 448 |
| 449 | func CompleteProxyConfigurers(proxies []v1.ProxyConfigurer) []v1.ProxyConfigurer { |
| 450 | proxyCfgs := proxies |
| 451 | for _, c := range proxyCfgs { |
| 452 | c.Complete() |
| 453 | } |
| 454 | return proxyCfgs |
| 455 | } |
| 456 |
| 457 | func CompleteVisitorConfigurers(visitors []v1.VisitorConfigurer) []v1.VisitorConfigurer { |
| 458 | visitorCfgs := visitors |
| 459 | for _, c := range visitorCfgs { |
| 460 | c.Complete() |
| 461 | } |
| 462 | return visitorCfgs |
| 463 | } |
| 464 |
| 465 | func FilterClientConfigurers( |
| 466 | common *v1.ClientCommonConfig, |
| 467 | proxies []v1.ProxyConfigurer, |
| 468 | visitors []v1.VisitorConfigurer, |
| 469 | ) ([]v1.ProxyConfigurer, []v1.VisitorConfigurer) { |
| 470 | if common == nil { |
| 471 | common = &v1.ClientCommonConfig{} |
| 472 | } |
| 473 |
| 474 | proxyCfgs := proxies |
| 475 | visitorCfgs := visitors |
| 476 |
| 477 | // Filter by start across merged configurers from all sources. |
| 478 | // For example, store entries are also filtered by this set. |
| 479 | if len(common.Start) > 0 { |
| 480 | startSet := sets.New(common.Start...) |
| 481 | proxyCfgs = lo.Filter(proxyCfgs, func(c v1.ProxyConfigurer, _ int) bool { |
| 482 | return startSet.Has(c.GetBaseConfig().Name) |
| 483 | }) |
| 484 | visitorCfgs = lo.Filter(visitorCfgs, func(c v1.VisitorConfigurer, _ int) bool { |
| 485 | return startSet.Has(c.GetBaseConfig().Name) |
| 486 | }) |
| 487 | } |
| 488 |
| 489 | // Filter by enabled field in each proxy |
| 490 | // nil or true means enabled, false means disabled |
| 491 | proxyCfgs = lo.Filter(proxyCfgs, func(c v1.ProxyConfigurer, _ int) bool { |
| 492 | enabled := c.GetBaseConfig().Enabled |
| 493 | return enabled == nil || *enabled |
| 494 | }) |
| 495 | visitorCfgs = lo.Filter(visitorCfgs, func(c v1.VisitorConfigurer, _ int) bool { |
| 496 | enabled := c.GetBaseConfig().Enabled |
| 497 | return enabled == nil || *enabled |
| 498 | }) |
| 499 | return proxyCfgs, visitorCfgs |
| 500 | } |
| 501 |
| 502 | func LoadAdditionalClientConfigs(paths []string, isLegacyFormat bool, strict bool) ([]v1.ProxyConfigurer, []v1.VisitorConfigurer, error) { |
| 503 | proxyCfgs := make([]v1.ProxyConfigurer, 0) |
| 504 | visitorCfgs := make([]v1.VisitorConfigurer, 0) |
| 505 | for _, path := range paths { |
| 506 | absDir, err := filepath.Abs(filepath.Dir(path)) |
| 507 | if err != nil { |
| 508 | return nil, nil, err |
| 509 | } |
| 510 | if _, err := os.Stat(absDir); os.IsNotExist(err) { |
| 511 | return nil, nil, err |
| 512 | } |
| 513 | files, err := os.ReadDir(absDir) |
| 514 | if err != nil { |
| 515 | return nil, nil, err |
| 516 | } |
| 517 | for _, fi := range files { |
| 518 | if fi.IsDir() { |
| 519 | continue |
| 520 | } |
| 521 | absFile := filepath.Join(absDir, fi.Name()) |
| 522 | if matched, _ := filepath.Match(filepath.Join(absDir, filepath.Base(path)), absFile); matched { |
| 523 | // support yaml/json/toml |
| 524 | cfg := v1.ClientConfig{} |
| 525 | if err := LoadConfigureFromFile(absFile, &cfg, strict); err != nil { |
| 526 | return nil, nil, fmt.Errorf("load additional config from %s error: %v", absFile, err) |
| 527 | } |
| 528 | for _, c := range cfg.Proxies { |
| 529 | proxyCfgs = append(proxyCfgs, c.ProxyConfigurer) |
| 530 | } |
| 531 | for _, c := range cfg.Visitors { |
| 532 | visitorCfgs = append(visitorCfgs, c.VisitorConfigurer) |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | } |
| 537 | return proxyCfgs, visitorCfgs, nil |
| 538 | } |