file.go 11 KB

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