server.go 11 KB

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