file.go 13 KB

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