npc.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/astaxie/beego/logs"
  6. "github.com/ccding/go-stun/stun"
  7. "github.com/cnlh/nps/client"
  8. "github.com/cnlh/nps/lib/common"
  9. "github.com/cnlh/nps/lib/config"
  10. "github.com/cnlh/nps/lib/file"
  11. "github.com/cnlh/nps/lib/install"
  12. "github.com/cnlh/nps/lib/version"
  13. "github.com/kardianos/service"
  14. "os"
  15. "runtime"
  16. "strings"
  17. "time"
  18. )
  19. var (
  20. serverAddr = flag.String("server", "", "Server addr (ip:port)")
  21. configPath = flag.String("config", "", "Configuration file path")
  22. verifyKey = flag.String("vkey", "", "Authentication key")
  23. logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
  24. connType = flag.String("type", "tcp", "Connection type with the server(kcp|tcp)")
  25. proxyUrl = flag.String("proxy", "", "proxy socks5 url(eg:socks5://111:222@127.0.0.1:9007)")
  26. logLevel = flag.String("log_level", "7", "log level 0~7")
  27. registerTime = flag.Int("time", 2, "register time long /h")
  28. localPort = flag.Int("local_port", 2000, "p2p local port")
  29. password = flag.String("password", "", "p2p password flag")
  30. target = flag.String("target", "", "p2p target")
  31. localType = flag.String("local_type", "p2p", "p2p target")
  32. logPath = flag.String("log_path", "", "npc log path")
  33. debug = flag.Bool("debug", true, "npc debug")
  34. )
  35. func main() {
  36. flag.Parse()
  37. logs.Reset()
  38. logs.EnableFuncCallDepth(true)
  39. logs.SetLogFuncCallDepth(3)
  40. if *logPath == "" {
  41. *logPath = common.GetNpcLogPath()
  42. }
  43. if common.IsWindows() {
  44. *logPath = strings.Replace(*logPath, "\\", "\\\\", -1)
  45. }
  46. if *debug {
  47. logs.SetLogger(logs.AdapterConsole, `{"level":`+*logLevel+`,"color":true}`)
  48. } else {
  49. logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"`+*logPath+`","daily":false,"maxlines":100000,"color":true}`)
  50. }
  51. // init service
  52. options := make(service.KeyValue)
  53. options["Restart"] = "on-success"
  54. options["SuccessExitStatus"] = "1 2 8 SIGKILL"
  55. svcConfig := &service.Config{
  56. Name: "Npc",
  57. DisplayName: "nps内网穿透客户端",
  58. Description: "一款轻量级、功能强大的内网穿透代理服务器。支持tcp、udp流量转发,支持内网http代理、内网socks5代理,同时支持snappy压缩、站点保护、加密传输、多路复用、header修改等。支持web图形化管理,集成多用户模式。",
  59. Option: options,
  60. }
  61. if !common.IsWindows() {
  62. svcConfig.Dependencies = []string{
  63. "Requires=network.target",
  64. "After=network-online.target syslog.target"}
  65. }
  66. for _, v := range os.Args[1:] {
  67. switch v {
  68. case "install", "start", "stop", "uninstall", "restart":
  69. continue
  70. }
  71. if !strings.Contains(v, "-service=") && !strings.Contains(v, "-debug=") {
  72. svcConfig.Arguments = append(svcConfig.Arguments, v)
  73. }
  74. }
  75. svcConfig.Arguments = append(svcConfig.Arguments, "-debug=false")
  76. prg := &npc{
  77. exit: make(chan struct{}),
  78. }
  79. s, err := service.New(prg, svcConfig)
  80. if err != nil {
  81. logs.Error(err)
  82. return
  83. }
  84. if len(os.Args) >= 2 {
  85. switch os.Args[1] {
  86. case "status":
  87. if len(os.Args) > 2 {
  88. path := strings.Replace(os.Args[2], "-config=", "", -1)
  89. client.GetTaskStatus(path)
  90. }
  91. case "register":
  92. flag.CommandLine.Parse(os.Args[2:])
  93. client.RegisterLocalIp(*serverAddr, *verifyKey, *connType, *proxyUrl, *registerTime)
  94. case "update":
  95. install.UpdateNpc()
  96. return
  97. case "nat":
  98. nat, host, err := stun.NewClient().Discover()
  99. if err != nil || host == nil {
  100. logs.Error("get nat type error", err)
  101. return
  102. }
  103. fmt.Printf("nat type: %s \npublic address: %s\n", nat.String(), host.String())
  104. os.Exit(0)
  105. case "install", "start", "stop", "uninstall", "restart":
  106. if os.Args[1] == "install" {
  107. install.InstallNpc()
  108. }
  109. err := service.Control(s, os.Args[1])
  110. if err != nil {
  111. logs.Error("Valid actions: %q\n", service.ControlAction, err.Error())
  112. }
  113. return
  114. }
  115. }
  116. s.Run()
  117. }
  118. type npc struct {
  119. exit chan struct{}
  120. }
  121. func (p *npc) Start(s service.Service) error {
  122. go p.run()
  123. return nil
  124. }
  125. func (p *npc) Stop(s service.Service) error {
  126. close(p.exit)
  127. if service.Interactive() {
  128. os.Exit(0)
  129. }
  130. return nil
  131. }
  132. func (p *npc) run() error {
  133. defer func() {
  134. if err := recover(); err != nil {
  135. const size = 64 << 10
  136. buf := make([]byte, size)
  137. buf = buf[:runtime.Stack(buf, false)]
  138. logs.Warning("npc: panic serving %v: %v\n%s", err, string(buf))
  139. }
  140. }()
  141. //p2p or secret command
  142. if *password != "" {
  143. commonConfig := new(config.CommonConfig)
  144. commonConfig.Server = *serverAddr
  145. commonConfig.VKey = *verifyKey
  146. commonConfig.Tp = *connType
  147. localServer := new(config.LocalServer)
  148. localServer.Type = *localType
  149. localServer.Password = *password
  150. localServer.Target = *target
  151. localServer.Port = *localPort
  152. commonConfig.Client = new(file.Client)
  153. commonConfig.Client.Cnf = new(file.Config)
  154. go client.StartLocalServer(localServer, commonConfig)
  155. return nil
  156. }
  157. env := common.GetEnvMap()
  158. if *serverAddr == "" {
  159. *serverAddr, _ = env["NPC_SERVER_ADDR"]
  160. }
  161. if *verifyKey == "" {
  162. *verifyKey, _ = env["NPC_SERVER_VKEY"]
  163. }
  164. logs.Info("the version of client is %s, the core version of client is %s", version.VERSION, version.GetVersion())
  165. if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
  166. go func() {
  167. for {
  168. client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil).Start()
  169. logs.Info("It will be reconnected in five seconds")
  170. time.Sleep(time.Second * 5)
  171. }
  172. }()
  173. } else {
  174. if *configPath == "" {
  175. *configPath = "conf/npc.conf"
  176. }
  177. go client.StartFromFile(*configPath)
  178. }
  179. select {
  180. case <-p.exit:
  181. logs.Warning("stop...")
  182. }
  183. return nil
  184. }