load.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 config
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "os"
  20. "path/filepath"
  21. "strings"
  22. "text/template"
  23. toml "github.com/pelletier/go-toml/v2"
  24. "github.com/samber/lo"
  25. "gopkg.in/ini.v1"
  26. "k8s.io/apimachinery/pkg/util/sets"
  27. "k8s.io/apimachinery/pkg/util/yaml"
  28. "github.com/fatedier/frp/pkg/config/legacy"
  29. v1 "github.com/fatedier/frp/pkg/config/v1"
  30. "github.com/fatedier/frp/pkg/config/v1/validation"
  31. "github.com/fatedier/frp/pkg/msg"
  32. "github.com/fatedier/frp/pkg/util/util"
  33. )
  34. var glbEnvs map[string]string
  35. func init() {
  36. glbEnvs = make(map[string]string)
  37. envs := os.Environ()
  38. for _, env := range envs {
  39. pair := strings.SplitN(env, "=", 2)
  40. if len(pair) != 2 {
  41. continue
  42. }
  43. glbEnvs[pair[0]] = pair[1]
  44. }
  45. }
  46. type Values struct {
  47. Envs map[string]string // environment vars
  48. }
  49. func GetValues() *Values {
  50. return &Values{
  51. Envs: glbEnvs,
  52. }
  53. }
  54. func DetectLegacyINIFormat(content []byte) bool {
  55. f, err := ini.Load(content)
  56. if err != nil {
  57. return false
  58. }
  59. if _, err := f.GetSection("common"); err == nil {
  60. return true
  61. }
  62. return false
  63. }
  64. func DetectLegacyINIFormatFromFile(path string) bool {
  65. b, err := os.ReadFile(path)
  66. if err != nil {
  67. return false
  68. }
  69. return DetectLegacyINIFormat(b)
  70. }
  71. func RenderWithTemplate(in []byte, values *Values) ([]byte, error) {
  72. tmpl, err := template.New("frp").Funcs(template.FuncMap{
  73. "parseNumberRange": parseNumberRange,
  74. "parseNumberRangePair": parseNumberRangePair,
  75. }).Parse(string(in))
  76. if err != nil {
  77. return nil, err
  78. }
  79. buffer := bytes.NewBufferString("")
  80. if err := tmpl.Execute(buffer, values); err != nil {
  81. return nil, err
  82. }
  83. return buffer.Bytes(), nil
  84. }
  85. func LoadFileContentWithTemplate(path string, values *Values) ([]byte, error) {
  86. b, err := os.ReadFile(path)
  87. if err != nil {
  88. return nil, err
  89. }
  90. return RenderWithTemplate(b, values)
  91. }
  92. func LoadConfigureFromFile(path string, c any, strict bool) error {
  93. content, err := LoadFileContentWithTemplate(path, GetValues())
  94. if err != nil {
  95. return err
  96. }
  97. return LoadConfigure(content, c, strict)
  98. }
  99. // parseYAMLWithDotFieldsHandling parses YAML with dot-prefixed fields handling
  100. // This function handles both cases efficiently: with or without dot fields
  101. func parseYAMLWithDotFieldsHandling(content []byte, target any) error {
  102. var temp any
  103. if err := yaml.Unmarshal(content, &temp); err != nil {
  104. return err
  105. }
  106. // Remove dot fields if it's a map
  107. if tempMap, ok := temp.(map[string]any); ok {
  108. for key := range tempMap {
  109. if strings.HasPrefix(key, ".") {
  110. delete(tempMap, key)
  111. }
  112. }
  113. }
  114. // Convert to JSON and decode with strict validation
  115. jsonBytes, err := json.Marshal(temp)
  116. if err != nil {
  117. return err
  118. }
  119. decoder := json.NewDecoder(bytes.NewReader(jsonBytes))
  120. decoder.DisallowUnknownFields()
  121. return decoder.Decode(target)
  122. }
  123. // LoadConfigure loads configuration from bytes and unmarshal into c.
  124. // Now it supports json, yaml and toml format.
  125. func LoadConfigure(b []byte, c any, strict bool) error {
  126. v1.DisallowUnknownFieldsMu.Lock()
  127. defer v1.DisallowUnknownFieldsMu.Unlock()
  128. v1.DisallowUnknownFields = strict
  129. var tomlObj any
  130. // Try to unmarshal as TOML first; swallow errors from that (assume it's not valid TOML).
  131. if err := toml.Unmarshal(b, &tomlObj); err == nil {
  132. b, err = json.Marshal(&tomlObj)
  133. if err != nil {
  134. return err
  135. }
  136. }
  137. // If the buffer smells like JSON (first non-whitespace character is '{'), unmarshal as JSON directly.
  138. if yaml.IsJSONBuffer(b) {
  139. decoder := json.NewDecoder(bytes.NewBuffer(b))
  140. if strict {
  141. decoder.DisallowUnknownFields()
  142. }
  143. return decoder.Decode(c)
  144. }
  145. // Handle YAML content
  146. if strict {
  147. // In strict mode, always use our custom handler to support YAML merge
  148. return parseYAMLWithDotFieldsHandling(b, c)
  149. }
  150. // Non-strict mode, parse normally
  151. return yaml.Unmarshal(b, c)
  152. }
  153. func NewProxyConfigurerFromMsg(m *msg.NewProxy, serverCfg *v1.ServerConfig) (v1.ProxyConfigurer, error) {
  154. m.ProxyType = util.EmptyOr(m.ProxyType, string(v1.ProxyTypeTCP))
  155. configurer := v1.NewProxyConfigurerByType(v1.ProxyType(m.ProxyType))
  156. if configurer == nil {
  157. return nil, fmt.Errorf("unknown proxy type: %s", m.ProxyType)
  158. }
  159. configurer.UnmarshalFromMsg(m)
  160. configurer.Complete("")
  161. if err := validation.ValidateProxyConfigurerForServer(configurer, serverCfg); err != nil {
  162. return nil, err
  163. }
  164. return configurer, nil
  165. }
  166. func LoadServerConfig(path string, strict bool) (*v1.ServerConfig, bool, error) {
  167. var (
  168. svrCfg *v1.ServerConfig
  169. isLegacyFormat bool
  170. )
  171. // detect legacy ini format
  172. if DetectLegacyINIFormatFromFile(path) {
  173. content, err := legacy.GetRenderedConfFromFile(path)
  174. if err != nil {
  175. return nil, true, err
  176. }
  177. legacyCfg, err := legacy.UnmarshalServerConfFromIni(content)
  178. if err != nil {
  179. return nil, true, err
  180. }
  181. svrCfg = legacy.Convert_ServerCommonConf_To_v1(&legacyCfg)
  182. isLegacyFormat = true
  183. } else {
  184. svrCfg = &v1.ServerConfig{}
  185. if err := LoadConfigureFromFile(path, svrCfg, strict); err != nil {
  186. return nil, false, err
  187. }
  188. }
  189. if svrCfg != nil {
  190. svrCfg.Complete()
  191. }
  192. return svrCfg, isLegacyFormat, nil
  193. }
  194. func LoadClientConfig(path string, strict bool) (
  195. *v1.ClientCommonConfig,
  196. []v1.ProxyConfigurer,
  197. []v1.VisitorConfigurer,
  198. bool, error,
  199. ) {
  200. var (
  201. cliCfg *v1.ClientCommonConfig
  202. proxyCfgs = make([]v1.ProxyConfigurer, 0)
  203. visitorCfgs = make([]v1.VisitorConfigurer, 0)
  204. isLegacyFormat bool
  205. )
  206. if DetectLegacyINIFormatFromFile(path) {
  207. legacyCommon, legacyProxyCfgs, legacyVisitorCfgs, err := legacy.ParseClientConfig(path)
  208. if err != nil {
  209. return nil, nil, nil, true, err
  210. }
  211. cliCfg = legacy.Convert_ClientCommonConf_To_v1(&legacyCommon)
  212. for _, c := range legacyProxyCfgs {
  213. proxyCfgs = append(proxyCfgs, legacy.Convert_ProxyConf_To_v1(c))
  214. }
  215. for _, c := range legacyVisitorCfgs {
  216. visitorCfgs = append(visitorCfgs, legacy.Convert_VisitorConf_To_v1(c))
  217. }
  218. isLegacyFormat = true
  219. } else {
  220. allCfg := v1.ClientConfig{}
  221. if err := LoadConfigureFromFile(path, &allCfg, strict); err != nil {
  222. return nil, nil, nil, false, err
  223. }
  224. cliCfg = &allCfg.ClientCommonConfig
  225. for _, c := range allCfg.Proxies {
  226. proxyCfgs = append(proxyCfgs, c.ProxyConfigurer)
  227. }
  228. for _, c := range allCfg.Visitors {
  229. visitorCfgs = append(visitorCfgs, c.VisitorConfigurer)
  230. }
  231. }
  232. // Load additional config from includes.
  233. // legacy ini format already handle this in ParseClientConfig.
  234. if len(cliCfg.IncludeConfigFiles) > 0 && !isLegacyFormat {
  235. extProxyCfgs, extVisitorCfgs, err := LoadAdditionalClientConfigs(cliCfg.IncludeConfigFiles, isLegacyFormat, strict)
  236. if err != nil {
  237. return nil, nil, nil, isLegacyFormat, err
  238. }
  239. proxyCfgs = append(proxyCfgs, extProxyCfgs...)
  240. visitorCfgs = append(visitorCfgs, extVisitorCfgs...)
  241. }
  242. // Filter by start
  243. if len(cliCfg.Start) > 0 {
  244. startSet := sets.New(cliCfg.Start...)
  245. proxyCfgs = lo.Filter(proxyCfgs, func(c v1.ProxyConfigurer, _ int) bool {
  246. return startSet.Has(c.GetBaseConfig().Name)
  247. })
  248. visitorCfgs = lo.Filter(visitorCfgs, func(c v1.VisitorConfigurer, _ int) bool {
  249. return startSet.Has(c.GetBaseConfig().Name)
  250. })
  251. }
  252. if cliCfg != nil {
  253. cliCfg.Complete()
  254. }
  255. for _, c := range proxyCfgs {
  256. c.Complete(cliCfg.User)
  257. }
  258. for _, c := range visitorCfgs {
  259. c.Complete(cliCfg)
  260. }
  261. return cliCfg, proxyCfgs, visitorCfgs, isLegacyFormat, nil
  262. }
  263. func LoadAdditionalClientConfigs(paths []string, isLegacyFormat bool, strict bool) ([]v1.ProxyConfigurer, []v1.VisitorConfigurer, error) {
  264. proxyCfgs := make([]v1.ProxyConfigurer, 0)
  265. visitorCfgs := make([]v1.VisitorConfigurer, 0)
  266. for _, path := range paths {
  267. absDir, err := filepath.Abs(filepath.Dir(path))
  268. if err != nil {
  269. return nil, nil, err
  270. }
  271. if _, err := os.Stat(absDir); os.IsNotExist(err) {
  272. return nil, nil, err
  273. }
  274. files, err := os.ReadDir(absDir)
  275. if err != nil {
  276. return nil, nil, err
  277. }
  278. for _, fi := range files {
  279. if fi.IsDir() {
  280. continue
  281. }
  282. absFile := filepath.Join(absDir, fi.Name())
  283. if matched, _ := filepath.Match(filepath.Join(absDir, filepath.Base(path)), absFile); matched {
  284. // support yaml/json/toml
  285. cfg := v1.ClientConfig{}
  286. if err := LoadConfigureFromFile(absFile, &cfg, strict); err != nil {
  287. return nil, nil, fmt.Errorf("load additional config from %s error: %v", absFile, err)
  288. }
  289. for _, c := range cfg.Proxies {
  290. proxyCfgs = append(proxyCfgs, c.ProxyConfigurer)
  291. }
  292. for _, c := range cfg.Visitors {
  293. visitorCfgs = append(visitorCfgs, c.VisitorConfigurer)
  294. }
  295. }
  296. }
  297. }
  298. return proxyCfgs, visitorCfgs, nil
  299. }