conn.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package conn
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/json"
  7. "errors"
  8. "github.com/cnlh/nps/lib/common"
  9. "github.com/cnlh/nps/lib/crypt"
  10. "github.com/cnlh/nps/lib/file"
  11. "github.com/cnlh/nps/lib/mux"
  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. type Conn struct {
  24. Conn net.Conn
  25. Rb []byte
  26. }
  27. //new conn
  28. func NewConn(conn net.Conn) *Conn {
  29. return &Conn{Conn: conn}
  30. }
  31. //get host 、connection type、method...from connection
  32. func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
  33. var b [32 * 1024]byte
  34. var n int
  35. if n, err = s.Read(b[:]); err != nil {
  36. return
  37. }
  38. rb = b[:n]
  39. r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
  40. if err != nil {
  41. return
  42. }
  43. hostPortURL, err := url.Parse(r.Host)
  44. if err != nil {
  45. address = r.Host
  46. err = nil
  47. return
  48. }
  49. if hostPortURL.Opaque == "443" {
  50. if strings.Index(r.Host, ":") == -1 {
  51. address = r.Host + ":443"
  52. } else {
  53. address = r.Host
  54. }
  55. } else {
  56. if strings.Index(r.Host, ":") == -1 {
  57. address = r.Host + ":80"
  58. } else {
  59. address = r.Host
  60. }
  61. }
  62. return
  63. }
  64. func (s *Conn) GetShortLenContent() (b []byte, err error) {
  65. var l int
  66. if l, err = s.GetLen(); err != nil {
  67. return
  68. }
  69. if l < 0 || l > 32<<10 {
  70. err = errors.New("read length error")
  71. return
  72. }
  73. return s.GetShortContent(l)
  74. }
  75. func (s *Conn) GetShortContent(l int) (b []byte, err error) {
  76. buf := make([]byte, l)
  77. return buf, binary.Read(s, binary.LittleEndian, &buf)
  78. }
  79. //读取指定长度内容
  80. func (s *Conn) ReadLen(cLen int, buf []byte) (int, error) {
  81. if cLen > len(buf) {
  82. return 0, errors.New("长度错误" + strconv.Itoa(cLen))
  83. }
  84. if n, err := io.ReadFull(s, buf[:cLen]); err != nil || n != cLen {
  85. return n, errors.New("Error reading specified length " + err.Error())
  86. }
  87. return cLen, nil
  88. }
  89. func (s *Conn) GetLen() (int, error) {
  90. var l int32
  91. err := binary.Read(s, binary.LittleEndian, &l)
  92. return int(l), err
  93. }
  94. func (s *Conn) WriteLenContent(buf []byte) (err error) {
  95. var b []byte
  96. if b, err = GetLenBytes(buf); err != nil {
  97. return
  98. }
  99. return binary.Write(s.Conn, binary.LittleEndian, b)
  100. }
  101. //read flag
  102. func (s *Conn) ReadFlag() (string, error) {
  103. buf := make([]byte, 4)
  104. return string(buf), binary.Read(s, binary.LittleEndian, &buf)
  105. }
  106. //set alive
  107. func (s *Conn) SetAlive(tp string) {
  108. switch s.Conn.(type) {
  109. case *kcp.UDPSession:
  110. s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Time{})
  111. case *net.TCPConn:
  112. conn := s.Conn.(*net.TCPConn)
  113. conn.SetReadDeadline(time.Time{})
  114. conn.SetKeepAlive(true)
  115. conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
  116. case *mux.PortConn:
  117. s.Conn.(*mux.PortConn).SetReadDeadline(time.Time{})
  118. }
  119. }
  120. //set read deadline
  121. func (s *Conn) SetReadDeadlineBySecond(t time.Duration) {
  122. switch s.Conn.(type) {
  123. case *kcp.UDPSession:
  124. s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  125. case *net.TCPConn:
  126. s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  127. case *mux.PortConn:
  128. s.Conn.(*mux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  129. }
  130. }
  131. //get link info from conn
  132. func (s *Conn) GetLinkInfo() (lk *Link, err error) {
  133. err = s.getInfo(&lk)
  134. return
  135. }
  136. //send info for link
  137. func (s *Conn) SendHealthInfo(info, status string) (int, error) {
  138. raw := bytes.NewBuffer([]byte{})
  139. common.BinaryWrite(raw, info, status)
  140. return s.Write(raw.Bytes())
  141. }
  142. //get health info from conn
  143. func (s *Conn) GetHealthInfo() (info string, status bool, err error) {
  144. var l int
  145. buf := common.BufPoolMax.Get().([]byte)
  146. defer common.PutBufPoolMax(buf)
  147. if l, err = s.GetLen(); err != nil {
  148. return
  149. } else if _, err = s.ReadLen(l, buf); err != nil {
  150. return
  151. } else {
  152. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  153. if len(arr) >= 2 {
  154. return arr[0], common.GetBoolByStr(arr[1]), nil
  155. }
  156. }
  157. return "", false, errors.New("receive health info error")
  158. }
  159. //get task info
  160. func (s *Conn) GetHostInfo() (h *file.Host, err error) {
  161. err = s.getInfo(&h)
  162. h.Id = int(file.GetDb().JsonDb.GetHostId())
  163. h.Flow = new(file.Flow)
  164. h.NoStore = true
  165. return
  166. }
  167. //get task info
  168. func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
  169. err = s.getInfo(&c)
  170. c.NoStore = true
  171. c.Status = true
  172. if c.Flow == nil {
  173. c.Flow = new(file.Flow)
  174. }
  175. c.NoDisplay = false
  176. return
  177. }
  178. //get task info
  179. func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
  180. err = s.getInfo(&t)
  181. t.Id = int(file.GetDb().JsonDb.GetTaskId())
  182. t.NoStore = true
  183. t.Flow = new(file.Flow)
  184. return
  185. }
  186. //send info
  187. func (s *Conn) SendInfo(t interface{}, flag string) (int, error) {
  188. /*
  189. The task info is formed as follows:
  190. +----+-----+---------+
  191. |type| len | content |
  192. +----+---------------+
  193. | 4 | 4 | ... |
  194. +----+---------------+
  195. */
  196. raw := bytes.NewBuffer([]byte{})
  197. if flag != "" {
  198. binary.Write(raw, binary.LittleEndian, []byte(flag))
  199. }
  200. b, err := json.Marshal(t)
  201. if err != nil {
  202. return 0, err
  203. }
  204. lenBytes, err := GetLenBytes(b)
  205. if err != nil {
  206. return 0, err
  207. }
  208. binary.Write(raw, binary.LittleEndian, lenBytes)
  209. return s.Write(raw.Bytes())
  210. }
  211. //get task info
  212. func (s *Conn) getInfo(t interface{}) (err error) {
  213. var l int
  214. buf := common.BufPoolMax.Get().([]byte)
  215. defer common.PutBufPoolMax(buf)
  216. if l, err = s.GetLen(); err != nil {
  217. return
  218. } else if _, err = s.ReadLen(l, buf); err != nil {
  219. return
  220. } else {
  221. json.Unmarshal(buf[:l], &t)
  222. }
  223. return
  224. }
  225. //close
  226. func (s *Conn) Close() error {
  227. return s.Conn.Close()
  228. }
  229. //write
  230. func (s *Conn) Write(b []byte) (int, error) {
  231. return s.Conn.Write(b)
  232. }
  233. //read
  234. func (s *Conn) Read(b []byte) (n int, err error) {
  235. if s.Rb != nil {
  236. //if the rb is not nil ,read rb first
  237. if len(s.Rb) > 0 {
  238. n = copy(b, s.Rb)
  239. s.Rb = s.Rb[n:]
  240. return
  241. }
  242. s.Rb = nil
  243. }
  244. return s.Conn.Read(b)
  245. }
  246. //write sign flag
  247. func (s *Conn) WriteClose() (int, error) {
  248. return s.Write([]byte(common.RES_CLOSE))
  249. }
  250. //write main
  251. func (s *Conn) WriteMain() (int, error) {
  252. return s.Write([]byte(common.WORK_MAIN))
  253. }
  254. //write main
  255. func (s *Conn) WriteConfig() (int, error) {
  256. return s.Write([]byte(common.WORK_CONFIG))
  257. }
  258. //write chan
  259. func (s *Conn) WriteChan() (int, error) {
  260. return s.Write([]byte(common.WORK_CHAN))
  261. }
  262. //get task or host result of add
  263. func (s *Conn) GetAddStatus() (b bool) {
  264. binary.Read(s.Conn, binary.LittleEndian, &b)
  265. return
  266. }
  267. func (s *Conn) WriteAddOk() error {
  268. return binary.Write(s.Conn, binary.LittleEndian, true)
  269. }
  270. func (s *Conn) WriteAddFail() error {
  271. defer s.Close()
  272. return binary.Write(s.Conn, binary.LittleEndian, false)
  273. }
  274. func (s *Conn) LocalAddr() net.Addr {
  275. return s.Conn.LocalAddr()
  276. }
  277. func (s *Conn) RemoteAddr() net.Addr {
  278. return s.Conn.RemoteAddr()
  279. }
  280. func (s *Conn) SetDeadline(t time.Time) error {
  281. return s.Conn.SetDeadline(t)
  282. }
  283. func (s *Conn) SetWriteDeadline(t time.Time) error {
  284. return s.Conn.SetWriteDeadline(t)
  285. }
  286. func (s *Conn) SetReadDeadline(t time.Time) error {
  287. return s.Conn.SetReadDeadline(t)
  288. }
  289. //get the assembled amount data(len 4 and content)
  290. func GetLenBytes(buf []byte) (b []byte, err error) {
  291. raw := bytes.NewBuffer([]byte{})
  292. if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
  293. return
  294. }
  295. if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
  296. return
  297. }
  298. b = raw.Bytes()
  299. return
  300. }
  301. //udp connection setting
  302. func SetUdpSession(sess *kcp.UDPSession) {
  303. sess.SetStreamMode(true)
  304. sess.SetWindowSize(1024, 1024)
  305. sess.SetReadBuffer(64 * 1024)
  306. sess.SetWriteBuffer(64 * 1024)
  307. sess.SetNoDelay(1, 10, 2, 1)
  308. sess.SetMtu(1600)
  309. sess.SetACKNoDelay(true)
  310. sess.SetWriteDelay(false)
  311. }
  312. //conn1 mux conn
  313. func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool, rb []byte) {
  314. var in, out int64
  315. var wg sync.WaitGroup
  316. connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
  317. if rb != nil {
  318. connHandle.Write(rb)
  319. }
  320. go func(in *int64) {
  321. wg.Add(1)
  322. *in, _ = common.CopyBuffer(connHandle, conn2)
  323. connHandle.Close()
  324. conn2.Close()
  325. wg.Done()
  326. }(&in)
  327. out, _ = common.CopyBuffer(conn2, connHandle)
  328. connHandle.Close()
  329. conn2.Close()
  330. wg.Wait()
  331. if flow != nil {
  332. flow.Add(in, out)
  333. }
  334. }
  335. //get crypt or snappy conn
  336. func GetConn(conn net.Conn, cpt, snappy bool, rt *rate.Rate, isServer bool) io.ReadWriteCloser {
  337. if cpt {
  338. if isServer {
  339. return rate.NewRateConn(crypt.NewTlsServerConn(conn), rt)
  340. }
  341. return rate.NewRateConn(crypt.NewTlsClientConn(conn), rt)
  342. } else if snappy {
  343. return rate.NewRateConn(NewSnappyConn(conn), rt)
  344. }
  345. return rate.NewRateConn(conn, rt)
  346. }
  347. type LenConn struct {
  348. conn io.Writer
  349. Len int
  350. }
  351. func NewLenConn(conn io.Writer) *LenConn {
  352. return &LenConn{conn: conn}
  353. }
  354. func (c *LenConn) Write(p []byte) (n int, err error) {
  355. n, err = c.conn.Write(p)
  356. c.Len += n
  357. return
  358. }