file.go 10 KB

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