1
0

root.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // Copyright 2018 fatedier, fatedier@gmail.com
  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 sub
  15. import (
  16. "context"
  17. "fmt"
  18. "io/fs"
  19. "os"
  20. "os/signal"
  21. "path/filepath"
  22. "slices"
  23. "sync"
  24. "syscall"
  25. "time"
  26. "github.com/spf13/cobra"
  27. "github.com/fatedier/frp/client"
  28. "github.com/fatedier/frp/pkg/config"
  29. v1 "github.com/fatedier/frp/pkg/config/v1"
  30. "github.com/fatedier/frp/pkg/config/v1/validation"
  31. "github.com/fatedier/frp/pkg/featuregate"
  32. "github.com/fatedier/frp/pkg/util/log"
  33. "github.com/fatedier/frp/pkg/util/version"
  34. )
  35. type UnsafeFeature = string
  36. const (
  37. TokenSourceExec UnsafeFeature = "TokenSourceExec"
  38. )
  39. var (
  40. cfgFile string
  41. cfgDir string
  42. showVersion bool
  43. strictConfigMode bool
  44. allowUnsafe []UnsafeFeature
  45. )
  46. func init() {
  47. rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
  48. rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one frpc service for each file in config directory")
  49. rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
  50. rootCmd.PersistentFlags().BoolVarP(&strictConfigMode, "strict_config", "", true, "strict config parsing mode, unknown fields will cause an errors")
  51. rootCmd.PersistentFlags().StringSliceVarP(&allowUnsafe, "allow_unsafe", "", []string{}, "allowed unsafe features, one or more of: TokenSourceExec")
  52. }
  53. var rootCmd = &cobra.Command{
  54. Use: "frpc",
  55. Short: "frpc is the client of frp (https://github.com/fatedier/frp)",
  56. RunE: func(cmd *cobra.Command, args []string) error {
  57. if showVersion {
  58. fmt.Println(version.Full())
  59. return nil
  60. }
  61. unsafeFeatures := v1.UnsafeFeatures{TokenSourceExec: slices.Contains(allowUnsafe, TokenSourceExec)}
  62. // If cfgDir is not empty, run multiple frpc service for each config file in cfgDir.
  63. // Note that it's only designed for testing. It's not guaranteed to be stable.
  64. if cfgDir != "" {
  65. _ = runMultipleClients(cfgDir, unsafeFeatures)
  66. return nil
  67. }
  68. // Do not show command usage here.
  69. err := runClient(cfgFile, unsafeFeatures)
  70. if err != nil {
  71. fmt.Println(err)
  72. os.Exit(1)
  73. }
  74. return nil
  75. },
  76. }
  77. func runMultipleClients(cfgDir string, unsafeFeatures v1.UnsafeFeatures) error {
  78. var wg sync.WaitGroup
  79. err := filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
  80. if err != nil || d.IsDir() {
  81. return nil
  82. }
  83. wg.Add(1)
  84. time.Sleep(time.Millisecond)
  85. go func() {
  86. defer wg.Done()
  87. err := runClient(path, unsafeFeatures)
  88. if err != nil {
  89. fmt.Printf("frpc service error for config file [%s]\n", path)
  90. }
  91. }()
  92. return nil
  93. })
  94. wg.Wait()
  95. return err
  96. }
  97. func Execute() {
  98. rootCmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc)
  99. if err := rootCmd.Execute(); err != nil {
  100. os.Exit(1)
  101. }
  102. }
  103. func handleTermSignal(svr *client.Service) {
  104. ch := make(chan os.Signal, 1)
  105. signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
  106. <-ch
  107. svr.GracefulClose(500 * time.Millisecond)
  108. }
  109. func runClient(cfgFilePath string, unsafeFeatures v1.UnsafeFeatures) error {
  110. cfg, proxyCfgs, visitorCfgs, isLegacyFormat, err := config.LoadClientConfig(cfgFilePath, strictConfigMode)
  111. if err != nil {
  112. return err
  113. }
  114. if isLegacyFormat {
  115. fmt.Printf("WARNING: ini format is deprecated and the support will be removed in the future, " +
  116. "please use yaml/json/toml format instead!\n")
  117. }
  118. if len(cfg.FeatureGates) > 0 {
  119. if err := featuregate.SetFromMap(cfg.FeatureGates); err != nil {
  120. return err
  121. }
  122. }
  123. warning, err := validation.ValidateAllClientConfig(cfg, proxyCfgs, visitorCfgs, unsafeFeatures)
  124. if warning != nil {
  125. fmt.Printf("WARNING: %v\n", warning)
  126. }
  127. if err != nil {
  128. return err
  129. }
  130. return startService(cfg, proxyCfgs, visitorCfgs, unsafeFeatures, cfgFilePath)
  131. }
  132. func startService(
  133. cfg *v1.ClientCommonConfig,
  134. proxyCfgs []v1.ProxyConfigurer,
  135. visitorCfgs []v1.VisitorConfigurer,
  136. unsafeFeatures v1.UnsafeFeatures,
  137. cfgFile string,
  138. ) error {
  139. log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
  140. if cfgFile != "" {
  141. log.Infof("start frpc service for config file [%s]", cfgFile)
  142. defer log.Infof("frpc service for config file [%s] stopped", cfgFile)
  143. }
  144. svr, err := client.NewService(client.ServiceOptions{
  145. Common: cfg,
  146. ProxyCfgs: proxyCfgs,
  147. VisitorCfgs: visitorCfgs,
  148. UnsafeFeatures: unsafeFeatures,
  149. ConfigFilePath: cfgFile,
  150. })
  151. if err != nil {
  152. return err
  153. }
  154. shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic"
  155. // Capture the exit signal if we use kcp or quic.
  156. if shouldGracefulClose {
  157. go handleTermSignal(svr)
  158. }
  159. return svr.Run(context.Background())
  160. }