npc.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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/version"
  12. "github.com/kardianos/service"
  13. "os"
  14. "runtime"
  15. "strings"
  16. "time"
  17. )
  18. var (
  19. serverAddr = flag.String("server", "", "Server addr (ip:port)")
  20. configPath = flag.String("config", "", "Configuration file path")
  21. verifyKey = flag.String("vkey", "", "Authentication key")
  22. logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
  23. connType = flag.String("type", "tcp", "Connection type with the server(kcp|tcp)")
  24. proxyUrl = flag.String("proxy", "", "proxy socks5 url(eg:socks5://111:222@127.0.0.1:9007)")
  25. logLevel = flag.String("log_level", "7", "log level 0~7")
  26. registerTime = flag.Int("time", 2, "register time long /h")
  27. localPort = flag.Int("local_port", 2000, "p2p local port")
  28. password = flag.String("password", "", "p2p password flag")
  29. target = flag.String("target", "", "p2p target")
  30. localType = flag.String("local_type", "p2p", "p2p target")
  31. logPath = flag.String("log_path", "", "npc log path")
  32. debug = flag.Bool("debug", false, "npc debug")
  33. srv = flag.String("service", "", "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. if !strings.Contains(v, "-service=") {
  68. svcConfig.Arguments = append(svcConfig.Arguments, v)
  69. }
  70. }
  71. prg := &npc{
  72. exit: make(chan struct{}),
  73. }
  74. s, err := service.New(prg, svcConfig)
  75. if err != nil {
  76. logs.Error(err)
  77. return
  78. }
  79. if len(os.Args) >= 2 {
  80. switch os.Args[1] {
  81. case "status":
  82. if len(os.Args) > 2 {
  83. path := strings.Replace(os.Args[2], "-config=", "", -1)
  84. client.GetTaskStatus(path)
  85. }
  86. case "register":
  87. flag.CommandLine.Parse(os.Args[2:])
  88. client.RegisterLocalIp(*serverAddr, *verifyKey, *connType, *proxyUrl, *registerTime)
  89. case "nat":
  90. nat, host, err := stun.NewClient().Discover()
  91. if err != nil || host == nil {
  92. logs.Error("get nat type error", err)
  93. return
  94. }
  95. fmt.Printf("nat type: %s \npublic address: %s\n", nat.String(), host.String())
  96. os.Exit(0)
  97. }
  98. }
  99. if *srv != "" {
  100. err := service.Control(s, *srv)
  101. if err != nil {
  102. logs.Error("Valid actions: %q\n", service.ControlAction, err.Error())
  103. }
  104. return
  105. }
  106. s.Run()
  107. }
  108. type npc struct {
  109. exit chan struct{}
  110. }
  111. func (p *npc) Start(s service.Service) error {
  112. p.run()
  113. return nil
  114. }
  115. func (p *npc) Stop(s service.Service) error {
  116. close(p.exit)
  117. if service.Interactive() {
  118. os.Exit(0)
  119. }
  120. return nil
  121. }
  122. func (p *npc) run() error {
  123. defer func() {
  124. if err := recover(); err != nil {
  125. const size = 64 << 10
  126. buf := make([]byte, size)
  127. buf = buf[:runtime.Stack(buf, false)]
  128. logs.Warning("npc: panic serving %v: %v\n%s", err, string(buf))
  129. }
  130. }()
  131. //p2p or secret command
  132. if *password != "" {
  133. commonConfig := new(config.CommonConfig)
  134. commonConfig.Server = *serverAddr
  135. commonConfig.VKey = *verifyKey
  136. commonConfig.Tp = *connType
  137. localServer := new(config.LocalServer)
  138. localServer.Type = *localType
  139. localServer.Password = *password
  140. localServer.Target = *target
  141. localServer.Port = *localPort
  142. commonConfig.Client = new(file.Client)
  143. commonConfig.Client.Cnf = new(file.Config)
  144. go client.StartLocalServer(localServer, commonConfig)
  145. return nil
  146. }
  147. env := common.GetEnvMap()
  148. if *serverAddr == "" {
  149. *serverAddr, _ = env["NPC_SERVER_ADDR"]
  150. }
  151. if *verifyKey == "" {
  152. *verifyKey, _ = env["NPC_SERVER_VKEY"]
  153. }
  154. logs.Info("the version of client is %s, the core version of client is %s", version.VERSION, version.GetVersion())
  155. if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
  156. go func() {
  157. for {
  158. client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil).Start()
  159. logs.Info("It will be reconnected in five seconds")
  160. time.Sleep(time.Second * 5)
  161. }
  162. }()
  163. } else {
  164. if *configPath == "" {
  165. *configPath = "conf/npc.conf"
  166. }
  167. go client.StartFromFile(*configPath)
  168. }
  169. select {
  170. case <-p.exit:
  171. logs.Warning("stop...")
  172. }
  173. return nil
  174. }