root.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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/spf13/cobra"
  26. "github.com/fatedier/frp/client"
  27. "github.com/fatedier/frp/models/auth"
  28. "github.com/fatedier/frp/models/config"
  29. "github.com/fatedier/frp/utils/log"
  30. "github.com/fatedier/frp/utils/version"
  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 parseClientCommonCfg(fileType int, content string) (cfg config.ClientCommonConf, err error) {
  115. if fileType == CfgFileTypeIni {
  116. cfg, err = parseClientCommonCfgFromIni(content)
  117. } else if fileType == CfgFileTypeCmd {
  118. cfg, err = parseClientCommonCfgFromCmd()
  119. }
  120. if err != nil {
  121. return
  122. }
  123. err = cfg.Check()
  124. if err != nil {
  125. return
  126. }
  127. return
  128. }
  129. func parseClientCommonCfgFromIni(content string) (config.ClientCommonConf, error) {
  130. cfg, err := config.UnmarshalClientConfFromIni(content)
  131. if err != nil {
  132. return config.ClientCommonConf{}, err
  133. }
  134. return cfg, err
  135. }
  136. func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
  137. cfg = config.GetDefaultClientConf()
  138. strs := strings.Split(serverAddr, ":")
  139. if len(strs) < 2 {
  140. err = fmt.Errorf("invalid server_addr")
  141. return
  142. }
  143. if strs[0] != "" {
  144. cfg.ServerAddr = strs[0]
  145. }
  146. cfg.ServerPort, err = strconv.Atoi(strs[1])
  147. if err != nil {
  148. err = fmt.Errorf("invalid server_addr")
  149. return
  150. }
  151. cfg.User = user
  152. cfg.Protocol = protocol
  153. cfg.LogLevel = logLevel
  154. cfg.LogFile = logFile
  155. cfg.LogMaxDays = int64(logMaxDays)
  156. if logFile == "console" {
  157. cfg.LogWay = "console"
  158. } else {
  159. cfg.LogWay = "file"
  160. }
  161. cfg.DisableLogColor = disableLogColor
  162. // Only token authentication is supported in cmd mode
  163. cfg.AuthClientConfig = auth.GetDefaultAuthClientConf()
  164. cfg.Token = token
  165. cfg.TLSEnable = tlsEnable
  166. return
  167. }
  168. func runClient(cfgFilePath string) (err error) {
  169. var content string
  170. content, err = config.GetRenderedConfFromFile(cfgFilePath)
  171. if err != nil {
  172. return
  173. }
  174. cfg, err := parseClientCommonCfg(CfgFileTypeIni, content)
  175. if err != nil {
  176. return
  177. }
  178. pxyCfgs, visitorCfgs, err := config.LoadAllConfFromIni(cfg.User, content, cfg.Start)
  179. if err != nil {
  180. return err
  181. }
  182. err = startService(cfg, pxyCfgs, visitorCfgs, cfgFilePath)
  183. return
  184. }
  185. func startService(cfg config.ClientCommonConf, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf, cfgFile string) (err error) {
  186. log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel,
  187. cfg.LogMaxDays, cfg.DisableLogColor)
  188. if cfg.DnsServer != "" {
  189. s := cfg.DnsServer
  190. if !strings.Contains(s, ":") {
  191. s += ":53"
  192. }
  193. // Change default dns server for frpc
  194. net.DefaultResolver = &net.Resolver{
  195. PreferGo: true,
  196. Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
  197. return net.Dial("udp", s)
  198. },
  199. }
  200. }
  201. svr, errRet := client.NewService(cfg, pxyCfgs, visitorCfgs, cfgFile)
  202. if errRet != nil {
  203. err = errRet
  204. return
  205. }
  206. // Capture the exit signal if we use kcp.
  207. if cfg.Protocol == "kcp" {
  208. go handleSignal(svr)
  209. }
  210. err = svr.Run()
  211. if cfg.Protocol == "kcp" {
  212. <-kcpDoneCh
  213. }
  214. return
  215. }