root.go 5.3 KB

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