root.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. kcpDoneCh chan struct{}
  66. )
  67. func init() {
  68. rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
  69. rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
  70. kcpDoneCh = make(chan struct{})
  71. }
  72. var rootCmd = &cobra.Command{
  73. Use: "frpc",
  74. Short: "frpc is the client of frp (https://github.com/fatedier/frp)",
  75. RunE: func(cmd *cobra.Command, args []string) error {
  76. if showVersion {
  77. fmt.Println(version.Full())
  78. return nil
  79. }
  80. // Do not show command usage here.
  81. err := runClient(cfgFile)
  82. if err != nil {
  83. fmt.Println(err)
  84. os.Exit(1)
  85. }
  86. return nil
  87. },
  88. }
  89. func Execute() {
  90. if err := rootCmd.Execute(); err != nil {
  91. os.Exit(1)
  92. }
  93. }
  94. func handleSignal(svr *client.Service) {
  95. ch := make(chan os.Signal)
  96. signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
  97. <-ch
  98. svr.Close()
  99. time.Sleep(250 * time.Millisecond)
  100. close(kcpDoneCh)
  101. }
  102. func parseClientCommonCfg(fileType int, content string) (cfg config.ClientCommonConf, err error) {
  103. if fileType == CfgFileTypeIni {
  104. cfg, err = parseClientCommonCfgFromIni(content)
  105. } else if fileType == CfgFileTypeCmd {
  106. cfg, err = parseClientCommonCfgFromCmd()
  107. }
  108. if err != nil {
  109. return
  110. }
  111. err = cfg.Check()
  112. if err != nil {
  113. return
  114. }
  115. return
  116. }
  117. func parseClientCommonCfgFromIni(content string) (config.ClientCommonConf, error) {
  118. cfg, err := config.UnmarshalClientConfFromIni(content)
  119. if err != nil {
  120. return config.ClientCommonConf{}, err
  121. }
  122. return cfg, err
  123. }
  124. func parseClientCommonCfgFromCmd() (cfg config.ClientCommonConf, err error) {
  125. cfg = config.GetDefaultClientConf()
  126. strs := strings.Split(serverAddr, ":")
  127. if len(strs) < 2 {
  128. err = fmt.Errorf("invalid server_addr")
  129. return
  130. }
  131. if strs[0] != "" {
  132. cfg.ServerAddr = strs[0]
  133. }
  134. cfg.ServerPort, err = strconv.Atoi(strs[1])
  135. if err != nil {
  136. err = fmt.Errorf("invalid server_addr")
  137. return
  138. }
  139. cfg.User = user
  140. cfg.Protocol = protocol
  141. cfg.LogLevel = logLevel
  142. cfg.LogFile = logFile
  143. cfg.LogMaxDays = int64(logMaxDays)
  144. if logFile == "console" {
  145. cfg.LogWay = "console"
  146. } else {
  147. cfg.LogWay = "file"
  148. }
  149. cfg.DisableLogColor = disableLogColor
  150. // Only token authentication is supported in cmd mode
  151. cfg.AuthClientConfig = auth.GetDefaultAuthClientConf()
  152. cfg.Token = token
  153. return
  154. }
  155. func runClient(cfgFilePath string) (err error) {
  156. var content string
  157. content, err = config.GetRenderedConfFromFile(cfgFilePath)
  158. if err != nil {
  159. return
  160. }
  161. cfg, err := parseClientCommonCfg(CfgFileTypeIni, content)
  162. if err != nil {
  163. return
  164. }
  165. pxyCfgs, visitorCfgs, err := config.LoadAllConfFromIni(cfg.User, content, cfg.Start)
  166. if err != nil {
  167. return err
  168. }
  169. err = startService(cfg, pxyCfgs, visitorCfgs, cfgFilePath)
  170. return
  171. }
  172. func startService(cfg config.ClientCommonConf, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf, cfgFile string) (err error) {
  173. log.InitLog(cfg.LogWay, cfg.LogFile, cfg.LogLevel,
  174. cfg.LogMaxDays, cfg.DisableLogColor)
  175. if cfg.DnsServer != "" {
  176. s := cfg.DnsServer
  177. if !strings.Contains(s, ":") {
  178. s += ":53"
  179. }
  180. // Change default dns server for frpc
  181. net.DefaultResolver = &net.Resolver{
  182. PreferGo: true,
  183. Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
  184. return net.Dial("udp", s)
  185. },
  186. }
  187. }
  188. svr, errRet := client.NewService(cfg, pxyCfgs, visitorCfgs, cfgFile)
  189. if errRet != nil {
  190. err = errRet
  191. return
  192. }
  193. // Capture the exit signal if we use kcp.
  194. if cfg.Protocol == "kcp" {
  195. go handleSignal(svr)
  196. }
  197. err = svr.Run()
  198. if cfg.Protocol == "kcp" {
  199. <-kcpDoneCh
  200. }
  201. return
  202. }