conn.go 12 KB

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