1
0

main.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Copyright 2016 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 main
  15. import (
  16. "encoding/base64"
  17. "encoding/json"
  18. "fmt"
  19. "io/ioutil"
  20. "net/http"
  21. "os"
  22. "os/signal"
  23. "strconv"
  24. "strings"
  25. "syscall"
  26. "time"
  27. docopt "github.com/docopt/docopt-go"
  28. "github.com/rodaine/table"
  29. ini "github.com/vaughan0/go-ini"
  30. "github.com/fatedier/frp/client"
  31. "github.com/fatedier/frp/models/config"
  32. "github.com/fatedier/frp/utils/log"
  33. "github.com/fatedier/frp/utils/version"
  34. )
  35. var (
  36. configFile string = "./frpc.ini"
  37. )
  38. var usage string = `frpc is the client of frp
  39. Usage:
  40. frpc [-c config_file] [-L log_file] [--log-level=<log_level>] [--server-addr=<server_addr>]
  41. frpc reload [-c config_file]
  42. frpc status [-c config_file]
  43. frpc -h | --help
  44. frpc -v | --version
  45. Options:
  46. -c config_file set config file
  47. -L log_file set output log file, including console
  48. --log-level=<log_level> set log level: debug, info, warn, error
  49. --server-addr=<server_addr> addr which frps is listening for, example: 0.0.0.0:7000
  50. -h --help show this screen
  51. -v --version show version
  52. `
  53. func main() {
  54. var err error
  55. confFile := "./frpc.ini"
  56. // the configures parsed from file will be replaced by those from command line if exist
  57. args, err := docopt.Parse(usage, nil, true, version.Full(), false)
  58. if args["-c"] != nil {
  59. confFile = args["-c"].(string)
  60. }
  61. conf, err := ini.LoadFile(confFile)
  62. if err != nil {
  63. fmt.Println(err)
  64. os.Exit(1)
  65. }
  66. config.ClientCommonCfg, err = config.LoadClientCommonConf(conf)
  67. if err != nil {
  68. fmt.Println(err)
  69. os.Exit(1)
  70. }
  71. config.ClientCommonCfg.ConfigFile = confFile
  72. // check if reload command
  73. if args["reload"] != nil {
  74. if args["reload"].(bool) {
  75. if err = CmdReload(); err != nil {
  76. fmt.Printf("frps reload error: %v\n", err)
  77. os.Exit(1)
  78. } else {
  79. fmt.Printf("reload success\n")
  80. os.Exit(0)
  81. }
  82. }
  83. }
  84. // check if status command
  85. if args["status"] != nil {
  86. if args["status"].(bool) {
  87. if err = CmdStatus(); err != nil {
  88. fmt.Printf("frpc get status error: %v\n", err)
  89. os.Exit(1)
  90. } else {
  91. os.Exit(0)
  92. }
  93. }
  94. }
  95. if args["-L"] != nil {
  96. if args["-L"].(string) == "console" {
  97. config.ClientCommonCfg.LogWay = "console"
  98. } else {
  99. config.ClientCommonCfg.LogWay = "file"
  100. config.ClientCommonCfg.LogFile = args["-L"].(string)
  101. }
  102. }
  103. if args["--log-level"] != nil {
  104. config.ClientCommonCfg.LogLevel = args["--log-level"].(string)
  105. }
  106. if args["--server-addr"] != nil {
  107. addr := strings.Split(args["--server-addr"].(string), ":")
  108. if len(addr) != 2 {
  109. fmt.Println("--server-addr format error: example 0.0.0.0:7000")
  110. os.Exit(1)
  111. }
  112. serverPort, err := strconv.ParseInt(addr[1], 10, 64)
  113. if err != nil {
  114. fmt.Println("--server-addr format error, example 0.0.0.0:7000")
  115. os.Exit(1)
  116. }
  117. config.ClientCommonCfg.ServerAddr = addr[0]
  118. config.ClientCommonCfg.ServerPort = int(serverPort)
  119. }
  120. if args["-v"] != nil {
  121. if args["-v"].(bool) {
  122. fmt.Println(version.Full())
  123. os.Exit(0)
  124. }
  125. }
  126. pxyCfgs, visitorCfgs, err := config.LoadProxyConfFromFile(config.ClientCommonCfg.User, conf, config.ClientCommonCfg.Start)
  127. if err != nil {
  128. fmt.Println(err)
  129. os.Exit(1)
  130. }
  131. log.InitLog(config.ClientCommonCfg.LogWay, config.ClientCommonCfg.LogFile,
  132. config.ClientCommonCfg.LogLevel, config.ClientCommonCfg.LogMaxDays)
  133. svr := client.NewService(pxyCfgs, visitorCfgs)
  134. // Capture the exit signal if we use kcp.
  135. if config.ClientCommonCfg.Protocol == "kcp" {
  136. go HandleSignal(svr)
  137. }
  138. err = svr.Run()
  139. if err != nil {
  140. fmt.Println(err)
  141. os.Exit(1)
  142. }
  143. }
  144. func HandleSignal(svr *client.Service) {
  145. ch := make(chan os.Signal)
  146. signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
  147. <-ch
  148. svr.Close()
  149. time.Sleep(250 * time.Millisecond)
  150. os.Exit(0)
  151. }
  152. func CmdReload() error {
  153. if config.ClientCommonCfg.AdminPort == 0 {
  154. return fmt.Errorf("admin_port shoud be set if you want to use reload feature")
  155. }
  156. req, err := http.NewRequest("GET", "http://"+
  157. config.ClientCommonCfg.AdminAddr+":"+fmt.Sprintf("%d", config.ClientCommonCfg.AdminPort)+"/api/reload", nil)
  158. if err != nil {
  159. return err
  160. }
  161. authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(config.ClientCommonCfg.AdminUser+":"+
  162. config.ClientCommonCfg.AdminPwd))
  163. req.Header.Add("Authorization", authStr)
  164. resp, err := http.DefaultClient.Do(req)
  165. if err != nil {
  166. return err
  167. } else {
  168. if resp.StatusCode != 200 {
  169. return fmt.Errorf("admin api status code [%d]", resp.StatusCode)
  170. }
  171. defer resp.Body.Close()
  172. body, err := ioutil.ReadAll(resp.Body)
  173. if err != nil {
  174. return err
  175. }
  176. res := &client.GeneralResponse{}
  177. err = json.Unmarshal(body, &res)
  178. if err != nil {
  179. return fmt.Errorf("unmarshal http response error: %s", strings.TrimSpace(string(body)))
  180. } else if res.Code != 0 {
  181. return fmt.Errorf(res.Msg)
  182. }
  183. }
  184. return nil
  185. }
  186. func CmdStatus() error {
  187. if config.ClientCommonCfg.AdminPort == 0 {
  188. return fmt.Errorf("admin_port shoud be set if you want to get proxy status")
  189. }
  190. req, err := http.NewRequest("GET", "http://"+
  191. config.ClientCommonCfg.AdminAddr+":"+fmt.Sprintf("%d", config.ClientCommonCfg.AdminPort)+"/api/status", nil)
  192. if err != nil {
  193. return err
  194. }
  195. authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(config.ClientCommonCfg.AdminUser+":"+
  196. config.ClientCommonCfg.AdminPwd))
  197. req.Header.Add("Authorization", authStr)
  198. resp, err := http.DefaultClient.Do(req)
  199. if err != nil {
  200. return err
  201. } else {
  202. if resp.StatusCode != 200 {
  203. return fmt.Errorf("admin api status code [%d]", resp.StatusCode)
  204. }
  205. defer resp.Body.Close()
  206. body, err := ioutil.ReadAll(resp.Body)
  207. if err != nil {
  208. return err
  209. }
  210. res := &client.StatusResp{}
  211. err = json.Unmarshal(body, &res)
  212. if err != nil {
  213. return fmt.Errorf("unmarshal http response error: %s", strings.TrimSpace(string(body)))
  214. }
  215. fmt.Println("Proxy Status...")
  216. if len(res.Tcp) > 0 {
  217. fmt.Printf("TCP")
  218. tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
  219. for _, ps := range res.Tcp {
  220. tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
  221. }
  222. tbl.Print()
  223. fmt.Println("")
  224. }
  225. if len(res.Udp) > 0 {
  226. fmt.Printf("UDP")
  227. tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
  228. for _, ps := range res.Udp {
  229. tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
  230. }
  231. tbl.Print()
  232. fmt.Println("")
  233. }
  234. if len(res.Http) > 0 {
  235. fmt.Printf("HTTP")
  236. tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
  237. for _, ps := range res.Http {
  238. tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
  239. }
  240. tbl.Print()
  241. fmt.Println("")
  242. }
  243. if len(res.Https) > 0 {
  244. fmt.Printf("HTTPS")
  245. tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
  246. for _, ps := range res.Https {
  247. tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
  248. }
  249. tbl.Print()
  250. fmt.Println("")
  251. }
  252. if len(res.Stcp) > 0 {
  253. fmt.Printf("STCP")
  254. tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
  255. for _, ps := range res.Stcp {
  256. tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
  257. }
  258. tbl.Print()
  259. fmt.Println("")
  260. }
  261. if len(res.Xtcp) > 0 {
  262. fmt.Printf("XTCP")
  263. tbl := table.New("Name", "Status", "LocalAddr", "Plugin", "RemoteAddr", "Error")
  264. for _, ps := range res.Xtcp {
  265. tbl.AddRow(ps.Name, ps.Status, ps.LocalAddr, ps.Plugin, ps.RemoteAddr, ps.Err)
  266. }
  267. tbl.Print()
  268. fmt.Println("")
  269. }
  270. }
  271. return nil
  272. }