load.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "html/template"
  20. "os"
  21. "path/filepath"
  22. "strings"
  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. // LoadConfigure loads configuration from bytes and unmarshal into c.
  100. // Now it supports json, yaml and toml format.
  101. func LoadConfigure(b []byte, c any, strict bool) error {
  102. v1.DisallowUnknownFieldsMu.Lock()
  103. defer v1.DisallowUnknownFieldsMu.Unlock()
  104. v1.DisallowUnknownFields = strict
  105. var tomlObj interface{}
  106. // Try to unmarshal as TOML first; swallow errors from that (assume it's not valid TOML).
  107. if err := toml.Unmarshal(b, &tomlObj); err == nil {
  108. b, err = json.Marshal(&tomlObj)
  109. if err != nil {
  110. return err
  111. }
  112. }
  113. // If the buffer smells like JSON (first non-whitespace character is '{'), unmarshal as JSON directly.
  114. if yaml.IsJSONBuffer(b) {
  115. decoder := json.NewDecoder(bytes.NewBuffer(b))
  116. if strict {
  117. decoder.DisallowUnknownFields()
  118. }
  119. return decoder.Decode(c)
  120. }
  121. // It wasn't JSON. Unmarshal as YAML.
  122. if strict {
  123. return yaml.UnmarshalStrict(b, c)
  124. }
  125. return yaml.Unmarshal(b, c)
  126. }
  127. func NewProxyConfigurerFromMsg(m *msg.NewProxy, serverCfg *v1.ServerConfig) (v1.ProxyConfigurer, error) {
  128. m.ProxyType = util.EmptyOr(m.ProxyType, string(v1.ProxyTypeTCP))
  129. configurer := v1.NewProxyConfigurerByType(v1.ProxyType(m.ProxyType))
  130. if configurer == nil {
  131. return nil, fmt.Errorf("unknown proxy type: %s", m.ProxyType)
  132. }
  133. configurer.UnmarshalFromMsg(m)
  134. configurer.Complete("")
  135. if err := validation.ValidateProxyConfigurerForServer(configurer, serverCfg); err != nil {
  136. return nil, err
  137. }
  138. return configurer, nil
  139. }
  140. func LoadServerConfig(path string, strict bool) (*v1.ServerConfig, bool, error) {
  141. var (
  142. svrCfg *v1.ServerConfig
  143. isLegacyFormat bool
  144. )
  145. // detect legacy ini format
  146. if DetectLegacyINIFormatFromFile(path) {
  147. content, err := legacy.GetRenderedConfFromFile(path)
  148. if err != nil {
  149. return nil, true, err
  150. }
  151. legacyCfg, err := legacy.UnmarshalServerConfFromIni(content)
  152. if err != nil {
  153. return nil, true, err
  154. }
  155. svrCfg = legacy.Convert_ServerCommonConf_To_v1(&legacyCfg)
  156. isLegacyFormat = true
  157. } else {
  158. svrCfg = &v1.ServerConfig{}
  159. if err := LoadConfigureFromFile(path, svrCfg, strict); err != nil {
  160. return nil, false, err
  161. }
  162. }
  163. if svrCfg != nil {
  164. svrCfg.Complete()
  165. }
  166. return svrCfg, isLegacyFormat, nil
  167. }
  168. func LoadClientConfig(path string, strict bool) (
  169. *v1.ClientCommonConfig,
  170. []v1.ProxyConfigurer,
  171. []v1.VisitorConfigurer,
  172. bool, error,
  173. ) {
  174. var (
  175. cliCfg *v1.ClientCommonConfig
  176. proxyCfgs = make([]v1.ProxyConfigurer, 0)
  177. visitorCfgs = make([]v1.VisitorConfigurer, 0)
  178. isLegacyFormat bool
  179. )
  180. if DetectLegacyINIFormatFromFile(path) {
  181. legacyCommon, legacyProxyCfgs, legacyVisitorCfgs, err := legacy.ParseClientConfig(path)
  182. if err != nil {
  183. return nil, nil, nil, true, err
  184. }
  185. cliCfg = legacy.Convert_ClientCommonConf_To_v1(&legacyCommon)
  186. for _, c := range legacyProxyCfgs {
  187. proxyCfgs = append(proxyCfgs, legacy.Convert_ProxyConf_To_v1(c))
  188. }
  189. for _, c := range legacyVisitorCfgs {
  190. visitorCfgs = append(visitorCfgs, legacy.Convert_VisitorConf_To_v1(c))
  191. }
  192. isLegacyFormat = true
  193. } else {
  194. allCfg := v1.ClientConfig{}
  195. if err := LoadConfigureFromFile(path, &allCfg, strict); err != nil {
  196. return nil, nil, nil, false, err
  197. }
  198. cliCfg = &allCfg.ClientCommonConfig
  199. for _, c := range allCfg.Proxies {
  200. proxyCfgs = append(proxyCfgs, c.ProxyConfigurer)
  201. }
  202. for _, c := range allCfg.Visitors {
  203. visitorCfgs = append(visitorCfgs, c.VisitorConfigurer)
  204. }
  205. }
  206. // Load additional config from includes.
  207. // legacy ini format already handle this in ParseClientConfig.
  208. if len(cliCfg.IncludeConfigFiles) > 0 && !isLegacyFormat {
  209. extProxyCfgs, extVisitorCfgs, err := LoadAdditionalClientConfigs(cliCfg.IncludeConfigFiles, isLegacyFormat, strict)
  210. if err != nil {
  211. return nil, nil, nil, isLegacyFormat, err
  212. }
  213. proxyCfgs = append(proxyCfgs, extProxyCfgs...)
  214. visitorCfgs = append(visitorCfgs, extVisitorCfgs...)
  215. }
  216. // Filter by start
  217. if len(cliCfg.Start) > 0 {
  218. startSet := sets.New(cliCfg.Start...)
  219. proxyCfgs = lo.Filter(proxyCfgs, func(c v1.ProxyConfigurer, _ int) bool {
  220. return startSet.Has(c.GetBaseConfig().Name)
  221. })
  222. visitorCfgs = lo.Filter(visitorCfgs, func(c v1.VisitorConfigurer, _ int) bool {
  223. return startSet.Has(c.GetBaseConfig().Name)
  224. })
  225. }
  226. if cliCfg != nil {
  227. cliCfg.Complete()
  228. }
  229. for _, c := range proxyCfgs {
  230. c.Complete(cliCfg.User)
  231. }
  232. for _, c := range visitorCfgs {
  233. c.Complete(cliCfg)
  234. }
  235. return cliCfg, proxyCfgs, visitorCfgs, isLegacyFormat, nil
  236. }
  237. func LoadAdditionalClientConfigs(paths []string, isLegacyFormat bool, strict bool) ([]v1.ProxyConfigurer, []v1.VisitorConfigurer, error) {
  238. proxyCfgs := make([]v1.ProxyConfigurer, 0)
  239. visitorCfgs := make([]v1.VisitorConfigurer, 0)
  240. for _, path := range paths {
  241. absDir, err := filepath.Abs(filepath.Dir(path))
  242. if err != nil {
  243. return nil, nil, err
  244. }
  245. if _, err := os.Stat(absDir); os.IsNotExist(err) {
  246. return nil, nil, err
  247. }
  248. files, err := os.ReadDir(absDir)
  249. if err != nil {
  250. return nil, nil, err
  251. }
  252. for _, fi := range files {
  253. if fi.IsDir() {
  254. continue
  255. }
  256. absFile := filepath.Join(absDir, fi.Name())
  257. if matched, _ := filepath.Match(filepath.Join(absDir, filepath.Base(path)), absFile); matched {
  258. // support yaml/json/toml
  259. cfg := v1.ClientConfig{}
  260. if err := LoadConfigureFromFile(absFile, &cfg, strict); err != nil {
  261. return nil, nil, fmt.Errorf("load additional config from %s error: %v", absFile, err)
  262. }
  263. for _, c := range cfg.Proxies {
  264. proxyCfgs = append(proxyCfgs, c.ProxyConfigurer)
  265. }
  266. for _, c := range cfg.Visitors {
  267. visitorCfgs = append(visitorCfgs, c.VisitorConfigurer)
  268. }
  269. }
  270. }
  271. }
  272. return proxyCfgs, visitorCfgs, nil
  273. }