conn.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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/mux"
  12. "github.com/cnlh/nps/lib/pool"
  13. "github.com/cnlh/nps/lib/rate"
  14. "github.com/cnlh/nps/vender/github.com/xtaci/kcp"
  15. "io"
  16. "net"
  17. "net/http"
  18. "net/url"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. )
  24. const cryptKey = "1234567812345678"
  25. type Conn struct {
  26. Conn net.Conn
  27. sync.Mutex
  28. }
  29. //new conn
  30. func NewConn(conn net.Conn) *Conn {
  31. c := new(Conn)
  32. c.Conn = conn
  33. return c
  34. }
  35. //从tcp报文中解析出host,连接类型等
  36. func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
  37. var b [32 * 1024]byte
  38. var n int
  39. if n, err = s.Read(b[:]); err != nil {
  40. return
  41. }
  42. rb = b[:n]
  43. r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
  44. if err != nil {
  45. return
  46. }
  47. hostPortURL, err := url.Parse(r.Host)
  48. if err != nil {
  49. address = r.Host
  50. err = nil
  51. return
  52. }
  53. if hostPortURL.Opaque == "443" { //https访问
  54. if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
  55. address = r.Host + ":443"
  56. } else {
  57. address = r.Host
  58. }
  59. } else { //http访问
  60. if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
  61. address = r.Host + ":80"
  62. } else {
  63. address = r.Host
  64. }
  65. }
  66. return
  67. }
  68. func (s *Conn) GetShortLenContent() (b []byte, err error) {
  69. var l int
  70. if l, err = s.GetLen(); err != nil {
  71. return
  72. }
  73. if l < 0 || l > 32<<10 {
  74. err = errors.New("read length error")
  75. return
  76. }
  77. return s.GetShortContent(l)
  78. }
  79. func (s *Conn) GetShortContent(l int) (b []byte, err error) {
  80. buf := make([]byte, l)
  81. return buf, binary.Read(s, binary.LittleEndian, &buf)
  82. }
  83. //读取指定长度内容
  84. func (s *Conn) ReadLen(cLen int, buf []byte) (int, error) {
  85. if cLen > len(buf) {
  86. return 0, errors.New("长度错误" + strconv.Itoa(cLen))
  87. }
  88. if n, err := io.ReadFull(s, buf[:cLen]); err != nil || n != cLen {
  89. return n, errors.New("Error reading specified length " + err.Error())
  90. }
  91. return cLen, nil
  92. }
  93. func (s *Conn) GetLen() (int, error) {
  94. var l int32
  95. err := binary.Read(s, binary.LittleEndian, &l)
  96. return int(l), err
  97. }
  98. func (s *Conn) WriteLenContent(buf []byte) (err error) {
  99. var b []byte
  100. if b, err = GetLenBytes(buf); err != nil {
  101. return
  102. }
  103. return binary.Write(s.Conn, binary.LittleEndian, b)
  104. }
  105. //read flag
  106. func (s *Conn) ReadFlag() (string, error) {
  107. buf := make([]byte, 4)
  108. return string(buf), binary.Read(s, binary.LittleEndian, &buf)
  109. }
  110. //设置连接为长连接
  111. func (s *Conn) SetAlive(tp string) {
  112. switch s.Conn.(type) {
  113. case *kcp.UDPSession:
  114. s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Time{})
  115. case *net.TCPConn:
  116. conn := s.Conn.(*net.TCPConn)
  117. conn.SetReadDeadline(time.Time{})
  118. conn.SetKeepAlive(true)
  119. conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
  120. case *mux.PortConn:
  121. s.Conn.(*mux.PortConn).SetReadDeadline(time.Time{})
  122. }
  123. }
  124. //设置连接为长连接
  125. func (s *Conn) SetReadDeadline(t time.Duration, tp string) {
  126. switch s.Conn.(type) {
  127. case *kcp.UDPSession:
  128. s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  129. case *net.TCPConn:
  130. s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  131. case *mux.PortConn:
  132. s.Conn.(*mux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  133. }
  134. }
  135. //send info for link
  136. func (s *Conn) SendLinkInfo(link *Link) (int, error) {
  137. raw := bytes.NewBuffer([]byte{})
  138. common.BinaryWrite(raw, link.ConnType, link.Host, common.GetStrByBool(link.Compress), common.GetStrByBool(link.Crypt), link.RemoteAddr)
  139. return s.Write(raw.Bytes())
  140. }
  141. //get link info from conn
  142. func (s *Conn) GetLinkInfo() (lk *Link, err error) {
  143. lk = new(Link)
  144. var l int
  145. buf := pool.BufPoolMax.Get().([]byte)
  146. defer pool.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. lk.ConnType = arr[0]
  154. lk.Host = arr[1]
  155. lk.Compress = common.GetBoolByStr(arr[2])
  156. lk.Crypt = common.GetBoolByStr(arr[3])
  157. lk.RemoteAddr = arr[4]
  158. }
  159. return
  160. }
  161. //send info for link
  162. func (s *Conn) SendHealthInfo(info, status string) (int, error) {
  163. raw := bytes.NewBuffer([]byte{})
  164. common.BinaryWrite(raw, info, status)
  165. s.Lock()
  166. defer s.Unlock()
  167. return s.Write(raw.Bytes())
  168. }
  169. //get health info from conn
  170. func (s *Conn) GetHealthInfo() (info string, status bool, err error) {
  171. var l int
  172. buf := pool.BufPoolMax.Get().([]byte)
  173. defer pool.PutBufPoolMax(buf)
  174. if l, err = s.GetLen(); err != nil {
  175. return
  176. } else if _, err = s.ReadLen(l, buf); err != nil {
  177. return
  178. } else {
  179. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  180. if len(arr) >= 2 {
  181. return arr[0], common.GetBoolByStr(arr[1]), nil
  182. }
  183. }
  184. return "", false, errors.New("receive health info error")
  185. }
  186. //send host info
  187. func (s *Conn) SendHostInfo(h *file.Host) (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. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_HOST))
  198. common.BinaryWrite(raw, h.Host, h.Target, h.HeaderChange, h.HostChange, h.Remark, h.Location, h.Scheme)
  199. s.Lock()
  200. defer s.Unlock()
  201. return s.Write(raw.Bytes())
  202. }
  203. //get task or host result of add
  204. func (s *Conn) GetAddStatus() (b bool) {
  205. binary.Read(s.Conn, binary.LittleEndian, &b)
  206. return
  207. }
  208. func (s *Conn) WriteAddOk() error {
  209. return binary.Write(s.Conn, binary.LittleEndian, true)
  210. }
  211. func (s *Conn) WriteAddFail() error {
  212. defer s.Close()
  213. return binary.Write(s.Conn, binary.LittleEndian, false)
  214. }
  215. //get task info
  216. func (s *Conn) GetHostInfo() (h *file.Host, err error) {
  217. var l int
  218. buf := pool.BufPoolMax.Get().([]byte)
  219. defer pool.PutBufPoolMax(buf)
  220. if l, err = s.GetLen(); err != nil {
  221. return
  222. } else if _, err = s.ReadLen(l, buf); err != nil {
  223. return
  224. } else {
  225. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  226. h = new(file.Host)
  227. h.Id = file.GetCsvDb().GetHostId()
  228. h.Host = arr[0]
  229. h.Target = arr[1]
  230. h.HeaderChange = arr[2]
  231. h.HostChange = arr[3]
  232. h.Remark = arr[4]
  233. h.Location = arr[5]
  234. h.Scheme = arr[6]
  235. if h.Scheme == "" {
  236. h.Scheme = "all"
  237. }
  238. h.Flow = new(file.Flow)
  239. h.NoStore = true
  240. }
  241. return
  242. }
  243. //send task info
  244. func (s *Conn) SendConfigInfo(c *config.CommonConfig) (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_CONF))
  255. common.BinaryWrite(raw, c.Cnf.U, c.Cnf.P, common.GetStrByBool(c.Cnf.Crypt), common.GetStrByBool(c.Cnf.Compress), strconv.Itoa(c.Client.RateLimit),
  256. strconv.Itoa(int(c.Client.Flow.FlowLimit)), strconv.Itoa(c.Client.MaxConn), c.Client.Remark)
  257. s.Lock()
  258. defer s.Unlock()
  259. return s.Write(raw.Bytes())
  260. }
  261. //get task info
  262. func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
  263. var l int
  264. buf := pool.BufPoolMax.Get().([]byte)
  265. defer pool.PutBufPoolMax(buf)
  266. if l, err = s.GetLen(); err != nil {
  267. return
  268. } else if _, err = s.ReadLen(l, buf); err != nil {
  269. return
  270. } else {
  271. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  272. c = file.NewClient("", true, false)
  273. c.Cnf.U = arr[0]
  274. c.Cnf.P = arr[1]
  275. c.Cnf.Crypt = common.GetBoolByStr(arr[2])
  276. c.Cnf.Compress = common.GetBoolByStr(arr[3])
  277. c.RateLimit = common.GetIntNoErrByStr(arr[4])
  278. c.Flow.FlowLimit = int64(common.GetIntNoErrByStr(arr[5]))
  279. c.MaxConn = common.GetIntNoErrByStr(arr[6])
  280. c.Remark = arr[7]
  281. }
  282. return
  283. }
  284. //send task info
  285. func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
  286. /*
  287. The task info is formed as follows:
  288. +----+-----+---------+
  289. |type| len | content |
  290. +----+---------------+
  291. | 4 | 4 | ... |
  292. +----+---------------+
  293. */
  294. raw := bytes.NewBuffer([]byte{})
  295. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
  296. common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark, t.TargetAddr, t.Password, t.LocalPath, t.StripPre)
  297. s.Lock()
  298. defer s.Unlock()
  299. return s.Write(raw.Bytes())
  300. }
  301. //get task info
  302. func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
  303. var l int
  304. buf := pool.BufPoolMax.Get().([]byte)
  305. defer pool.PutBufPoolMax(buf)
  306. if l, err = s.GetLen(); err != nil {
  307. return
  308. } else if _, err = s.ReadLen(l, buf); err != nil {
  309. return
  310. } else {
  311. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  312. t = new(file.Tunnel)
  313. t.Mode = arr[0]
  314. t.Ports = arr[1]
  315. t.Target = arr[2]
  316. t.Id = file.GetCsvDb().GetTaskId()
  317. t.Status = true
  318. t.Flow = new(file.Flow)
  319. t.Remark = arr[3]
  320. t.TargetAddr = arr[4]
  321. t.Password = arr[5]
  322. t.LocalPath = arr[6]
  323. t.StripPre = arr[7]
  324. t.NoStore = true
  325. }
  326. return
  327. }
  328. //close
  329. func (s *Conn) Close() error {
  330. return s.Conn.Close()
  331. }
  332. //write
  333. func (s *Conn) Write(b []byte) (int, error) {
  334. return s.Conn.Write(b)
  335. }
  336. //read
  337. func (s *Conn) Read(b []byte) (int, error) {
  338. return s.Conn.Read(b)
  339. }
  340. //write sign flag
  341. func (s *Conn) WriteClose() (int, error) {
  342. return s.Write([]byte(common.RES_CLOSE))
  343. }
  344. //write main
  345. func (s *Conn) WriteMain() (int, error) {
  346. s.Lock()
  347. defer s.Unlock()
  348. return s.Write([]byte(common.WORK_MAIN))
  349. }
  350. //write main
  351. func (s *Conn) WriteConfig() (int, error) {
  352. s.Lock()
  353. defer s.Unlock()
  354. return s.Write([]byte(common.WORK_CONFIG))
  355. }
  356. //write chan
  357. func (s *Conn) WriteChan() (int, error) {
  358. s.Lock()
  359. defer s.Unlock()
  360. return s.Write([]byte(common.WORK_CHAN))
  361. }
  362. //获取长度+内容
  363. func GetLenBytes(buf []byte) (b []byte, err error) {
  364. raw := bytes.NewBuffer([]byte{})
  365. if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
  366. return
  367. }
  368. if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
  369. return
  370. }
  371. b = raw.Bytes()
  372. return
  373. }
  374. func SetUdpSession(sess *kcp.UDPSession) {
  375. sess.SetStreamMode(true)
  376. sess.SetWindowSize(1024, 1024)
  377. sess.SetReadBuffer(64 * 1024)
  378. sess.SetWriteBuffer(64 * 1024)
  379. sess.SetNoDelay(1, 10, 2, 1)
  380. sess.SetMtu(1600)
  381. sess.SetACKNoDelay(true)
  382. sess.SetWriteDelay(false)
  383. }
  384. //conn1 mux conn
  385. func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool) {
  386. var in, out int64
  387. var wg sync.WaitGroup
  388. connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
  389. go func(in *int64) {
  390. wg.Add(1)
  391. *in, _ = common.CopyBuffer(connHandle, conn2)
  392. connHandle.Close()
  393. conn2.Close()
  394. wg.Done()
  395. }(&in)
  396. out, _ = common.CopyBuffer(conn2, connHandle)
  397. connHandle.Close()
  398. conn2.Close()
  399. wg.Wait()
  400. if flow != nil {
  401. flow.Add(in, out)
  402. }
  403. }
  404. //get crypt or snappy conn
  405. func GetConn(conn net.Conn, cpt, snappy bool, rate *rate.Rate, isServer bool) (io.ReadWriteCloser) {
  406. if cpt {
  407. if isServer {
  408. return crypt.NewTlsServerConn(conn)
  409. }
  410. return crypt.NewTlsClientConn(conn)
  411. } else if snappy {
  412. return NewSnappyConn(conn, cpt, rate)
  413. }
  414. return conn
  415. }
  416. //read length or id (content length=4)
  417. func GetLen(reader io.Reader) (int, error) {
  418. var l int32
  419. return int(l), binary.Read(reader, binary.LittleEndian, &l)
  420. }