conn.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. package conn
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "errors"
  7. "github.com/cnlh/nps/lib/common"
  8. "github.com/cnlh/nps/lib/config"
  9. "github.com/cnlh/nps/lib/file"
  10. "github.com/cnlh/nps/lib/pool"
  11. "github.com/cnlh/nps/lib/rate"
  12. "github.com/cnlh/nps/vender/github.com/xtaci/kcp"
  13. "io"
  14. "net"
  15. "net/http"
  16. "net/url"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. )
  22. const cryptKey = "1234567812345678"
  23. type Conn struct {
  24. Conn net.Conn
  25. sync.Mutex
  26. }
  27. //new conn
  28. func NewConn(conn net.Conn) *Conn {
  29. c := new(Conn)
  30. c.Conn = conn
  31. return c
  32. }
  33. //从tcp报文中解析出host,连接类型等
  34. func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
  35. var b [32 * 1024]byte
  36. var n int
  37. if n, err = s.Read(b[:]); err != nil {
  38. return
  39. }
  40. rb = b[:n]
  41. r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
  42. if err != nil {
  43. return
  44. }
  45. hostPortURL, err := url.Parse(r.Host)
  46. if err != nil {
  47. address = r.Host
  48. err = nil
  49. return
  50. }
  51. if hostPortURL.Opaque == "443" { //https访问
  52. if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
  53. address = r.Host + ":443"
  54. } else {
  55. address = r.Host
  56. }
  57. } else { //http访问
  58. if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
  59. address = r.Host + ":80"
  60. } else {
  61. address = r.Host
  62. }
  63. }
  64. return
  65. }
  66. func (s *Conn) GetLenContent() (b []byte, err error) {
  67. var l int
  68. if l, err = s.GetLen(); err != nil {
  69. return
  70. }
  71. b, err = s.ReadLen(l)
  72. return
  73. }
  74. //读取指定长度内容
  75. func (s *Conn) ReadLen(cLen int) ([]byte, error) {
  76. if cLen > pool.PoolSize {
  77. return nil, errors.New("长度错误" + strconv.Itoa(cLen))
  78. }
  79. var buf []byte
  80. if cLen < pool.PoolSizeSmall {
  81. buf = pool.BufPoolSmall.Get().([]byte)[:cLen]
  82. //TODO 回收
  83. //defer pool.PutBufPoolSmall(buf)
  84. } else {
  85. buf = pool.BufPoolMax.Get().([]byte)[:cLen]
  86. //defer pool.PutBufPoolMax(buf)
  87. }
  88. if n, err := io.ReadFull(s, buf); err != nil || n != cLen {
  89. return buf, errors.New("Error reading specified length " + err.Error())
  90. }
  91. return buf, nil
  92. }
  93. //read length or id (content length=4)
  94. func (s *Conn) GetLen() (int, error) {
  95. var l int32
  96. err := binary.Read(s, binary.LittleEndian, &l)
  97. return int(l), err
  98. }
  99. func (s *Conn) WriteLenContent(buf []byte) (err error) {
  100. var b []byte
  101. if b, err = GetLenBytes(buf); err != nil {
  102. return
  103. }
  104. return binary.Write(s.Conn, binary.LittleEndian, b)
  105. }
  106. //read flag
  107. func (s *Conn) ReadFlag() (string, error) {
  108. val, err := s.ReadLen(4)
  109. if err != nil {
  110. return "", err
  111. }
  112. return string(val), err
  113. }
  114. //read connect status
  115. func (s *Conn) GetConnStatus() (id int, status bool, err error) {
  116. id, err = s.GetLen()
  117. if err != nil {
  118. return
  119. }
  120. var b []byte
  121. if b, err = s.ReadLen(1); err != nil {
  122. return
  123. } else {
  124. status = common.GetBoolByStr(string(b[0]))
  125. }
  126. return
  127. }
  128. //设置连接为长连接
  129. func (s *Conn) SetAlive(tp string) {
  130. if tp == "kcp" {
  131. s.setKcpAlive()
  132. } else {
  133. s.setTcpAlive()
  134. }
  135. }
  136. //设置连接为长连接
  137. func (s *Conn) setTcpAlive() {
  138. conn := s.Conn.(*net.TCPConn)
  139. conn.SetReadDeadline(time.Time{})
  140. conn.SetKeepAlive(true)
  141. conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
  142. }
  143. //设置连接为长连接
  144. func (s *Conn) setKcpAlive() {
  145. conn := s.Conn.(*kcp.UDPSession)
  146. conn.SetReadDeadline(time.Time{})
  147. }
  148. //设置连接为长连接
  149. func (s *Conn) SetReadDeadline(t time.Duration, tp string) {
  150. if tp == "kcp" {
  151. s.SetKcpReadDeadline(t)
  152. } else {
  153. s.SetTcpReadDeadline(t)
  154. }
  155. }
  156. //set read dead time
  157. func (s *Conn) SetTcpReadDeadline(t time.Duration) {
  158. s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  159. }
  160. //set read dead time
  161. func (s *Conn) SetKcpReadDeadline(t time.Duration) {
  162. s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  163. }
  164. //单独读(加密|压缩)
  165. func (s *Conn) ReadFrom(b []byte, compress int, crypt bool, rate *rate.Rate) (int, error) {
  166. if common.COMPRESS_SNAPY_DECODE == compress {
  167. return NewSnappyConn(s.Conn, crypt, rate).Read(b)
  168. }
  169. return NewCryptConn(s.Conn, crypt, rate).Read(b)
  170. }
  171. //单独写(加密|压缩)
  172. func (s *Conn) WriteTo(b []byte, compress int, crypt bool, rate *rate.Rate) (n int, err error) {
  173. if common.COMPRESS_SNAPY_ENCODE == compress {
  174. return NewSnappyConn(s.Conn, crypt, rate).Write(b)
  175. }
  176. return NewCryptConn(s.Conn, crypt, rate).Write(b)
  177. }
  178. //send msg
  179. func (s *Conn) SendMsg(content []byte, link *Link) (n int, err error) {
  180. /*
  181. The msg info is formed as follows:
  182. +----+--------+
  183. |id | content |
  184. +----+--------+
  185. | 4 | ... |
  186. +----+--------+
  187. */
  188. s.Lock()
  189. defer s.Unlock()
  190. if err = binary.Write(s.Conn, binary.LittleEndian, int32(link.Id)); err != nil {
  191. return
  192. }
  193. n, err = s.WriteTo(content, link.En, link.Crypt, link.Rate)
  194. return
  195. }
  196. //get msg content from conn
  197. func (s *Conn) GetMsgContent(link *Link) (content []byte, err error) {
  198. s.Lock()
  199. defer s.Unlock()
  200. buf := pool.BufPoolCopy.Get().([]byte)
  201. if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil {
  202. content = buf[:n]
  203. }
  204. return
  205. }
  206. //send info for link
  207. func (s *Conn) SendLinkInfo(link *Link) (int, error) {
  208. /*
  209. The link info is formed as follows:
  210. +----------+------+----------+------+----------+-----+
  211. | id | len | type | hostlen | host | en | de |crypt |
  212. +----------+------+----------+------+---------+------+
  213. | 4 | 4 | 3 | 4 | host | 1 | 1 | 1 |
  214. +----------+------+----------+------+----+----+------+
  215. */
  216. raw := bytes.NewBuffer([]byte{})
  217. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONN))
  218. binary.Write(raw, binary.LittleEndian, int32(14+len(link.Host)))
  219. binary.Write(raw, binary.LittleEndian, int32(link.Id))
  220. binary.Write(raw, binary.LittleEndian, []byte(link.ConnType))
  221. binary.Write(raw, binary.LittleEndian, int32(len(link.Host)))
  222. binary.Write(raw, binary.LittleEndian, []byte(link.Host))
  223. binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.En)))
  224. binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.De)))
  225. binary.Write(raw, binary.LittleEndian, []byte(common.GetStrByBool(link.Crypt)))
  226. s.Lock()
  227. defer s.Unlock()
  228. return s.Write(raw.Bytes())
  229. }
  230. func (s *Conn) GetLinkInfo() (lk *Link, err error) {
  231. s.Lock()
  232. defer s.Unlock()
  233. var hostLen, n int
  234. var buf []byte
  235. if n, err = s.GetLen(); err != nil {
  236. return
  237. }
  238. lk = new(Link)
  239. if buf, err = s.ReadLen(n); err != nil {
  240. return
  241. }
  242. if lk.Id, err = GetLenByBytes(buf[:4]); err != nil {
  243. return
  244. }
  245. lk.ConnType = string(buf[4:7])
  246. if hostLen, err = GetLenByBytes(buf[7:11]); err != nil {
  247. return
  248. } else {
  249. lk.Host = string(buf[11 : 11+hostLen])
  250. lk.En = common.GetIntNoErrByStr(string(buf[11+hostLen]))
  251. lk.De = common.GetIntNoErrByStr(string(buf[12+hostLen]))
  252. lk.Crypt = common.GetBoolByStr(string(buf[13+hostLen]))
  253. lk.MsgCh = make(chan []byte)
  254. lk.StatusCh = make(chan bool)
  255. }
  256. return
  257. }
  258. //send host info
  259. func (s *Conn) SendHostInfo(h *file.Host) (int, error) {
  260. /*
  261. The task info is formed as follows:
  262. +----+-----+---------+
  263. |type| len | content |
  264. +----+---------------+
  265. | 4 | 4 | ... |
  266. +----+---------------+
  267. */
  268. raw := bytes.NewBuffer([]byte{})
  269. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_HOST))
  270. common.BinaryWrite(raw, h.Host, h.Target, h.HeaderChange, h.HostChange, h.Remark, h.Location)
  271. s.Lock()
  272. defer s.Unlock()
  273. return s.Write(raw.Bytes())
  274. }
  275. func (s *Conn) GetAddStatus() (b bool) {
  276. binary.Read(s.Conn, binary.LittleEndian, &b)
  277. return
  278. }
  279. func (s *Conn) WriteAddOk() error {
  280. return binary.Write(s.Conn, binary.LittleEndian, true)
  281. }
  282. func (s *Conn) WriteAddFail() error {
  283. defer s.Close()
  284. return binary.Write(s.Conn, binary.LittleEndian, false)
  285. }
  286. //get task info
  287. func (s *Conn) GetHostInfo() (h *file.Host, err error) {
  288. var l int
  289. var b []byte
  290. if l, err = s.GetLen(); err != nil {
  291. return
  292. } else if b, err = s.ReadLen(l); err != nil {
  293. return
  294. } else {
  295. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  296. h = new(file.Host)
  297. h.Id = file.GetCsvDb().GetHostId()
  298. h.Host = arr[0]
  299. h.Target = arr[1]
  300. h.HeaderChange = arr[2]
  301. h.HostChange = arr[3]
  302. h.Remark = arr[4]
  303. h.Location = arr[5]
  304. h.Flow = new(file.Flow)
  305. h.NoStore = true
  306. }
  307. return
  308. }
  309. //send task info
  310. func (s *Conn) SendConfigInfo(c *config.CommonConfig) (int, error) {
  311. /*
  312. The task info is formed as follows:
  313. +----+-----+---------+
  314. |type| len | content |
  315. +----+---------------+
  316. | 4 | 4 | ... |
  317. +----+---------------+
  318. */
  319. raw := bytes.NewBuffer([]byte{})
  320. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONF))
  321. common.BinaryWrite(raw, c.Cnf.U, c.Cnf.P, common.GetStrByBool(c.Cnf.Crypt), c.Cnf.Compress, strconv.Itoa(c.Client.RateLimit),
  322. strconv.Itoa(int(c.Client.Flow.FlowLimit)), strconv.Itoa(c.Client.MaxConn), c.Client.Remark)
  323. s.Lock()
  324. defer s.Unlock()
  325. return s.Write(raw.Bytes())
  326. }
  327. //get task info
  328. func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
  329. var l int
  330. var b []byte
  331. if l, err = s.GetLen(); err != nil {
  332. return
  333. } else if b, err = s.ReadLen(l); err != nil {
  334. return
  335. } else {
  336. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  337. c = file.NewClient("", true, false)
  338. c.Cnf.U = arr[0]
  339. c.Cnf.P = arr[1]
  340. c.Cnf.Crypt = common.GetBoolByStr(arr[2])
  341. c.Cnf.Compress = arr[3]
  342. c.RateLimit = common.GetIntNoErrByStr(arr[4])
  343. c.Flow.FlowLimit = int64(common.GetIntNoErrByStr(arr[5]))
  344. c.MaxConn = common.GetIntNoErrByStr(arr[6])
  345. c.Remark = arr[7]
  346. c.Cnf.CompressDecode, c.Cnf.CompressDecode = common.GetCompressType(arr[3])
  347. }
  348. return
  349. }
  350. //send task info
  351. func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
  352. /*
  353. The task info is formed as follows:
  354. +----+-----+---------+
  355. |type| len | content |
  356. +----+---------------+
  357. | 4 | 4 | ... |
  358. +----+---------------+
  359. */
  360. raw := bytes.NewBuffer([]byte{})
  361. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
  362. common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark, t.TargetAddr, t.Password)
  363. s.Lock()
  364. defer s.Unlock()
  365. return s.Write(raw.Bytes())
  366. }
  367. //get task info
  368. func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
  369. var l int
  370. var b []byte
  371. if l, err = s.GetLen(); err != nil {
  372. return
  373. } else if b, err = s.ReadLen(l); err != nil {
  374. return
  375. } else {
  376. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  377. t = new(file.Tunnel)
  378. t.Mode = arr[0]
  379. t.Ports = arr[1]
  380. t.Target = arr[2]
  381. t.Id = file.GetCsvDb().GetTaskId()
  382. t.Status = true
  383. t.Flow = new(file.Flow)
  384. t.Remark = arr[3]
  385. t.TargetAddr = arr[4]
  386. t.Password = arr[5]
  387. t.NoStore = true
  388. }
  389. return
  390. }
  391. func (s *Conn) WriteWriteSuccess(id int) error {
  392. return binary.Write(s.Conn, binary.LittleEndian, int32(id))
  393. }
  394. //write connect success
  395. func (s *Conn) WriteSuccess(id int) (int, error) {
  396. raw := bytes.NewBuffer([]byte{})
  397. binary.Write(raw, binary.LittleEndian, int32(id))
  398. binary.Write(raw, binary.LittleEndian, []byte("1"))
  399. s.Lock()
  400. defer s.Unlock()
  401. return s.Write(raw.Bytes())
  402. }
  403. //write connect fail
  404. func (s *Conn) WriteFail(id int) (int, error) {
  405. raw := bytes.NewBuffer([]byte{})
  406. binary.Write(raw, binary.LittleEndian, int32(id))
  407. binary.Write(raw, binary.LittleEndian, []byte("0"))
  408. s.Lock()
  409. defer s.Unlock()
  410. return s.Write(raw.Bytes())
  411. }
  412. //close
  413. func (s *Conn) Close() error {
  414. return s.Conn.Close()
  415. }
  416. //write
  417. func (s *Conn) Write(b []byte) (int, error) {
  418. return s.Conn.Write(b)
  419. }
  420. //read
  421. func (s *Conn) Read(b []byte) (int, error) {
  422. return s.Conn.Read(b)
  423. }
  424. //write error
  425. func (s *Conn) WriteError() (int, error) {
  426. return s.Write([]byte(common.RES_MSG))
  427. }
  428. //write sign flag
  429. func (s *Conn) WriteSign() (int, error) {
  430. return s.Write([]byte(common.RES_SIGN))
  431. }
  432. //write sign flag
  433. func (s *Conn) WriteClose() (int, error) {
  434. return s.Write([]byte(common.RES_CLOSE))
  435. }
  436. //write main
  437. func (s *Conn) WriteMain() (int, error) {
  438. s.Lock()
  439. defer s.Unlock()
  440. return s.Write([]byte(common.WORK_MAIN))
  441. }
  442. //write main
  443. func (s *Conn) WriteConfig() (int, error) {
  444. s.Lock()
  445. defer s.Unlock()
  446. return s.Write([]byte(common.WORK_CONFIG))
  447. }
  448. //write chan
  449. func (s *Conn) WriteChan() (int, error) {
  450. s.Lock()
  451. defer s.Unlock()
  452. return s.Write([]byte(common.WORK_CHAN))
  453. }
  454. //获取长度+内容
  455. func GetLenBytes(buf []byte) (b []byte, err error) {
  456. raw := bytes.NewBuffer([]byte{})
  457. if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
  458. return
  459. }
  460. if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
  461. return
  462. }
  463. b = raw.Bytes()
  464. return
  465. }
  466. //解析出长度
  467. func GetLenByBytes(buf []byte) (int, error) {
  468. nlen := binary.LittleEndian.Uint32(buf)
  469. if nlen <= 0 {
  470. return 0, errors.New("数据长度错误")
  471. }
  472. return int(nlen), nil
  473. }
  474. func SetUdpSession(sess *kcp.UDPSession) {
  475. sess.SetStreamMode(true)
  476. sess.SetWindowSize(1024, 1024)
  477. sess.SetReadBuffer(64 * 1024)
  478. sess.SetWriteBuffer(64 * 1024)
  479. sess.SetNoDelay(1, 10, 2, 1)
  480. sess.SetMtu(1600)
  481. sess.SetACKNoDelay(true)
  482. sess.SetWriteDelay(false)
  483. }