db.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package file
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/cnlh/nps/lib/common"
  6. "github.com/cnlh/nps/lib/crypt"
  7. "github.com/cnlh/nps/lib/rate"
  8. "net/http"
  9. "regexp"
  10. "sort"
  11. "strings"
  12. "sync"
  13. )
  14. type DbUtils struct {
  15. JsonDb *JsonDb
  16. }
  17. var (
  18. Db *DbUtils
  19. once sync.Once
  20. )
  21. //init csv from file
  22. func GetDb() *DbUtils {
  23. once.Do(func() {
  24. jsonDb := NewJsonDb(common.GetRunPath())
  25. jsonDb.LoadClientFromJsonFile()
  26. jsonDb.LoadTaskFromJsonFile()
  27. jsonDb.LoadHostFromJsonFile()
  28. Db = &DbUtils{JsonDb: jsonDb}
  29. })
  30. return Db
  31. }
  32. func GetMapKeys(m sync.Map, isSort bool, sortKey, order string) (keys []int) {
  33. if sortKey != "" && isSort {
  34. return sortClientByKey(m, sortKey, order)
  35. }
  36. m.Range(func(key, value interface{}) bool {
  37. keys = append(keys, key.(int))
  38. return true
  39. })
  40. sort.Ints(keys)
  41. return
  42. }
  43. func (s *DbUtils) GetClientList(start, length int, search, sort, order string, clientId int) ([]*Client, int) {
  44. list := make([]*Client, 0)
  45. var cnt int
  46. keys := GetMapKeys(s.JsonDb.Clients, true, sort, order)
  47. for _, key := range keys {
  48. if value, ok := s.JsonDb.Clients.Load(key); ok {
  49. v := value.(*Client)
  50. if v.NoDisplay {
  51. continue
  52. }
  53. if clientId != 0 && clientId != v.Id {
  54. continue
  55. }
  56. if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search)) {
  57. continue
  58. }
  59. cnt++
  60. if start--; start < 0 {
  61. if length--; length > 0 {
  62. list = append(list, v)
  63. }
  64. }
  65. }
  66. }
  67. return list, cnt
  68. }
  69. func (s *DbUtils) GetIdByVerifyKey(vKey string, addr string) (id int, err error) {
  70. var exist bool
  71. s.JsonDb.Clients.Range(func(key, value interface{}) bool {
  72. v := value.(*Client)
  73. if common.Getverifyval(v.VerifyKey) == vKey && v.Status {
  74. v.Addr = common.GetIpByAddr(addr)
  75. id = v.Id
  76. exist = true
  77. return false
  78. }
  79. return true
  80. })
  81. if exist {
  82. return
  83. }
  84. return 0, errors.New("not found")
  85. }
  86. func (s *DbUtils) NewTask(t *Tunnel) (err error) {
  87. s.JsonDb.Tasks.Range(func(key, value interface{}) bool {
  88. v := value.(*Tunnel)
  89. if (v.Mode == "secret" || v.Mode == "p2p") && v.Password == t.Password {
  90. err = errors.New(fmt.Sprintf("secret mode keys %s must be unique", t.Password))
  91. return false
  92. }
  93. return true
  94. })
  95. if err != nil {
  96. return
  97. }
  98. t.Flow = new(Flow)
  99. s.JsonDb.Tasks.Store(t.Id, t)
  100. s.JsonDb.StoreTasksToJsonFile()
  101. return
  102. }
  103. func (s *DbUtils) UpdateTask(t *Tunnel) error {
  104. s.JsonDb.Tasks.Store(t.Id, t)
  105. s.JsonDb.StoreTasksToJsonFile()
  106. return nil
  107. }
  108. func (s *DbUtils) DelTask(id int) error {
  109. s.JsonDb.Tasks.Delete(id)
  110. s.JsonDb.StoreTasksToJsonFile()
  111. return nil
  112. }
  113. //md5 password
  114. func (s *DbUtils) GetTaskByMd5Password(p string) (t *Tunnel) {
  115. s.JsonDb.Tasks.Range(func(key, value interface{}) bool {
  116. if crypt.Md5(value.(*Tunnel).Password) == p {
  117. t = value.(*Tunnel)
  118. return false
  119. }
  120. return true
  121. })
  122. return
  123. }
  124. func (s *DbUtils) GetTask(id int) (t *Tunnel, err error) {
  125. if v, ok := s.JsonDb.Tasks.Load(id); ok {
  126. t = v.(*Tunnel)
  127. return
  128. }
  129. err = errors.New("not found")
  130. return
  131. }
  132. func (s *DbUtils) DelHost(id int) error {
  133. s.JsonDb.Hosts.Delete(id)
  134. s.JsonDb.StoreHostToJsonFile()
  135. return nil
  136. }
  137. func (s *DbUtils) IsHostExist(h *Host) bool {
  138. var exist bool
  139. s.JsonDb.Hosts.Range(func(key, value interface{}) bool {
  140. v := value.(*Host)
  141. if v.Id != h.Id && v.Host == h.Host && h.Location == v.Location && (v.Scheme == "all" || v.Scheme == h.Scheme) {
  142. exist = true
  143. return false
  144. }
  145. return true
  146. })
  147. return exist
  148. }
  149. func (s *DbUtils) NewHost(t *Host) error {
  150. if t.Location == "" {
  151. t.Location = "/"
  152. }
  153. if s.IsHostExist(t) {
  154. return errors.New("host has exist")
  155. }
  156. t.Flow = new(Flow)
  157. s.JsonDb.Hosts.Store(t.Id, t)
  158. s.JsonDb.StoreHostToJsonFile()
  159. return nil
  160. }
  161. func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, int) {
  162. list := make([]*Host, 0)
  163. var cnt int
  164. keys := GetMapKeys(s.JsonDb.Hosts, false, "", "")
  165. for _, key := range keys {
  166. if value, ok := s.JsonDb.Hosts.Load(key); ok {
  167. v := value.(*Host)
  168. if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search)) {
  169. continue
  170. }
  171. if id == 0 || v.Client.Id == id {
  172. cnt++
  173. if start--; start < 0 {
  174. if length--; length > 0 {
  175. list = append(list, v)
  176. }
  177. }
  178. }
  179. }
  180. }
  181. return list, cnt
  182. }
  183. func (s *DbUtils) DelClient(id int) error {
  184. s.JsonDb.Clients.Delete(id)
  185. s.JsonDb.StoreClientsToJsonFile()
  186. return nil
  187. }
  188. func (s *DbUtils) NewClient(c *Client) error {
  189. var isNotSet bool
  190. if c.WebUserName != "" && !s.VerifyUserName(c.WebUserName, c.Id) {
  191. return errors.New("web login username duplicate, please reset")
  192. }
  193. reset:
  194. if c.VerifyKey == "" || isNotSet {
  195. isNotSet = true
  196. c.VerifyKey = crypt.GetRandomString(16)
  197. }
  198. if c.RateLimit == 0 {
  199. c.Rate = rate.NewRate(int64(2 << 23))
  200. c.Rate.Start()
  201. }
  202. if !s.VerifyVkey(c.VerifyKey, c.Id) {
  203. if isNotSet {
  204. goto reset
  205. }
  206. return errors.New("Vkey duplicate, please reset")
  207. }
  208. if c.Id == 0 {
  209. c.Id = int(s.JsonDb.GetClientId())
  210. }
  211. if c.Flow == nil {
  212. c.Flow = new(Flow)
  213. }
  214. s.JsonDb.Clients.Store(c.Id, c)
  215. s.JsonDb.StoreClientsToJsonFile()
  216. return nil
  217. }
  218. func (s *DbUtils) VerifyVkey(vkey string, id int) (res bool) {
  219. res = true
  220. s.JsonDb.Clients.Range(func(key, value interface{}) bool {
  221. v := value.(*Client)
  222. if v.VerifyKey == vkey && v.Id != id {
  223. res = false
  224. return false
  225. }
  226. return true
  227. })
  228. return res
  229. }
  230. func (s *DbUtils) VerifyUserName(username string, id int) (res bool) {
  231. res = true
  232. s.JsonDb.Clients.Range(func(key, value interface{}) bool {
  233. v := value.(*Client)
  234. if v.WebUserName == username && v.Id != id {
  235. res = false
  236. return false
  237. }
  238. return true
  239. })
  240. return res
  241. }
  242. func (s *DbUtils) UpdateClient(t *Client) error {
  243. s.JsonDb.Clients.Store(t.Id, t)
  244. if t.RateLimit == 0 {
  245. t.Rate = rate.NewRate(int64(2 << 23))
  246. t.Rate.Start()
  247. }
  248. return nil
  249. }
  250. func (s *DbUtils) IsPubClient(id int) bool {
  251. client, err := s.GetClient(id)
  252. if err == nil {
  253. return client.NoDisplay
  254. }
  255. return false
  256. }
  257. func (s *DbUtils) GetClient(id int) (c *Client, err error) {
  258. if v, ok := s.JsonDb.Clients.Load(id); ok {
  259. c = v.(*Client)
  260. return
  261. }
  262. err = errors.New("未找到客户端")
  263. return
  264. }
  265. func (s *DbUtils) GetClientIdByVkey(vkey string) (id int, err error) {
  266. var exist bool
  267. s.JsonDb.Clients.Range(func(key, value interface{}) bool {
  268. v := value.(*Client)
  269. if crypt.Md5(v.VerifyKey) == vkey {
  270. exist = true
  271. id = v.Id
  272. return false
  273. }
  274. return true
  275. })
  276. if exist {
  277. return
  278. }
  279. err = errors.New("未找到客户端")
  280. return
  281. }
  282. func (s *DbUtils) GetHostById(id int) (h *Host, err error) {
  283. if v, ok := s.JsonDb.Hosts.Load(id); ok {
  284. h = v.(*Host)
  285. return
  286. }
  287. err = errors.New("The host could not be parsed")
  288. return
  289. }
  290. //get key by host from x
  291. func (s *DbUtils) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
  292. var hosts []*Host
  293. //Handling Ported Access
  294. host = common.GetIpByAddr(host)
  295. s.JsonDb.Hosts.Range(func(key, value interface{}) bool {
  296. v := value.(*Host)
  297. if v.IsClose {
  298. return true
  299. }
  300. //Remove http(s) http(s)://a.proxy.com
  301. //*.proxy.com *.a.proxy.com Do some pan-parsing
  302. tmp := strings.Replace(v.Host, "*", `\w+?`, -1)
  303. var re *regexp.Regexp
  304. if re, err = regexp.Compile(tmp); err != nil {
  305. return true
  306. }
  307. if len(re.FindAllString(host, -1)) > 0 && (v.Scheme == "all" || v.Scheme == r.URL.Scheme) {
  308. //URL routing
  309. hosts = append(hosts, v)
  310. }
  311. return true
  312. })
  313. for _, v := range hosts {
  314. //If not set, default matches all
  315. if v.Location == "" {
  316. v.Location = "/"
  317. }
  318. if strings.Index(r.RequestURI, v.Location) == 0 {
  319. if h == nil || (len(v.Location) > len(h.Location)) {
  320. h = v
  321. }
  322. }
  323. }
  324. if h != nil {
  325. return
  326. }
  327. err = errors.New("The host could not be parsed")
  328. return
  329. }