conn.go 12 KB

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