server.go 11 KB

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