1
0

root.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. dnsServer string
  50. proxyName string
  51. localIP string
  52. localPort int
  53. remotePort int
  54. useEncryption bool
  55. useCompression bool
  56. bandwidthLimit string
  57. bandwidthLimitMode string
  58. customDomains string
  59. subDomain string
  60. httpUser string
  61. httpPwd string
  62. locations string
  63. hostHeaderRewrite string
  64. role string
  65. sk string
  66. multiplexer string
  67. serverName string
  68. bindAddr string
  69. bindPort int
  70. tlsEnable bool
  71. tlsServerName string
  72. )
  73. func init() {
  74. rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
  75. rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one frpc service for each file in config directory")
  76. rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
  77. }
  78. func RegisterCommonFlags(cmd *cobra.Command) {
  79. cmd.PersistentFlags().StringVarP(&serverAddr, "server_addr", "s", "127.0.0.1:7000", "frp server's address")
  80. cmd.PersistentFlags().StringVarP(&user, "user", "u", "", "user")
  81. cmd.PersistentFlags().StringVarP(&protocol, "protocol", "p", "tcp", "tcp, kcp, quic, websocket, wss")
  82. cmd.PersistentFlags().StringVarP(&token, "token", "t", "", "auth token")
  83. cmd.PersistentFlags().StringVarP(&logLevel, "log_level", "", "info", "log level")
  84. cmd.PersistentFlags().StringVarP(&logFile, "log_file", "", "console", "console or file path")
  85. cmd.PersistentFlags().IntVarP(&logMaxDays, "log_max_days", "", 3, "log file reversed days")
  86. cmd.PersistentFlags().BoolVarP(&disableLogColor, "disable_log_color", "", false, "disable log color in console")
  87. cmd.PersistentFlags().BoolVarP(&tlsEnable, "tls_enable", "", true, "enable frpc tls")
  88. cmd.PersistentFlags().StringVarP(&tlsServerName, "tls_server_name", "", "", "specify the custom server name of tls certificate")
  89. cmd.PersistentFlags().StringVarP(&dnsServer, "dns_server", "", "", "specify dns server instead of using system default one")
  90. }
  91. var rootCmd = &cobra.Command{
  92. Use: "frpc",
  93. Short: "frpc is the client of frp (https://github.com/fatedier/frp)",
  94. RunE: func(cmd *cobra.Command, args []string) error {
  95. if showVersion {
  96. fmt.Println(version.Full())
  97. return nil
  98. }
  99. // If cfgDir is not empty, run multiple frpc service for each config file in cfgDir.
  100. // Note that it's only designed for testing. It's not guaranteed to be stable.
  101. if cfgDir != "" {
  102. _ = runMultipleClients(cfgDir)
  103. return nil
  104. }
  105. // Do not show command usage here.
  106. err := runClient(cfgFile)
  107. if err != nil {
  108. os.Exit(1)
  109. }
  110. return nil
  111. },
  112. }
  113. func runMultipleClients(cfgDir string) error {
  114. var wg sync.WaitGroup
  115. err := filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
  116. if err != nil || d.IsDir() {
  117. return nil
  118. }
  119. wg.Add(1)
  120. time.Sleep(time.Millisecond)
  121. go func() {
  122. defer wg.Done()
  123. err := runClient(path)
  124. if err != nil {
  125. fmt.Printf("frpc service error for config file [%s]\n", path)
  126. }
  127. }()
  128. return nil
  129. })
  130. wg.Wait()
  131. return err
  132. }
  133. func Execute() {
  134. if err := rootCmd.Execute(); err != nil {
  135. os.Exit(1)
  136. }
  137. }
  138. func handleSignal(svr *client.Service, doneCh chan struct{}) {
  139. ch := make(chan os.Signal, 1)
  140. signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
  141. <-ch
  142. svr.GracefulClose(500 * time.Millisecond)
  143. close(doneCh)
  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. closedDoneCh := make(chan struct{})
  203. shouldGracefulClose := cfg.Protocol == "kcp" || cfg.Protocol == "quic"
  204. // Capture the exit signal if we use kcp or quic.
  205. if shouldGracefulClose {
  206. go handleSignal(svr, closedDoneCh)
  207. }
  208. err = svr.Run()
  209. if err == nil && shouldGracefulClose {
  210. <-closedDoneCh
  211. }
  212. return
  213. }