1
0

file.go 12 KB

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