root.go 4.9 KB

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