conn.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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/crypt"
  10. "github.com/cnlh/nps/lib/file"
  11. "github.com/cnlh/nps/lib/pool"
  12. "github.com/cnlh/nps/lib/rate"
  13. "github.com/cnlh/nps/vender/github.com/xtaci/kcp"
  14. "io"
  15. "net"
  16. "net/http"
  17. "net/url"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. const cryptKey = "1234567812345678"
  24. type Conn struct {
  25. Conn net.Conn
  26. sync.Mutex
  27. }
  28. //new conn
  29. func NewConn(conn net.Conn) *Conn {
  30. c := new(Conn)
  31. c.Conn = conn
  32. return c
  33. }
  34. //从tcp报文中解析出host,连接类型等
  35. func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
  36. var b [32 * 1024]byte
  37. var n int
  38. if n, err = s.Read(b[:]); err != nil {
  39. return
  40. }
  41. rb = b[:n]
  42. r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
  43. if err != nil {
  44. return
  45. }
  46. hostPortURL, err := url.Parse(r.Host)
  47. if err != nil {
  48. address = r.Host
  49. err = nil
  50. return
  51. }
  52. if hostPortURL.Opaque == "443" { //https访问
  53. if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
  54. address = r.Host + ":443"
  55. } else {
  56. address = r.Host
  57. }
  58. } else { //http访问
  59. if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
  60. address = r.Host + ":80"
  61. } else {
  62. address = r.Host
  63. }
  64. }
  65. return
  66. }
  67. //读取指定长度内容
  68. func (s *Conn) ReadLen(cLen int) ([]byte, error) {
  69. if cLen > pool.PoolSize {
  70. return nil, errors.New("长度错误" + strconv.Itoa(cLen))
  71. }
  72. var buf []byte
  73. if cLen < pool.PoolSizeSmall {
  74. buf = pool.BufPoolSmall.Get().([]byte)[:cLen]
  75. defer pool.PutBufPoolSmall(buf)
  76. } else {
  77. buf = pool.BufPoolMax.Get().([]byte)[:cLen]
  78. defer pool.PutBufPoolMax(buf)
  79. }
  80. if n, err := io.ReadFull(s, buf); err != nil || n != cLen {
  81. return buf, errors.New("Error reading specified length " + err.Error())
  82. }
  83. return buf, nil
  84. }
  85. //read length or id (content length=4)
  86. func (s *Conn) GetLen() (int, error) {
  87. var l int32
  88. err := binary.Read(s, binary.LittleEndian, &l)
  89. return int(l), err
  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 {
  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 *config.CommonConfig) (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.Cnf.U, c.Cnf.P, common.GetStrByBool(c.Cnf.Crypt), c.Cnf.Compress, strconv.Itoa(c.Client.RateLimit),
  307. strconv.Itoa(int(c.Client.Flow.FlowLimit)), strconv.Itoa(c.Client.MaxConn), c.Client.Remark)
  308. s.Lock()
  309. defer s.Unlock()
  310. return s.Write(raw.Bytes())
  311. }
  312. //get task info
  313. func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
  314. var l int
  315. var b []byte
  316. if l, err = s.GetLen(); err != nil {
  317. return
  318. } else if b, err = s.ReadLen(l); err != nil {
  319. return
  320. } else {
  321. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  322. c = file.NewClient(crypt.GetRandomString(16), true, false)
  323. c.Cnf.U = arr[0]
  324. c.Cnf.P = arr[1]
  325. c.Cnf.Crypt = common.GetBoolByStr(arr[2])
  326. c.Cnf.Compress = arr[3]
  327. c.RateLimit = common.GetIntNoErrByStr(arr[4])
  328. c.Flow.FlowLimit = int64(common.GetIntNoErrByStr(arr[5]))
  329. c.MaxConn = common.GetIntNoErrByStr(arr[6])
  330. c.Remark = arr[7]
  331. c.Cnf.CompressDecode, c.Cnf.CompressDecode = common.GetCompressType(arr[3])
  332. }
  333. return
  334. }
  335. //send task info
  336. func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
  337. /*
  338. The task info is formed as follows:
  339. +----+-----+---------+
  340. |type| len | content |
  341. +----+---------------+
  342. | 4 | 4 | ... |
  343. +----+---------------+
  344. */
  345. raw := bytes.NewBuffer([]byte{})
  346. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
  347. common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark, t.TargetAddr, t.Password)
  348. s.Lock()
  349. defer s.Unlock()
  350. return s.Write(raw.Bytes())
  351. }
  352. //get task info
  353. func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
  354. var l int
  355. var b []byte
  356. if l, err = s.GetLen(); err != nil {
  357. return
  358. } else if b, err = s.ReadLen(l); err != nil {
  359. return
  360. } else {
  361. arr := strings.Split(string(b), common.CONN_DATA_SEQ)
  362. t = new(file.Tunnel)
  363. t.Mode = arr[0]
  364. t.Ports = arr[1]
  365. t.Target = arr[2]
  366. t.Id = file.GetCsvDb().GetTaskId()
  367. t.Status = true
  368. t.Flow = new(file.Flow)
  369. t.Remark = arr[3]
  370. t.TargetAddr = arr[4]
  371. t.Password = arr[5]
  372. t.NoStore = true
  373. }
  374. return
  375. }
  376. func (s *Conn) WriteWriteSuccess(id int) error {
  377. return binary.Write(s.Conn, binary.LittleEndian, int32(id))
  378. }
  379. //write connect success
  380. func (s *Conn) WriteSuccess(id int) (int, error) {
  381. raw := bytes.NewBuffer([]byte{})
  382. binary.Write(raw, binary.LittleEndian, int32(id))
  383. binary.Write(raw, binary.LittleEndian, []byte("1"))
  384. s.Lock()
  385. defer s.Unlock()
  386. return s.Write(raw.Bytes())
  387. }
  388. //write connect fail
  389. func (s *Conn) WriteFail(id int) (int, error) {
  390. raw := bytes.NewBuffer([]byte{})
  391. binary.Write(raw, binary.LittleEndian, int32(id))
  392. binary.Write(raw, binary.LittleEndian, []byte("0"))
  393. s.Lock()
  394. defer s.Unlock()
  395. return s.Write(raw.Bytes())
  396. }
  397. //close
  398. func (s *Conn) Close() error {
  399. return s.Conn.Close()
  400. }
  401. //write
  402. func (s *Conn) Write(b []byte) (int, error) {
  403. return s.Conn.Write(b)
  404. }
  405. //read
  406. func (s *Conn) Read(b []byte) (int, error) {
  407. return s.Conn.Read(b)
  408. }
  409. //write error
  410. func (s *Conn) WriteError() (int, error) {
  411. return s.Write([]byte(common.RES_MSG))
  412. }
  413. //write sign flag
  414. func (s *Conn) WriteSign() (int, error) {
  415. return s.Write([]byte(common.RES_SIGN))
  416. }
  417. //write sign flag
  418. func (s *Conn) WriteClose() (int, error) {
  419. return s.Write([]byte(common.RES_CLOSE))
  420. }
  421. //write main
  422. func (s *Conn) WriteMain() (int, error) {
  423. s.Lock()
  424. defer s.Unlock()
  425. return s.Write([]byte(common.WORK_MAIN))
  426. }
  427. //write main
  428. func (s *Conn) WriteConfig() (int, error) {
  429. s.Lock()
  430. defer s.Unlock()
  431. return s.Write([]byte(common.WORK_CONFIG))
  432. }
  433. //write chan
  434. func (s *Conn) WriteChan() (int, error) {
  435. s.Lock()
  436. defer s.Unlock()
  437. return s.Write([]byte(common.WORK_CHAN))
  438. }
  439. //获取长度+内容
  440. func GetLenBytes(buf []byte) (b []byte, err error) {
  441. raw := bytes.NewBuffer([]byte{})
  442. if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
  443. return
  444. }
  445. if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
  446. return
  447. }
  448. b = raw.Bytes()
  449. return
  450. }
  451. //解析出长度
  452. func GetLenByBytes(buf []byte) (int, error) {
  453. nlen := binary.LittleEndian.Uint32(buf)
  454. if nlen <= 0 {
  455. return 0, errors.New("数据长度错误")
  456. }
  457. return int(nlen), nil
  458. }
  459. func SetUdpSession(sess *kcp.UDPSession) {
  460. sess.SetStreamMode(true)
  461. sess.SetWindowSize(1024, 1024)
  462. sess.SetReadBuffer(64 * 1024)
  463. sess.SetWriteBuffer(64 * 1024)
  464. sess.SetNoDelay(1, 10, 2, 1)
  465. sess.SetMtu(1600)
  466. sess.SetACKNoDelay(true)
  467. }