1
0

file.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. }
  242. post.Flow = new(Flow)
  243. post.Flow.FlowLimit = int64(common.GetIntNoErrByStr(item[9]))
  244. if len(item) >= 12 {
  245. post.ConfigConnAllow = common.GetBoolByStr(item[11])
  246. } else {
  247. post.ConfigConnAllow = true
  248. }
  249. s.Clients.Store(post.Id, post)
  250. }
  251. }
  252. func (s *Csv) LoadHostFromCsv() {
  253. path := filepath.Join(s.RunPath, "conf", "hosts.csv")
  254. records, err := s.openFile(path)
  255. if err != nil {
  256. logs.Error("Profile Opening Error:", path)
  257. os.Exit(0)
  258. }
  259. // 将每一行数据保存到内存slice中
  260. for _, item := range records {
  261. post := &Host{
  262. Host: item[0],
  263. Target: item[1],
  264. HeaderChange: item[3],
  265. HostChange: item[4],
  266. Remark: item[5],
  267. Location: item[6],
  268. Id: common.GetIntNoErrByStr(item[7]),
  269. }
  270. if post.Client, err = s.GetClient(common.GetIntNoErrByStr(item[2])); err != nil {
  271. continue
  272. }
  273. post.Flow = new(Flow)
  274. post.Flow.ExportFlow = int64(common.GetIntNoErrByStr(item[8]))
  275. post.Flow.InletFlow = int64(common.GetIntNoErrByStr(item[9]))
  276. if len(item) > 10 {
  277. post.Scheme = item[10]
  278. } else {
  279. post.Scheme = "all"
  280. }
  281. s.Hosts.Store(post.Id, post)
  282. if post.Id > int(s.HostIncreaseId) {
  283. s.HostIncreaseId = int32(post.Id)
  284. }
  285. //store host to hostMap if the host url is none
  286. }
  287. }
  288. func (s *Csv) DelHost(id int) error {
  289. s.Hosts.Delete(id)
  290. s.StoreHostToCsv()
  291. return nil
  292. }
  293. func (s *Csv) GetMapLen(m sync.Map) int {
  294. var c int
  295. m.Range(func(key, value interface{}) bool {
  296. c++
  297. return true
  298. })
  299. return c
  300. }
  301. func (s *Csv) IsHostExist(h *Host) bool {
  302. var exist bool
  303. s.Hosts.Range(func(key, value interface{}) bool {
  304. v := value.(*Host)
  305. if v.Host == h.Host && h.Location == v.Location && (v.Scheme == "all" || v.Scheme == h.Scheme) {
  306. exist = true
  307. return false
  308. }
  309. return true
  310. })
  311. return exist
  312. }
  313. func (s *Csv) NewHost(t *Host) error {
  314. if s.IsHostExist(t) {
  315. return errors.New("host has exist")
  316. }
  317. if t.Location == "" {
  318. t.Location = "/"
  319. }
  320. t.Flow = new(Flow)
  321. s.Hosts.Store(t.Id, t)
  322. s.StoreHostToCsv()
  323. return nil
  324. }
  325. func (s *Csv) GetHost(start, length int, id int, search string) ([]*Host, int) {
  326. list := make([]*Host, 0)
  327. var cnt int
  328. keys := common.GetMapKeys(s.Hosts)
  329. for _, key := range keys {
  330. if value, ok := s.Hosts.Load(key); ok {
  331. v := value.(*Host)
  332. if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search)) {
  333. continue
  334. }
  335. if id == 0 || v.Client.Id == id {
  336. cnt++
  337. if start--; start < 0 {
  338. if length--; length > 0 {
  339. list = append(list, v)
  340. }
  341. }
  342. }
  343. }
  344. }
  345. return list, cnt
  346. }
  347. func (s *Csv) DelClient(id int) error {
  348. s.Clients.Delete(id)
  349. s.StoreClientsToCsv()
  350. return nil
  351. }
  352. func (s *Csv) NewClient(c *Client) error {
  353. var isNotSet bool
  354. reset:
  355. if c.VerifyKey == "" || isNotSet {
  356. isNotSet = true
  357. c.VerifyKey = crypt.GetRandomString(16)
  358. }
  359. if !s.VerifyVkey(c.VerifyKey, c.id) {
  360. if isNotSet {
  361. goto reset
  362. }
  363. return errors.New("Vkey duplicate, please reset")
  364. }
  365. if c.Id == 0 {
  366. c.Id = int(s.GetClientId())
  367. }
  368. if c.Flow == nil {
  369. c.Flow = new(Flow)
  370. }
  371. s.Clients.Store(c.Id, c)
  372. s.StoreClientsToCsv()
  373. return nil
  374. }
  375. func (s *Csv) VerifyVkey(vkey string, id int) (res bool) {
  376. res = true
  377. s.Clients.Range(func(key, value interface{}) bool {
  378. v := value.(*Client)
  379. if v.VerifyKey == vkey && v.Id != id {
  380. res = false
  381. return false
  382. }
  383. return true
  384. })
  385. return res
  386. }
  387. func (s *Csv) GetClientId() int32 {
  388. return atomic.AddInt32(&s.ClientIncreaseId, 1)
  389. }
  390. func (s *Csv) GetTaskId() int32 {
  391. return atomic.AddInt32(&s.TaskIncreaseId, 1)
  392. }
  393. func (s *Csv) GetHostId() int32 {
  394. return atomic.AddInt32(&s.HostIncreaseId, 1)
  395. }
  396. func (s *Csv) UpdateClient(t *Client) error {
  397. s.Clients.Store(t.Id, t)
  398. return nil
  399. }
  400. func (s *Csv) GetClientList(start, length int, search string) ([]*Client, int) {
  401. list := make([]*Client, 0)
  402. var cnt int
  403. keys := common.GetMapKeys(s.Clients)
  404. for _, key := range keys {
  405. if value, ok := s.Clients.Load(key); ok {
  406. v := value.(*Client)
  407. if v.NoDisplay {
  408. continue
  409. }
  410. if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search)) {
  411. continue
  412. }
  413. cnt++
  414. if start--; start < 0 {
  415. if length--; length > 0 {
  416. list = append(list, v)
  417. }
  418. }
  419. }
  420. }
  421. return list, cnt
  422. }
  423. func (s *Csv) GetClient(id int) (c *Client, err error) {
  424. if v, ok := s.Clients.Load(id); ok {
  425. c = v.(*Client)
  426. return
  427. }
  428. err = errors.New("未找到客户端")
  429. return
  430. }
  431. func (s *Csv) GetClientIdByVkey(vkey string) (id int, err error) {
  432. var exist bool
  433. s.Clients.Range(func(key, value interface{}) bool {
  434. v := value.(*Client)
  435. if crypt.Md5(v.VerifyKey) == vkey {
  436. exist = true
  437. id = v.Id
  438. return false
  439. }
  440. return true
  441. })
  442. if exist {
  443. return
  444. }
  445. err = errors.New("未找到客户端")
  446. return
  447. }
  448. func (s *Csv) GetHostById(id int) (h *Host, err error) {
  449. if v, ok := s.Hosts.Load(id); ok {
  450. h = v.(*Host)
  451. return
  452. }
  453. err = errors.New("The host could not be parsed")
  454. return
  455. }
  456. //get key by host from x
  457. func (s *Csv) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
  458. var hosts []*Host
  459. //Handling Ported Access
  460. host = common.GetIpByAddr(host)
  461. s.Hosts.Range(func(key, value interface{}) bool {
  462. v := value.(*Host)
  463. if v.IsClose {
  464. return true
  465. }
  466. //Remove http(s) http(s)://a.proxy.com
  467. //*.proxy.com *.a.proxy.com Do some pan-parsing
  468. tmp := strings.Replace(v.Host, "*", `\w+?`, -1)
  469. var re *regexp.Regexp
  470. if re, err = regexp.Compile(tmp); err != nil {
  471. return true
  472. }
  473. if len(re.FindAllString(host, -1)) > 0 && (v.Scheme == "all" || v.Scheme == r.URL.Scheme) {
  474. //URL routing
  475. hosts = append(hosts, v)
  476. }
  477. return true
  478. })
  479. for _, v := range hosts {
  480. //If not set, default matches all
  481. if v.Location == "" {
  482. v.Location = "/"
  483. }
  484. if strings.Index(r.RequestURI, v.Location) == 0 {
  485. if h == nil || (len(v.Location) > len(h.Location)) {
  486. h = v
  487. }
  488. }
  489. }
  490. if h != nil {
  491. return
  492. }
  493. err = errors.New("The host could not be parsed")
  494. return
  495. }
  496. func (s *Csv) StoreClientsToCsv() {
  497. // 创建文件
  498. csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "clients.csv"))
  499. if err != nil {
  500. logs.Error(err.Error())
  501. }
  502. defer csvFile.Close()
  503. writer := csv.NewWriter(csvFile)
  504. s.Clients.Range(func(key, value interface{}) bool {
  505. client := value.(*Client)
  506. if client.NoStore {
  507. return true
  508. }
  509. record := []string{
  510. strconv.Itoa(client.Id),
  511. client.VerifyKey,
  512. client.Remark,
  513. strconv.FormatBool(client.Status),
  514. client.Cnf.U,
  515. client.Cnf.P,
  516. common.GetStrByBool(client.Cnf.Crypt),
  517. strconv.FormatBool(client.Cnf.Compress),
  518. strconv.Itoa(client.RateLimit),
  519. strconv.Itoa(int(client.Flow.FlowLimit)),
  520. strconv.Itoa(int(client.MaxConn)),
  521. common.GetStrByBool(client.ConfigConnAllow),
  522. }
  523. err := writer.Write(record)
  524. if err != nil {
  525. logs.Error(err.Error())
  526. }
  527. return true
  528. })
  529. writer.Flush()
  530. }