file.go 10 KB

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