1
0

file.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. package file
  2. import (
  3. "encoding/csv"
  4. "errors"
  5. "fmt"
  6. "github.com/cnlh/nps/lib/common"
  7. "github.com/cnlh/nps/lib/crypt"
  8. "github.com/cnlh/nps/lib/rate"
  9. "github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "sync/atomic"
  18. )
  19. func NewCsv(runPath string) *Csv {
  20. return &Csv{
  21. RunPath: runPath,
  22. }
  23. }
  24. type Csv struct {
  25. Tasks sync.Map
  26. Hosts sync.Map //域名列表
  27. HostsTmp sync.Map
  28. Clients sync.Map //客户端
  29. RunPath string //存储根目录
  30. ClientIncreaseId int32 //客户端id
  31. TaskIncreaseId int32 //任务自增ID
  32. HostIncreaseId int32 //host increased id
  33. }
  34. func (s *Csv) StoreTasksToCsv() {
  35. // 创建文件
  36. csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "tasks.csv"))
  37. if err != nil {
  38. logs.Error(err.Error())
  39. }
  40. defer csvFile.Close()
  41. writer := csv.NewWriter(csvFile)
  42. s.Tasks.Range(func(key, value interface{}) bool {
  43. task := value.(*Tunnel)
  44. if task.NoStore {
  45. return true
  46. }
  47. record := []string{
  48. strconv.Itoa(task.Port),
  49. task.Mode,
  50. task.Target.TargetStr,
  51. common.GetStrByBool(task.Status),
  52. strconv.Itoa(task.Id),
  53. strconv.Itoa(task.Client.Id),
  54. task.Remark,
  55. strconv.Itoa(int(task.Flow.ExportFlow)),
  56. strconv.Itoa(int(task.Flow.InletFlow)),
  57. task.Password,
  58. task.ServerIp,
  59. }
  60. err := writer.Write(record)
  61. if err != nil {
  62. logs.Error(err.Error())
  63. }
  64. return true
  65. })
  66. writer.Flush()
  67. }
  68. func (s *Csv) openFile(path string) ([][]string, error) {
  69. // 打开文件
  70. file, err := os.Open(path)
  71. if err != nil {
  72. panic(err)
  73. }
  74. defer file.Close()
  75. // 获取csv的reader
  76. reader := csv.NewReader(file)
  77. // 设置FieldsPerRecord为-1
  78. reader.FieldsPerRecord = -1
  79. // 读取文件中所有行保存到slice中
  80. return reader.ReadAll()
  81. }
  82. func (s *Csv) LoadTaskFromCsv() {
  83. path := filepath.Join(s.RunPath, "conf", "tasks.csv")
  84. records, err := s.openFile(path)
  85. if err != nil {
  86. logs.Error("Profile Opening Error:", path)
  87. os.Exit(0)
  88. }
  89. // 将每一行数据保存到内存slice中
  90. for _, item := range records {
  91. post := &Tunnel{
  92. Port: common.GetIntNoErrByStr(item[0]),
  93. Mode: item[1],
  94. Status: common.GetBoolByStr(item[3]),
  95. Id: common.GetIntNoErrByStr(item[4]),
  96. Remark: item[6],
  97. Password: item[9],
  98. }
  99. post.Target = new(Target)
  100. post.Target.TargetStr = item[2]
  101. post.Flow = new(Flow)
  102. post.Flow.ExportFlow = int64(common.GetIntNoErrByStr(item[7]))
  103. post.Flow.InletFlow = int64(common.GetIntNoErrByStr(item[8]))
  104. if post.Client, err = s.GetClient(common.GetIntNoErrByStr(item[5])); err != nil {
  105. continue
  106. }
  107. if len(item) > 10 {
  108. post.ServerIp = item[10]
  109. } else {
  110. post.ServerIp = "0.0.0.0"
  111. }
  112. s.Tasks.Store(post.Id, post)
  113. if post.Id > int(s.TaskIncreaseId) {
  114. s.TaskIncreaseId = int32(s.TaskIncreaseId)
  115. }
  116. }
  117. }
  118. func (s *Csv) GetIdByVerifyKey(vKey string, addr string) (id int, err error) {
  119. var exist bool
  120. s.Clients.Range(func(key, value interface{}) bool {
  121. v := value.(*Client)
  122. if common.Getverifyval(v.VerifyKey) == vKey && v.Status {
  123. v.Addr = common.GetIpByAddr(addr)
  124. id = v.Id
  125. exist = true
  126. return false
  127. }
  128. return true
  129. })
  130. if exist {
  131. return
  132. }
  133. return 0, errors.New("not found")
  134. }
  135. func (s *Csv) NewTask(t *Tunnel) (err error) {
  136. s.Tasks.Range(func(key, value interface{}) bool {
  137. v := value.(*Tunnel)
  138. if (v.Mode == "secret" || v.Mode == "p2p") && v.Password == t.Password {
  139. err = errors.New(fmt.Sprintf("Secret mode keys %s must be unique", t.Password))
  140. return false
  141. }
  142. return true
  143. })
  144. if err != nil {
  145. return
  146. }
  147. t.Flow = new(Flow)
  148. s.Tasks.Store(t.Id, t)
  149. s.StoreTasksToCsv()
  150. return
  151. }
  152. func (s *Csv) UpdateTask(t *Tunnel) error {
  153. s.Tasks.Store(t.Id, t)
  154. s.StoreTasksToCsv()
  155. return nil
  156. }
  157. func (s *Csv) DelTask(id int) error {
  158. s.Tasks.Delete(id)
  159. s.StoreTasksToCsv()
  160. return nil
  161. }
  162. //md5 password
  163. func (s *Csv) GetTaskByMd5Password(p string) (t *Tunnel) {
  164. s.Tasks.Range(func(key, value interface{}) bool {
  165. if crypt.Md5(value.(*Tunnel).Password) == p {
  166. t = value.(*Tunnel)
  167. return false
  168. }
  169. return true
  170. })
  171. return
  172. }
  173. func (s *Csv) GetTask(id int) (t *Tunnel, err error) {
  174. if v, ok := s.Tasks.Load(id); ok {
  175. t = v.(*Tunnel)
  176. return
  177. }
  178. err = errors.New("not found")
  179. return
  180. }
  181. func (s *Csv) StoreHostToCsv() {
  182. // 创建文件
  183. csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "hosts.csv"))
  184. if err != nil {
  185. panic(err)
  186. }
  187. defer csvFile.Close()
  188. // 获取csv的Writer
  189. writer := csv.NewWriter(csvFile)
  190. // 将map中的Post转换成slice,因为csv的Write需要slice参数
  191. // 并写入csv文件
  192. s.Hosts.Range(func(key, value interface{}) bool {
  193. host := value.(*Host)
  194. if host.NoStore {
  195. return true
  196. }
  197. record := []string{
  198. host.Host,
  199. host.Target.TargetStr,
  200. strconv.Itoa(host.Client.Id),
  201. host.HeaderChange,
  202. host.HostChange,
  203. host.Remark,
  204. host.Location,
  205. strconv.Itoa(host.Id),
  206. strconv.Itoa(int(host.Flow.ExportFlow)),
  207. strconv.Itoa(int(host.Flow.InletFlow)),
  208. host.Scheme,
  209. }
  210. err1 := writer.Write(record)
  211. if err1 != nil {
  212. panic(err1)
  213. }
  214. return true
  215. })
  216. // 确保所有内存数据刷到csv文件
  217. writer.Flush()
  218. }
  219. func (s *Csv) LoadClientFromCsv() {
  220. path := filepath.Join(s.RunPath, "conf", "clients.csv")
  221. records, err := s.openFile(path)
  222. if err != nil {
  223. logs.Error("Profile Opening Error:", path)
  224. os.Exit(0)
  225. }
  226. // 将每一行数据保存到内存slice中
  227. for _, item := range records {
  228. post := &Client{
  229. Id: common.GetIntNoErrByStr(item[0]),
  230. VerifyKey: item[1],
  231. Remark: item[2],
  232. Status: common.GetBoolByStr(item[3]),
  233. RateLimit: common.GetIntNoErrByStr(item[8]),
  234. Cnf: &Config{
  235. U: item[4],
  236. P: item[5],
  237. Crypt: common.GetBoolByStr(item[6]),
  238. Compress: common.GetBoolByStr(item[7]),
  239. },
  240. MaxConn: common.GetIntNoErrByStr(item[10]),
  241. }
  242. if post.Id > int(s.ClientIncreaseId) {
  243. s.ClientIncreaseId = int32(post.Id)
  244. }
  245. if post.RateLimit > 0 {
  246. post.Rate = rate.NewRate(int64(post.RateLimit * 1024))
  247. post.Rate.Start()
  248. } else {
  249. post.Rate = rate.NewRate(int64(2 << 23))
  250. post.Rate.Start()
  251. }
  252. post.Flow = new(Flow)
  253. post.Flow.FlowLimit = int64(common.GetIntNoErrByStr(item[9]))
  254. if len(item) >= 12 {
  255. post.ConfigConnAllow = common.GetBoolByStr(item[11])
  256. } else {
  257. post.ConfigConnAllow = true
  258. }
  259. if len(item) >= 13 {
  260. post.WebUserName = item[12]
  261. } else {
  262. post.WebUserName = ""
  263. }
  264. if len(item) >= 14 {
  265. post.WebPassword = item[13]
  266. } else {
  267. post.WebPassword = ""
  268. }
  269. s.Clients.Store(post.Id, post)
  270. }
  271. }
  272. func (s *Csv) LoadHostFromCsv() {
  273. path := filepath.Join(s.RunPath, "conf", "hosts.csv")
  274. records, err := s.openFile(path)
  275. if err != nil {
  276. logs.Error("Profile Opening Error:", path)
  277. os.Exit(0)
  278. }
  279. // 将每一行数据保存到内存slice中
  280. for _, item := range records {
  281. post := &Host{
  282. Host: item[0],
  283. HeaderChange: item[3],
  284. HostChange: item[4],
  285. Remark: item[5],
  286. Location: item[6],
  287. Id: common.GetIntNoErrByStr(item[7]),
  288. }
  289. if post.Client, err = s.GetClient(common.GetIntNoErrByStr(item[2])); err != nil {
  290. continue
  291. }
  292. post.Target = new(Target)
  293. post.Target.TargetStr = item[1]
  294. post.Flow = new(Flow)
  295. post.Flow.ExportFlow = int64(common.GetIntNoErrByStr(item[8]))
  296. post.Flow.InletFlow = int64(common.GetIntNoErrByStr(item[9]))
  297. if len(item) > 10 {
  298. post.Scheme = item[10]
  299. } else {
  300. post.Scheme = "all"
  301. }
  302. s.Hosts.Store(post.Id, post)
  303. if post.Id > int(s.HostIncreaseId) {
  304. s.HostIncreaseId = int32(post.Id)
  305. }
  306. //store host to hostMap if the host url is none
  307. }
  308. }
  309. func (s *Csv) DelHost(id int) error {
  310. s.Hosts.Delete(id)
  311. s.StoreHostToCsv()
  312. return nil
  313. }
  314. func (s *Csv) GetMapLen(m sync.Map) int {
  315. var c int
  316. m.Range(func(key, value interface{}) bool {
  317. c++
  318. return true
  319. })
  320. return c
  321. }
  322. func (s *Csv) IsHostExist(h *Host) bool {
  323. var exist bool
  324. s.Hosts.Range(func(key, value interface{}) bool {
  325. v := value.(*Host)
  326. if v.Host == h.Host && h.Location == v.Location && (v.Scheme == "all" || v.Scheme == h.Scheme) {
  327. exist = true
  328. return false
  329. }
  330. return true
  331. })
  332. return exist
  333. }
  334. func (s *Csv) NewHost(t *Host) error {
  335. if t.Location == "" {
  336. t.Location = "/"
  337. }
  338. if s.IsHostExist(t) {
  339. return errors.New("host has exist")
  340. }
  341. t.Flow = new(Flow)
  342. s.Hosts.Store(t.Id, t)
  343. s.StoreHostToCsv()
  344. return nil
  345. }
  346. func (s *Csv) GetHost(start, length int, id int, search string) ([]*Host, int) {
  347. list := make([]*Host, 0)
  348. var cnt int
  349. keys := GetMapKeys(s.Hosts, false, "", "")
  350. for _, key := range keys {
  351. if value, ok := s.Hosts.Load(key); ok {
  352. v := value.(*Host)
  353. if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search)) {
  354. continue
  355. }
  356. if id == 0 || v.Client.Id == id {
  357. cnt++
  358. if start--; start < 0 {
  359. if length--; length > 0 {
  360. list = append(list, v)
  361. }
  362. }
  363. }
  364. }
  365. }
  366. return list, cnt
  367. }
  368. func (s *Csv) DelClient(id int) error {
  369. s.Clients.Delete(id)
  370. s.StoreClientsToCsv()
  371. return nil
  372. }
  373. func (s *Csv) NewClient(c *Client) error {
  374. var isNotSet bool
  375. if c.WebUserName != "" && !s.VerifyUserName(c.WebUserName, c.Id) {
  376. return errors.New("web login username duplicate, please reset")
  377. }
  378. reset:
  379. if c.VerifyKey == "" || isNotSet {
  380. isNotSet = true
  381. c.VerifyKey = crypt.GetRandomString(16)
  382. }
  383. if c.RateLimit == 0 {
  384. c.Rate = rate.NewRate(int64(2 << 23))
  385. c.Rate.Start()
  386. }
  387. if !s.VerifyVkey(c.VerifyKey, c.Id) {
  388. if isNotSet {
  389. goto reset
  390. }
  391. return errors.New("Vkey duplicate, please reset")
  392. }
  393. if c.Id == 0 {
  394. c.Id = int(s.GetClientId())
  395. }
  396. if c.Flow == nil {
  397. c.Flow = new(Flow)
  398. }
  399. s.Clients.Store(c.Id, c)
  400. s.StoreClientsToCsv()
  401. return nil
  402. }
  403. func (s *Csv) VerifyVkey(vkey string, id int) (res bool) {
  404. res = true
  405. s.Clients.Range(func(key, value interface{}) bool {
  406. v := value.(*Client)
  407. if v.VerifyKey == vkey && v.Id != id {
  408. res = false
  409. return false
  410. }
  411. return true
  412. })
  413. return res
  414. }
  415. func (s *Csv) VerifyUserName(username string, id int) (res bool) {
  416. res = true
  417. s.Clients.Range(func(key, value interface{}) bool {
  418. v := value.(*Client)
  419. if v.WebUserName == username && v.Id != id {
  420. res = false
  421. return false
  422. }
  423. return true
  424. })
  425. return res
  426. }
  427. func (s *Csv) GetClientId() int32 {
  428. return atomic.AddInt32(&s.ClientIncreaseId, 1)
  429. }
  430. func (s *Csv) GetTaskId() int32 {
  431. return atomic.AddInt32(&s.TaskIncreaseId, 1)
  432. }
  433. func (s *Csv) GetHostId() int32 {
  434. return atomic.AddInt32(&s.HostIncreaseId, 1)
  435. }
  436. func (s *Csv) UpdateClient(t *Client) error {
  437. s.Clients.Store(t.Id, t)
  438. if t.RateLimit == 0 {
  439. t.Rate = rate.NewRate(int64(2 << 23))
  440. t.Rate.Start()
  441. }
  442. return nil
  443. }
  444. func (s *Csv) GetClientList(start, length int, search, sort, order string, clientId int) ([]*Client, int) {
  445. list := make([]*Client, 0)
  446. var cnt int
  447. keys := GetMapKeys(s.Clients, true, sort, order)
  448. for _, key := range keys {
  449. if value, ok := s.Clients.Load(key); ok {
  450. v := value.(*Client)
  451. if v.NoDisplay {
  452. continue
  453. }
  454. if clientId != 0 && clientId != v.Id {
  455. continue
  456. }
  457. if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search)) {
  458. continue
  459. }
  460. cnt++
  461. if start--; start < 0 {
  462. if length--; length > 0 {
  463. list = append(list, v)
  464. }
  465. }
  466. }
  467. }
  468. return list, cnt
  469. }
  470. func (s *Csv) IsPubClient(id int) bool {
  471. client, err := s.GetClient(id)
  472. if err == nil {
  473. return client.NoDisplay
  474. }
  475. return false
  476. }
  477. func (s *Csv) GetClient(id int) (c *Client, err error) {
  478. if v, ok := s.Clients.Load(id); ok {
  479. c = v.(*Client)
  480. return
  481. }
  482. err = errors.New("未找到客户端")
  483. return
  484. }
  485. func (s *Csv) GetClientIdByVkey(vkey string) (id int, err error) {
  486. var exist bool
  487. s.Clients.Range(func(key, value interface{}) bool {
  488. v := value.(*Client)
  489. if crypt.Md5(v.VerifyKey) == vkey {
  490. exist = true
  491. id = v.Id
  492. return false
  493. }
  494. return true
  495. })
  496. if exist {
  497. return
  498. }
  499. err = errors.New("未找到客户端")
  500. return
  501. }
  502. func (s *Csv) GetHostById(id int) (h *Host, err error) {
  503. if v, ok := s.Hosts.Load(id); ok {
  504. h = v.(*Host)
  505. return
  506. }
  507. err = errors.New("The host could not be parsed")
  508. return
  509. }
  510. //get key by host from x
  511. func (s *Csv) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
  512. var hosts []*Host
  513. //Handling Ported Access
  514. host = common.GetIpByAddr(host)
  515. s.Hosts.Range(func(key, value interface{}) bool {
  516. v := value.(*Host)
  517. if v.IsClose {
  518. return true
  519. }
  520. //Remove http(s) http(s)://a.proxy.com
  521. //*.proxy.com *.a.proxy.com Do some pan-parsing
  522. tmp := strings.Replace(v.Host, "*", `\w+?`, -1)
  523. var re *regexp.Regexp
  524. if re, err = regexp.Compile(tmp); err != nil {
  525. return true
  526. }
  527. if len(re.FindAllString(host, -1)) > 0 && (v.Scheme == "all" || v.Scheme == r.URL.Scheme) {
  528. //URL routing
  529. hosts = append(hosts, v)
  530. }
  531. return true
  532. })
  533. for _, v := range hosts {
  534. //If not set, default matches all
  535. if v.Location == "" {
  536. v.Location = "/"
  537. }
  538. if strings.Index(r.RequestURI, v.Location) == 0 {
  539. if h == nil || (len(v.Location) > len(h.Location)) {
  540. h = v
  541. }
  542. }
  543. }
  544. if h != nil {
  545. return
  546. }
  547. err = errors.New("The host could not be parsed")
  548. return
  549. }
  550. func (s *Csv) StoreClientsToCsv() {
  551. // 创建文件
  552. csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "clients.csv"))
  553. if err != nil {
  554. logs.Error(err.Error())
  555. }
  556. defer csvFile.Close()
  557. writer := csv.NewWriter(csvFile)
  558. s.Clients.Range(func(key, value interface{}) bool {
  559. client := value.(*Client)
  560. if client.NoStore {
  561. return true
  562. }
  563. record := []string{
  564. strconv.Itoa(client.Id),
  565. client.VerifyKey,
  566. client.Remark,
  567. strconv.FormatBool(client.Status),
  568. client.Cnf.U,
  569. client.Cnf.P,
  570. common.GetStrByBool(client.Cnf.Crypt),
  571. strconv.FormatBool(client.Cnf.Compress),
  572. strconv.Itoa(client.RateLimit),
  573. strconv.Itoa(int(client.Flow.FlowLimit)),
  574. strconv.Itoa(int(client.MaxConn)),
  575. common.GetStrByBool(client.ConfigConnAllow),
  576. client.WebUserName,
  577. client.WebPassword,
  578. }
  579. err := writer.Write(record)
  580. if err != nil {
  581. logs.Error(err.Error())
  582. }
  583. return true
  584. })
  585. writer.Flush()
  586. }