root.go 6.4 KB

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