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