conn.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. 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. if err = binary.Write(s.Conn, binary.LittleEndian, int32(link.Id)); err != nil {
  176. return
  177. }
  178. n, err = s.WriteTo(content, link.En, link.Crypt, link.Rate)
  179. return
  180. }
  181. //get msg content from conn
  182. func (s *Conn) GetMsgContent(link *Link) (content []byte, err error) {
  183. s.Lock()
  184. defer s.Unlock()
  185. buf := pool.BufPoolCopy.Get().([]byte)
  186. if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil && n > 4 {
  187. content = buf[:n]
  188. }
  189. return
  190. }
  191. //send info for link
  192. func (s *Conn) SendLinkInfo(link *Link) (int, error) {
  193. /*
  194. The link info is formed as follows:
  195. +----------+------+----------+------+----------+-----+
  196. | id | len | type | hostlen | host | en | de |crypt |
  197. +----------+------+----------+------+---------+------+
  198. | 4 | 4 | 3 | 4 | host | 1 | 1 | 1 |
  199. +----------+------+----------+------+----+----+------+
  200. */
  201. raw := bytes.NewBuffer([]byte{})
  202. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONN))
  203. binary.Write(raw, binary.LittleEndian, int32(14+len(link.Host)))
  204. binary.Write(raw, binary.LittleEndian, int32(link.Id))
  205. binary.Write(raw, binary.LittleEndian, []byte(link.ConnType))
  206. binary.Write(raw, binary.LittleEndian, int32(len(link.Host)))
  207. binary.Write(raw, binary.LittleEndian, []byte(link.Host))
  208. binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.En)))
  209. binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.De)))
  210. binary.Write(raw, binary.LittleEndian, []byte(common.GetStrByBool(link.Crypt)))
  211. s.Lock()
  212. defer s.Unlock()
  213. return s.Write(raw.Bytes())
  214. }
  215. func (s *Conn) GetLinkInfo() (lk *Link, err error) {
  216. s.Lock()
  217. defer s.Unlock()
  218. var hostLen, n int
  219. var buf []byte
  220. if n, err = s.GetLen(); err != nil {
  221. return
  222. }
  223. lk = new(Link)
  224. if buf, err = s.ReadLen(n); err != nil {
  225. return
  226. }
  227. if lk.Id, err = GetLenByBytes(buf[:4]); err != nil {
  228. return
  229. }
  230. lk.ConnType = string(buf[4:7])
  231. if hostLen, err = GetLenByBytes(buf[7:11]); err != nil {
  232. return
  233. } else {
  234. lk.Host = string(buf[11 : 11+hostLen])
  235. lk.En = common.GetIntNoErrByStr(string(buf[11+hostLen]))
  236. lk.De = common.GetIntNoErrByStr(string(buf[12+hostLen]))
  237. lk.Crypt = common.GetBoolByStr(string(buf[13+hostLen]))
  238. lk.MsgCh = make(chan []byte)
  239. lk.StatusCh = make(chan bool)
  240. }
  241. return
  242. }
  243. //send host info
  244. func (s *Conn) SendHostInfo(h *file.Host) (int, error) {
  245. /*
  246. The task info is formed as follows:
  247. +----+-----+---------+
  248. |type| len | content |
  249. +----+---------------+
  250. | 4 | 4 | ... |
  251. +----+---------------+
  252. */
  253. raw := bytes.NewBuffer([]byte{})
  254. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_HOST))
  255. common.BinaryWrite(raw, h.Host, h.Target, h.HeaderChange, h.HostChange, h.Remark, h.Location)
  256. s.Lock()
  257. defer s.Unlock()
  258. return s.Write(raw.Bytes())
  259. }
  260. func (s *Conn) GetAddStatus() (b bool) {
  261. binary.Read(s.Conn, binary.LittleEndian, &b)
  262. return
  263. }
  264. func (s *Conn) WriteAddOk() error {
  265. return binary.Write(s.Conn, binary.LittleEndian, true)
  266. }
  267. func (s *Conn) WriteAddFail() error {
  268. defer s.Close()
  269. return binary.Write(s.Conn, binary.LittleEndian, false)
  270. }
  271. //get task info
  272. func (s *Conn) GetHostInfo() (h *file.Host, err error) {
  273. var l int
  274. var b []byte
  275. if l, err = s.GetLen(); err != nil {
  276. return
  277. } else if b, err = s.ReadLen(l); err != nil {
  278. return
  279. } else {
  280. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  281. h = new(file.Host)
  282. h.Id = file.GetCsvDb().GetHostId()
  283. h.Host = arr[0]
  284. h.Target = arr[1]
  285. h.HeaderChange = arr[2]
  286. h.HostChange = arr[3]
  287. h.Remark = arr[4]
  288. h.Location = arr[5]
  289. h.Flow = new(file.Flow)
  290. h.NoStore = true
  291. }
  292. return
  293. }
  294. //send task info
  295. func (s *Conn) SendConfigInfo(c *file.Config) (int, error) {
  296. /*
  297. The task info is formed as follows:
  298. +----+-----+---------+
  299. |type| len | content |
  300. +----+---------------+
  301. | 4 | 4 | ... |
  302. +----+---------------+
  303. */
  304. raw := bytes.NewBuffer([]byte{})
  305. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONF))
  306. common.BinaryWrite(raw, c.U, c.P, common.GetStrByBool(c.Crypt), c.Compress)
  307. s.Lock()
  308. defer s.Unlock()
  309. return s.Write(raw.Bytes())
  310. }
  311. //get task info
  312. func (s *Conn) GetConfigInfo() (c *file.Config, err error) {
  313. var l int
  314. var b []byte
  315. if l, err = s.GetLen(); err != nil {
  316. return
  317. } else if b, err = s.ReadLen(l); err != nil {
  318. return
  319. } else {
  320. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  321. c = new(file.Config)
  322. c.U = arr[0]
  323. c.P = arr[1]
  324. c.Crypt = common.GetBoolByStr(arr[2])
  325. c.Compress = arr[3]
  326. c.CompressDecode, c.CompressDecode = common.GetCompressType(arr[3])
  327. }
  328. return
  329. }
  330. //send task info
  331. func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
  332. /*
  333. The task info is formed as follows:
  334. +----+-----+---------+
  335. |type| len | content |
  336. +----+---------------+
  337. | 4 | 4 | ... |
  338. +----+---------------+
  339. */
  340. raw := bytes.NewBuffer([]byte{})
  341. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
  342. common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark)
  343. s.Lock()
  344. defer s.Unlock()
  345. return s.Write(raw.Bytes())
  346. }
  347. //get task info
  348. func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
  349. var l int
  350. var b []byte
  351. if l, err = s.GetLen(); err != nil {
  352. return
  353. } else if b, err = s.ReadLen(l); err != nil {
  354. return
  355. } else {
  356. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  357. t = new(file.Tunnel)
  358. t.Mode = arr[0]
  359. t.Ports = arr[1]
  360. t.Target = arr[2]
  361. t.Id = file.GetCsvDb().GetTaskId()
  362. t.Status = true
  363. t.Flow = new(file.Flow)
  364. t.Remark = arr[3]
  365. t.NoStore = true
  366. }
  367. return
  368. }
  369. func (s *Conn) WriteWriteSuccess(id int) error {
  370. return binary.Write(s.Conn, binary.LittleEndian, int32(id))
  371. }
  372. //write connect success
  373. func (s *Conn) WriteSuccess(id int) (int, error) {
  374. raw := bytes.NewBuffer([]byte{})
  375. binary.Write(raw, binary.LittleEndian, int32(id))
  376. binary.Write(raw, binary.LittleEndian, []byte("1"))
  377. s.Lock()
  378. defer s.Unlock()
  379. return s.Write(raw.Bytes())
  380. }
  381. //write connect fail
  382. func (s *Conn) WriteFail(id int) (int, error) {
  383. raw := bytes.NewBuffer([]byte{})
  384. binary.Write(raw, binary.LittleEndian, int32(id))
  385. binary.Write(raw, binary.LittleEndian, []byte("0"))
  386. s.Lock()
  387. defer s.Unlock()
  388. return s.Write(raw.Bytes())
  389. }
  390. //close
  391. func (s *Conn) Close() error {
  392. return s.Conn.Close()
  393. }
  394. //write
  395. func (s *Conn) Write(b []byte) (int, error) {
  396. return s.Conn.Write(b)
  397. }
  398. //read
  399. func (s *Conn) Read(b []byte) (int, error) {
  400. return s.Conn.Read(b)
  401. }
  402. //write error
  403. func (s *Conn) WriteError() (int, error) {
  404. return s.Write([]byte(common.RES_MSG))
  405. }
  406. //write sign flag
  407. func (s *Conn) WriteSign() (int, error) {
  408. return s.Write([]byte(common.RES_SIGN))
  409. }
  410. //write sign flag
  411. func (s *Conn) WriteClose() (int, error) {
  412. return s.Write([]byte(common.RES_CLOSE))
  413. }
  414. //write main
  415. func (s *Conn) WriteMain() (int, error) {
  416. s.Lock()
  417. defer s.Unlock()
  418. return s.Write([]byte(common.WORK_MAIN))
  419. }
  420. //write main
  421. func (s *Conn) WriteConfig() (int, error) {
  422. s.Lock()
  423. defer s.Unlock()
  424. return s.Write([]byte(common.WORK_CONFIG))
  425. }
  426. //write chan
  427. func (s *Conn) WriteChan() (int, error) {
  428. s.Lock()
  429. defer s.Unlock()
  430. return s.Write([]byte(common.WORK_CHAN))
  431. }
  432. //获取长度+内容
  433. func GetLenBytes(buf []byte) (b []byte, err error) {
  434. raw := bytes.NewBuffer([]byte{})
  435. if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
  436. return
  437. }
  438. if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
  439. return
  440. }
  441. b = raw.Bytes()
  442. return
  443. }
  444. //解析出长度
  445. func GetLenByBytes(buf []byte) (int, error) {
  446. nlen := binary.LittleEndian.Uint32(buf)
  447. if nlen <= 0 {
  448. return 0, errors.New("数据长度错误")
  449. }
  450. return int(nlen), nil
  451. }
  452. func SetUdpSession(sess *kcp.UDPSession) {
  453. sess.SetStreamMode(true)
  454. sess.SetWindowSize(1024, 1024)
  455. sess.SetReadBuffer(64 * 1024)
  456. sess.SetWriteBuffer(64 * 1024)
  457. sess.SetNoDelay(1, 10, 2, 1)
  458. sess.SetMtu(1600)
  459. sess.SetACKNoDelay(true)
  460. }