1
0

npc.go 6.8 KB

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