root.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. "fmt"
  17. "io/fs"
  18. "net"
  19. "os"
  20. "os/signal"
  21. "path/filepath"
  22. "strconv"
  23. "sync"
  24. "syscall"
  25. "time"
  26. "github.com/spf13/cobra"
  27. "github.com/fatedier/frp/client"
  28. "github.com/fatedier/frp/pkg/auth"
  29. "github.com/fatedier/frp/pkg/config"
  30. "github.com/fatedier/frp/pkg/util/log"
  31. "github.com/fatedier/frp/pkg/util/version"
  32. )
  33. const (
  34. CfgFileTypeIni = iota
  35. CfgFileTypeCmd
  36. )
  37. var (
  38. cfgFile string
  39. cfgDir string
  40. showVersion bool
  41. serverAddr string
  42. user string
  43. protocol string
  44. token string
  45. logLevel string
  46. logFile string
  47. logMaxDays int
  48. disableLogColor bool
  49. proxyName string
  50. localIP string
  51. localPort int
  52. remotePort int
  53. useEncryption bool
  54. useCompression bool
  55. bandwidthLimit string
  56. bandwidthLimitMode string
  57. customDomains string
  58. subDomain string
  59. httpUser string
  60. httpPwd string
  61. locations string
  62. hostHeaderRewrite string
  63. role string
  64. sk string
  65. multiplexer string
  66. serverName string
  67. bindAddr string
  68. bindPort int
  69. tlsEnable bool
  70. )
  71. func init() {
  72. rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
  73. rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one frpc service for each file in config directory")
  74. rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
  75. }
  76. func RegisterCommonFlags(cmd *cobra.Command) {
  77. cmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address")
  78. cmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
  79. cmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp or kcp or websocket")
  80. cmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
  81. cmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
  82. cmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
  83. cmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
  84. cmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
  85. cmd.PersistentFlags().BoolVarP(&tlsEnable, "tls_enable", "", false, "enable frpc tls")
  86. }
  87. var rootCmd = &cobra.Command{
  88. Use: "frpc",
  89. Short: "frpc is the client of frp (https://github.com/fatedier/frp)",
  90. RunE: func(cmd *cobra.Command, args []string) error {
  91. if showVersion {
  92. fmt.Println(version.Full())
  93. return nil
  94. }
  95. // If cfgDir is not empty, run multiple frpc service for each config file in cfgDir.
  96. // Note that it's only designed for testing. It's not guaranteed to be stable.
  97. if cfgDir != "" {
  98. var wg sync.WaitGroup
  99. _ = filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
  100. if err != nil {
  101. return nil
  102. }
  103. if d.IsDir() {
  104. return nil
  105. }
  106. wg.Add(1)
  107. time.Sleep(time.Millisecond)
  108. go func() {
  109. defer wg.Done()
  110. err := runClient(path)
  111. if err != nil {
  112. fmt.Printf("frpc service error for config file [%s]\n", path)
  113. }
  114. }()
  115. return nil
  116. })
  117. wg.Wait()
  118. return nil
  119. }
  120. // Do not show command usage here.
  121. err := runClient(cfgFile)
  122. if err != nil {
  123. fmt.Println(err)
  124. os.Exit(1)
  125. }
  126. return nil
  127. },
  128. }
  129. func Execute() {
  130. if err := rootCmd.Execute(); err != nil {
  131. os.Exit(1)
  132. }
  133. }
  134. func handleSignal(svr *client.Service, doneCh chan struct{}) {
  135. ch := make(chan os.Signal, 1)
  136. signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
  137. <-ch
  138. svr.GracefulClose(500 * time.Millisecond)
  139. close(doneCh)
  140. }
  141. func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
  142. cfg = config.GetDefaultClientConf()
  143. ipStr, portStr, err := net.SplitHostPort(serverAddr)
  144. if err != nil {
  145. err = fmt.Errorf("invalid server_addr: %v", err)
  146. return
  147. }
  148. cfg.ServerAddr = ipStr
  149. cfg.ServerPort, err = strconv.Atoi(portStr)
  150. if err != nil {
  151. err = fmt.Errorf("invalid server_addr: %v", err)
  152. return
  153. }
  154. cfg.User = user
  155. cfg.Protocol = protocol
  156. cfg.LogLevel = logLevel
  157. cfg.LogFile = logFile
  158. cfg.LogMaxDays = int64(logMaxDays)
  159. cfg.DisableLogColor = disableLogColor
  160. // Only token authentication is supported in cmd mode
  161. cfg.ClientConfig = auth.GetDefaultClientConf()
  162. cfg.Token = token
  163. cfg.TLSEnable = tlsEnable
  164. cfg.Complete()
  165. if err = cfg.Validate(); err != nil {
  166. err = fmt.Errorf("parse config error: %v", err)
  167. return
  168. }
  169. return
  170. }
  171. func runClient(cfgFilePath string) error {
  172. cfg, pxyCfgs, visitorCfgs, err := config.ParseClientConfig(cfgFilePath)
  173. if err != nil {
  174. return err
  175. }
  176. return startService(cfg, pxyCfgs, visitorCfgs, cfgFilePath)
  177. }
  178. func startService(
  179. cfg config.ClientCommonConf,
  180. pxyCfgs map[string]config.ProxyConf,
  181. visitorCfgs map[string]config.VisitorConf,
  182. cfgFile string,
  183. ) (err error) {
  184. log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel,
  185. cfg.LogMaxDays, cfg.DisableLogColor)
  186. if cfgFile != "" {
  187. log.Trace("start frpc service for config file [%s]", cfgFile)
  188. defer log.Trace("frpc service for config file [%s] stopped", cfgFile)
  189. }
  190. svr, errRet := client.NewService(cfg, pxyCfgs, visitorCfgs, cfgFile)
  191. if errRet != nil {
  192. err = errRet
  193. return
  194. }
  195. closedDoneCh := make(chan struct{})
  196. shouldGracefulClose := cfg.Protocol == "kcp" || cfg.Protocol == "quic"
  197. // Capture the exit signal if we use kcp or quic.
  198. if shouldGracefulClose {
  199. go handleSignal(svr, closedDoneCh)
  200. }
  201. err = svr.Run()
  202. if err == nil && shouldGracefulClose {
  203. <-closedDoneCh
  204. }
  205. return
  206. }