root.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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.Close()
  111. time.Sleep(250 * time.Millisecond)
  112. close(kcpDoneCh)
  113. }
  114. func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
  115. cfg = config.GetDefaultClientConf()
  116. ipStr, portStr, err := net.SplitHostPort(serverAddr)
  117. if err != nil {
  118. err = fmt.Errorf("invalid server_addr: %v", err)
  119. return
  120. }
  121. cfg.ServerAddr = ipStr
  122. cfg.ServerPort, err = strconv.Atoi(portStr)
  123. if err != nil {
  124. err = fmt.Errorf("invalid server_addr: %v", err)
  125. return
  126. }
  127. cfg.User = user
  128. cfg.Protocol = protocol
  129. cfg.LogLevel = logLevel
  130. cfg.LogFile = logFile
  131. cfg.LogMaxDays = int64(logMaxDays)
  132. cfg.DisableLogColor = disableLogColor
  133. // Only token authentication is supported in cmd mode
  134. cfg.ClientConfig = auth.GetDefaultClientConf()
  135. cfg.Token = token
  136. cfg.TLSEnable = tlsEnable
  137. cfg.Complete()
  138. if err = cfg.Validate(); err != nil {
  139. err = fmt.Errorf("Parse config error: %v", err)
  140. return
  141. }
  142. return
  143. }
  144. func runClient(cfgFilePath string) error {
  145. cfg, pxyCfgs, visitorCfgs, err := config.ParseClientConfig(cfgFilePath)
  146. if err != nil {
  147. return err
  148. }
  149. return startService(cfg, pxyCfgs, visitorCfgs, cfgFilePath)
  150. }
  151. func startService(
  152. cfg config.ClientCommonConf,
  153. pxyCfgs map[string]config.ProxyConf,
  154. visitorCfgs map[string]config.VisitorConf,
  155. cfgFile string,
  156. ) (err error) {
  157. log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel,
  158. cfg.LogMaxDays, cfg.DisableLogColor)
  159. if cfg.DNSServer != "" {
  160. s := cfg.DNSServer
  161. if !strings.Contains(s, ":") {
  162. s += ":53"
  163. }
  164. // Change default dns server for frpc
  165. net.DefaultResolver = &net.Resolver{
  166. PreferGo: true,
  167. Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
  168. return net.Dial("udp", s)
  169. },
  170. }
  171. }
  172. svr, errRet := client.NewService(cfg, pxyCfgs, visitorCfgs, cfgFile)
  173. if errRet != nil {
  174. err = errRet
  175. return
  176. }
  177. // Capture the exit signal if we use kcp.
  178. if cfg.Protocol == "kcp" {
  179. go handleSignal(svr)
  180. }
  181. err = svr.Run()
  182. if err == nil && cfg.Protocol == "kcp" {
  183. <-kcpDoneCh
  184. }
  185. return
  186. }