server.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package server
  2. import (
  3. "errors"
  4. "github.com/cnlh/nps/bridge"
  5. "github.com/cnlh/nps/lib/common"
  6. "github.com/cnlh/nps/lib/file"
  7. "github.com/cnlh/nps/server/proxy"
  8. "github.com/cnlh/nps/server/tool"
  9. "github.com/cnlh/nps/vender/github.com/astaxie/beego"
  10. "github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
  11. "github.com/shirou/gopsutil/cpu"
  12. "github.com/shirou/gopsutil/load"
  13. "github.com/shirou/gopsutil/mem"
  14. "github.com/shirou/gopsutil/net"
  15. "math"
  16. "os"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. var (
  22. Bridge *bridge.Bridge
  23. RunList map[int]interface{}
  24. )
  25. func init() {
  26. RunList = make(map[int]interface{})
  27. }
  28. //init task from db
  29. func InitFromCsv() {
  30. //Add a public password
  31. if vkey := beego.AppConfig.String("public_vkey"); vkey != "" {
  32. c := file.NewClient(vkey, true, true)
  33. file.GetDb().NewClient(c)
  34. RunList[c.Id] = nil
  35. }
  36. //Initialize services in server-side files
  37. file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
  38. if value.(*file.Tunnel).Status {
  39. AddTask(value.(*file.Tunnel))
  40. }
  41. return true
  42. })
  43. }
  44. //get bridge command
  45. func DealBridgeTask() {
  46. for {
  47. select {
  48. case t := <-Bridge.OpenTask:
  49. AddTask(t)
  50. case t := <-Bridge.CloseTask:
  51. StopServer(t.Id)
  52. case id := <-Bridge.CloseClient:
  53. DelTunnelAndHostByClientId(id, true)
  54. if v, ok := file.GetDb().JsonDb.Clients.Load(id); ok {
  55. if v.(*file.Client).NoStore {
  56. file.GetDb().DelClient(id)
  57. }
  58. }
  59. case tunnel := <-Bridge.OpenTask:
  60. StartTask(tunnel.Id)
  61. case s := <-Bridge.SecretChan:
  62. logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
  63. if t := file.GetDb().GetTaskByMd5Password(s.Password); t != nil {
  64. if !t.Client.GetConn() {
  65. logs.Info("Connections exceed the current client %d limit", t.Client.Id)
  66. s.Conn.Close()
  67. } else if t.Status {
  68. go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow)
  69. } else {
  70. s.Conn.Close()
  71. logs.Trace("This key %s cannot be processed,status is close", s.Password)
  72. }
  73. } else {
  74. logs.Trace("This key %s cannot be processed", s.Password)
  75. s.Conn.Close()
  76. }
  77. }
  78. }
  79. }
  80. //start a new server
  81. func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string) {
  82. Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList)
  83. go func() {
  84. if err := Bridge.StartTunnel(); err != nil {
  85. logs.Error("start server bridge error", err)
  86. os.Exit(0)
  87. }
  88. }()
  89. if p, err := beego.AppConfig.Int("p2p_port"); err == nil {
  90. logs.Info("start p2p server port", p)
  91. go proxy.NewP2PServer(p).Start()
  92. }
  93. go DealBridgeTask()
  94. go dealClientFlow()
  95. if svr := NewMode(Bridge, cnf); svr != nil {
  96. if err := svr.Start(); err != nil {
  97. logs.Error(err)
  98. }
  99. RunList[cnf.Id] = svr
  100. } else {
  101. logs.Error("Incorrect startup mode %s", cnf.Mode)
  102. }
  103. }
  104. func dealClientFlow() {
  105. ticker := time.NewTicker(time.Minute)
  106. for {
  107. select {
  108. case <-ticker.C:
  109. dealClientData()
  110. }
  111. }
  112. }
  113. //new a server by mode name
  114. func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
  115. var service proxy.Service
  116. switch c.Mode {
  117. case "tcp", "file":
  118. service = proxy.NewTunnelModeServer(proxy.ProcessTunnel, Bridge, c)
  119. case "socks5":
  120. service = proxy.NewSock5ModeServer(Bridge, c)
  121. case "httpProxy":
  122. service = proxy.NewTunnelModeServer(proxy.ProcessHttp, Bridge, c)
  123. case "udp":
  124. service = proxy.NewUdpModeServer(Bridge, c)
  125. case "webServer":
  126. InitFromCsv()
  127. t := &file.Tunnel{
  128. Port: 0,
  129. Mode: "httpHostServer",
  130. Status: true,
  131. }
  132. AddTask(t)
  133. service = proxy.NewWebServer(Bridge)
  134. case "httpHostServer":
  135. service = proxy.NewHttp(Bridge, c)
  136. }
  137. return service
  138. }
  139. //stop server
  140. func StopServer(id int) error {
  141. if v, ok := RunList[id]; ok {
  142. if svr, ok := v.(proxy.Service); ok {
  143. if err := svr.Close(); err != nil {
  144. return err
  145. }
  146. logs.Info("stop server id %d", id)
  147. } else {
  148. logs.Warn("stop server id %d error", id)
  149. }
  150. if t, err := file.GetDb().GetTask(id); err != nil {
  151. return err
  152. } else {
  153. t.Status = false
  154. file.GetDb().UpdateTask(t)
  155. }
  156. delete(RunList, id)
  157. return nil
  158. }
  159. return errors.New("task is not running")
  160. }
  161. //add task
  162. func AddTask(t *file.Tunnel) error {
  163. if t.Mode == "secret" || t.Mode == "p2p" {
  164. logs.Info("secret task %s start ", t.Remark)
  165. RunList[t.Id] = nil
  166. return nil
  167. }
  168. if b := tool.TestServerPort(t.Port, t.Mode); !b && t.Mode != "httpHostServer" {
  169. logs.Error("taskId %d start error port %d open failed", t.Id, t.Port)
  170. return errors.New("the port open error")
  171. }
  172. if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
  173. go flowSession(time.Minute * time.Duration(minute))
  174. }
  175. if svr := NewMode(Bridge, t); svr != nil {
  176. logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
  177. RunList[t.Id] = svr
  178. go func() {
  179. if err := svr.Start(); err != nil {
  180. logs.Error("clientId %d taskId %d start error %s", t.Client.Id, t.Id, err)
  181. delete(RunList, t.Id)
  182. return
  183. }
  184. }()
  185. } else {
  186. return errors.New("the mode is not correct")
  187. }
  188. return nil
  189. }
  190. //start task
  191. func StartTask(id int) error {
  192. if t, err := file.GetDb().GetTask(id); err != nil {
  193. return err
  194. } else {
  195. AddTask(t)
  196. t.Status = true
  197. file.GetDb().UpdateTask(t)
  198. }
  199. return nil
  200. }
  201. //delete task
  202. func DelTask(id int) error {
  203. if _, ok := RunList[id]; ok {
  204. if err := StopServer(id); err != nil {
  205. return err
  206. }
  207. }
  208. return file.GetDb().DelTask(id)
  209. }
  210. //get task list by page num
  211. func GetTunnel(start, length int, typeVal string, clientId int, search string) ([]*file.Tunnel, int) {
  212. list := make([]*file.Tunnel, 0)
  213. var cnt int
  214. keys := file.GetMapKeys(file.GetDb().JsonDb.Tasks, false, "", "")
  215. for _, key := range keys {
  216. if value, ok := file.GetDb().JsonDb.Tasks.Load(key); ok {
  217. v := value.(*file.Tunnel)
  218. if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
  219. continue
  220. }
  221. if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search)) {
  222. continue
  223. }
  224. cnt++
  225. if _, ok := Bridge.Client.Load(v.Client.Id); ok {
  226. v.Client.IsConnect = true
  227. } else {
  228. v.Client.IsConnect = false
  229. }
  230. if start--; start < 0 {
  231. if length--; length > 0 {
  232. if _, ok := RunList[v.Id]; ok {
  233. v.RunStatus = true
  234. } else {
  235. v.RunStatus = false
  236. }
  237. list = append(list, v)
  238. }
  239. }
  240. }
  241. }
  242. return list, cnt
  243. }
  244. //get client list
  245. func GetClientList(start, length int, search, sort, order string, clientId int) (list []*file.Client, cnt int) {
  246. list, cnt = file.GetDb().GetClientList(start, length, search, sort, order, clientId)
  247. dealClientData()
  248. return
  249. }
  250. func dealClientData() {
  251. file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
  252. v := value.(*file.Client)
  253. if _, ok := Bridge.Client.Load(v.Id); ok {
  254. v.IsConnect = true
  255. } else {
  256. v.IsConnect = false
  257. }
  258. v.Flow.InletFlow = 0
  259. v.Flow.ExportFlow = 0
  260. file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
  261. h := value.(*file.Host)
  262. if h.Client.Id == v.Id {
  263. v.Flow.InletFlow += h.Flow.InletFlow
  264. v.Flow.ExportFlow += h.Flow.ExportFlow
  265. }
  266. return true
  267. })
  268. file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
  269. t := value.(*file.Tunnel)
  270. if t.Client.Id == v.Id {
  271. v.Flow.InletFlow += t.Flow.InletFlow
  272. v.Flow.ExportFlow += t.Flow.ExportFlow
  273. }
  274. return true
  275. })
  276. return true
  277. })
  278. return
  279. }
  280. //delete all host and tasks by client id
  281. func DelTunnelAndHostByClientId(clientId int, justDelNoStore bool) {
  282. var ids []int
  283. file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
  284. v := value.(*file.Tunnel)
  285. if justDelNoStore && !v.NoStore {
  286. return true
  287. }
  288. if v.Client.Id == clientId {
  289. ids = append(ids, v.Id)
  290. }
  291. return true
  292. })
  293. for _, id := range ids {
  294. DelTask(id)
  295. }
  296. ids = ids[:0]
  297. file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
  298. v := value.(*file.Host)
  299. if justDelNoStore && !v.NoStore {
  300. return true
  301. }
  302. if v.Client.Id == clientId {
  303. ids = append(ids, v.Id)
  304. }
  305. return true
  306. })
  307. for _, id := range ids {
  308. file.GetDb().DelHost(id)
  309. }
  310. }
  311. //close the client
  312. func DelClientConnect(clientId int) {
  313. Bridge.DelClient(clientId)
  314. }
  315. func GetDashboardData() map[string]interface{} {
  316. data := make(map[string]interface{})
  317. data["hostCount"] = common.GeSynctMapLen(file.GetDb().JsonDb.Hosts)
  318. data["clientCount"] = common.GeSynctMapLen(file.GetDb().JsonDb.Clients) - 1 //Remove the public key client
  319. dealClientData()
  320. c := 0
  321. var in, out int64
  322. file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
  323. v := value.(*file.Client)
  324. if v.IsConnect {
  325. c += 1
  326. }
  327. in += v.Flow.InletFlow
  328. out += v.Flow.ExportFlow
  329. return true
  330. })
  331. data["clientOnlineCount"] = c
  332. data["inletFlowCount"] = int(in)
  333. data["exportFlowCount"] = int(out)
  334. var tcp, udp, secret, socks5, p2p, http int
  335. file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
  336. switch value.(*file.Tunnel).Mode {
  337. case "tcp":
  338. tcp += 1
  339. case "socks5":
  340. udp += 1
  341. case "httpProxy":
  342. http += 1
  343. case "udp":
  344. udp += 1
  345. case "p2p":
  346. p2p += 1
  347. case "secret":
  348. secret += 1
  349. }
  350. return true
  351. })
  352. data["tcpC"] = tcp
  353. data["udpCount"] = udp
  354. data["socks5Count"] = socks5
  355. data["httpProxyCount"] = http
  356. data["secretCount"] = secret
  357. data["p2pCount"] = p2p
  358. data["bridgeType"] = beego.AppConfig.String("bridge_type")
  359. data["httpProxyPort"] = beego.AppConfig.String("http_proxy_port")
  360. data["httpsProxyPort"] = beego.AppConfig.String("https_proxy_port")
  361. data["ipLimit"] = beego.AppConfig.String("ip_limit")
  362. data["flowStoreInterval"] = beego.AppConfig.String("flow_store_interval")
  363. data["serverIp"] = beego.AppConfig.String("p2p_ip")
  364. data["p2pPort"] = beego.AppConfig.String("p2p_port")
  365. data["logLevel"] = beego.AppConfig.String("log_level")
  366. tcpCount := 0
  367. file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
  368. tcpCount += int(value.(*file.Client).NowConn)
  369. return true
  370. })
  371. data["tcpCount"] = tcpCount
  372. cpuPercet, _ := cpu.Percent(0, true)
  373. var cpuAll float64
  374. for _, v := range cpuPercet {
  375. cpuAll += v
  376. }
  377. loads, _ := load.Avg()
  378. data["load"] = loads.String()
  379. data["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
  380. swap, _ := mem.SwapMemory()
  381. data["swap_mem"] = math.Round(swap.UsedPercent)
  382. vir, _ := mem.VirtualMemory()
  383. data["virtual_mem"] = math.Round(vir.UsedPercent)
  384. conn, _ := net.ProtoCounters(nil)
  385. io1, _ := net.IOCounters(false)
  386. time.Sleep(time.Millisecond * 500)
  387. io2, _ := net.IOCounters(false)
  388. if len(io2) > 0 && len(io1) > 0 {
  389. data["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
  390. data["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
  391. }
  392. for _, v := range conn {
  393. data[v.Protocol] = v.Stats["CurrEstab"]
  394. }
  395. //chart
  396. var fg int
  397. if len(tool.ServerStatus) >= 10 {
  398. fg = len(tool.ServerStatus) / 10
  399. for i := 0; i <= 9; i++ {
  400. data["sys"+strconv.Itoa(i+1)] = tool.ServerStatus[i*fg]
  401. }
  402. }
  403. return data
  404. }
  405. func flowSession(m time.Duration) {
  406. ticker := time.NewTicker(m)
  407. for {
  408. select {
  409. case <-ticker.C:
  410. file.GetDb().JsonDb.StoreHostToJsonFile()
  411. file.GetDb().JsonDb.StoreTasksToJsonFile()
  412. file.GetDb().JsonDb.StoreClientsToJsonFile()
  413. }
  414. }
  415. }