db.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package file
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "regexp"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "ehang.io/nps/lib/common"
  11. "ehang.io/nps/lib/crypt"
  12. "ehang.io/nps/lib/rate"
  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. } else if c.Rate == nil {
  201. c.Rate = rate.NewRate(int64(c.RateLimit * 1024))
  202. }
  203. c.Rate.Start()
  204. if !s.VerifyVkey(c.VerifyKey, c.Id) {
  205. if isNotSet {
  206. goto reset
  207. }
  208. return errors.New("Vkey duplicate, please reset")
  209. }
  210. if c.Id == 0 {
  211. c.Id = int(s.JsonDb.GetClientId())
  212. }
  213. if c.Flow == nil {
  214. c.Flow = new(Flow)
  215. }
  216. s.JsonDb.Clients.Store(c.Id, c)
  217. s.JsonDb.StoreClientsToJsonFile()
  218. return nil
  219. }
  220. func (s *DbUtils) VerifyVkey(vkey string, id int) (res bool) {
  221. res = true
  222. s.JsonDb.Clients.Range(func(key, value interface{}) bool {
  223. v := value.(*Client)
  224. if v.VerifyKey == vkey && v.Id != id {
  225. res = false
  226. return false
  227. }
  228. return true
  229. })
  230. return res
  231. }
  232. func (s *DbUtils) VerifyUserName(username string, id int) (res bool) {
  233. res = true
  234. s.JsonDb.Clients.Range(func(key, value interface{}) bool {
  235. v := value.(*Client)
  236. if v.WebUserName == username && v.Id != id {
  237. res = false
  238. return false
  239. }
  240. return true
  241. })
  242. return res
  243. }
  244. func (s *DbUtils) UpdateClient(t *Client) error {
  245. s.JsonDb.Clients.Store(t.Id, t)
  246. if t.RateLimit == 0 {
  247. t.Rate = rate.NewRate(int64(2 << 23))
  248. t.Rate.Start()
  249. }
  250. return nil
  251. }
  252. func (s *DbUtils) IsPubClient(id int) bool {
  253. client, err := s.GetClient(id)
  254. if err == nil {
  255. return client.NoDisplay
  256. }
  257. return false
  258. }
  259. func (s *DbUtils) GetClient(id int) (c *Client, err error) {
  260. if v, ok := s.JsonDb.Clients.Load(id); ok {
  261. c = v.(*Client)
  262. return
  263. }
  264. err = errors.New("未找到客户端")
  265. return
  266. }
  267. func (s *DbUtils) GetClientIdByVkey(vkey string) (id int, err error) {
  268. var exist bool
  269. s.JsonDb.Clients.Range(func(key, value interface{}) bool {
  270. v := value.(*Client)
  271. if crypt.Md5(v.VerifyKey) == vkey {
  272. exist = true
  273. id = v.Id
  274. return false
  275. }
  276. return true
  277. })
  278. if exist {
  279. return
  280. }
  281. err = errors.New("未找到客户端")
  282. return
  283. }
  284. func (s *DbUtils) GetHostById(id int) (h *Host, err error) {
  285. if v, ok := s.JsonDb.Hosts.Load(id); ok {
  286. h = v.(*Host)
  287. return
  288. }
  289. err = errors.New("The host could not be parsed")
  290. return
  291. }
  292. //get key by host from x
  293. func (s *DbUtils) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
  294. var hosts []*Host
  295. //Handling Ported Access
  296. host = common.GetIpByAddr(host)
  297. s.JsonDb.Hosts.Range(func(key, value interface{}) bool {
  298. v := value.(*Host)
  299. if v.IsClose {
  300. return true
  301. }
  302. //Remove http(s) http(s)://a.proxy.com
  303. //*.proxy.com *.a.proxy.com Do some pan-parsing
  304. tmp := strings.Replace(v.Host, "*", `\w+?`, -1)
  305. var re *regexp.Regexp
  306. if re, err = regexp.Compile(tmp); err != nil {
  307. return true
  308. }
  309. if len(re.FindAllString(host, -1)) > 0 && (v.Scheme == "all" || v.Scheme == r.URL.Scheme) {
  310. //URL routing
  311. hosts = append(hosts, v)
  312. }
  313. return true
  314. })
  315. for _, v := range hosts {
  316. //If not set, default matches all
  317. if v.Location == "" {
  318. v.Location = "/"
  319. }
  320. if strings.Index(r.RequestURI, v.Location) == 0 {
  321. if h == nil || (len(v.Location) > len(h.Location)) {
  322. h = v
  323. }
  324. }
  325. }
  326. if h != nil {
  327. return
  328. }
  329. err = errors.New("The host could not be parsed")
  330. return
  331. }