conn.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. func (s *Conn) GetShortLenContent() (b []byte, err error) {
  67. var l int
  68. if l, err = s.GetLen(); err != nil {
  69. return
  70. }
  71. if l < 0 || l > 32<<10 {
  72. err = errors.New("read length error")
  73. return
  74. }
  75. return s.GetShortContent(l)
  76. }
  77. func (s *Conn) GetShortContent(l int) (b []byte, err error) {
  78. buf := make([]byte, l)
  79. return buf, binary.Read(s, binary.LittleEndian, &buf)
  80. }
  81. //读取指定长度内容
  82. func (s *Conn) ReadLen(cLen int, buf []byte) (int, error) {
  83. if cLen > len(buf) {
  84. return 0, errors.New("长度错误" + strconv.Itoa(cLen))
  85. }
  86. if n, err := io.ReadFull(s, buf[:cLen]); err != nil || n != cLen {
  87. return n, errors.New("Error reading specified length " + err.Error())
  88. }
  89. return cLen, nil
  90. }
  91. func (s *Conn) GetLen() (int, error) {
  92. var l int32
  93. err := binary.Read(s, binary.LittleEndian, &l)
  94. return int(l), err
  95. }
  96. func (s *Conn) WriteLenContent(buf []byte) (err error) {
  97. var b []byte
  98. if b, err = GetLenBytes(buf); err != nil {
  99. return
  100. }
  101. return binary.Write(s.Conn, binary.LittleEndian, b)
  102. }
  103. //read flag
  104. func (s *Conn) ReadFlag() (string, error) {
  105. buf := make([]byte, 4)
  106. return string(buf), binary.Read(s, binary.LittleEndian, &buf)
  107. }
  108. //设置连接为长连接
  109. func (s *Conn) SetAlive(tp string) {
  110. if tp == "kcp" {
  111. s.setKcpAlive()
  112. } else {
  113. s.setTcpAlive()
  114. }
  115. }
  116. //设置连接为长连接
  117. func (s *Conn) setTcpAlive() {
  118. conn := s.Conn.(*net.TCPConn)
  119. conn.SetReadDeadline(time.Time{})
  120. conn.SetKeepAlive(true)
  121. conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
  122. }
  123. //设置连接为长连接
  124. func (s *Conn) setKcpAlive() {
  125. conn := s.Conn.(*kcp.UDPSession)
  126. conn.SetReadDeadline(time.Time{})
  127. }
  128. //设置连接为长连接
  129. func (s *Conn) SetReadDeadline(t time.Duration, tp string) {
  130. if tp == "kcp" {
  131. s.SetKcpReadDeadline(t)
  132. } else {
  133. s.SetTcpReadDeadline(t)
  134. }
  135. }
  136. //set read dead time
  137. func (s *Conn) SetTcpReadDeadline(t time.Duration) {
  138. s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  139. }
  140. //set read dead time
  141. func (s *Conn) SetKcpReadDeadline(t time.Duration) {
  142. s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
  143. }
  144. //send info for link
  145. func (s *Conn) SendLinkInfo(link *Link) (int, error) {
  146. raw := bytes.NewBuffer([]byte{})
  147. common.BinaryWrite(raw, link.ConnType, link.Host, common.GetStrByBool(link.Compress), common.GetStrByBool(link.Crypt), link.RemoteAddr)
  148. s.Lock()
  149. defer s.Unlock()
  150. return s.Write(raw.Bytes())
  151. }
  152. //get link info from conn
  153. func (s *Conn) GetLinkInfo() (lk *Link, err error) {
  154. lk = new(Link)
  155. var l int
  156. buf := pool.BufPoolMax.Get().([]byte)
  157. defer pool.PutBufPoolMax(buf)
  158. if l, err = s.GetLen(); err != nil {
  159. return
  160. } else if _, err = s.ReadLen(l, buf); err != nil {
  161. return
  162. } else {
  163. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  164. lk.ConnType = arr[0]
  165. lk.Host = arr[1]
  166. lk.Compress = common.GetBoolByStr(arr[2])
  167. lk.Crypt = common.GetBoolByStr(arr[3])
  168. lk.RemoteAddr = arr[4]
  169. }
  170. return
  171. }
  172. //send host info
  173. func (s *Conn) SendHostInfo(h *file.Host) (int, error) {
  174. /*
  175. The task info is formed as follows:
  176. +----+-----+---------+
  177. |type| len | content |
  178. +----+---------------+
  179. | 4 | 4 | ... |
  180. +----+---------------+
  181. */
  182. raw := bytes.NewBuffer([]byte{})
  183. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_HOST))
  184. common.BinaryWrite(raw, h.Host, h.Target, h.HeaderChange, h.HostChange, h.Remark, h.Location)
  185. s.Lock()
  186. defer s.Unlock()
  187. return s.Write(raw.Bytes())
  188. }
  189. //get task or host result of add
  190. func (s *Conn) GetAddStatus() (b bool) {
  191. binary.Read(s.Conn, binary.LittleEndian, &b)
  192. return
  193. }
  194. func (s *Conn) WriteAddOk() error {
  195. return binary.Write(s.Conn, binary.LittleEndian, true)
  196. }
  197. func (s *Conn) WriteAddFail() error {
  198. defer s.Close()
  199. return binary.Write(s.Conn, binary.LittleEndian, false)
  200. }
  201. //get task info
  202. func (s *Conn) GetHostInfo() (h *file.Host, err error) {
  203. var l int
  204. buf := pool.BufPoolMax.Get().([]byte)
  205. defer pool.PutBufPoolMax(buf)
  206. if l, err = s.GetLen(); err != nil {
  207. return
  208. } else if _, err = s.ReadLen(l, buf); err != nil {
  209. return
  210. } else {
  211. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  212. h = new(file.Host)
  213. h.Id = file.GetCsvDb().GetHostId()
  214. h.Host = arr[0]
  215. h.Target = arr[1]
  216. h.HeaderChange = arr[2]
  217. h.HostChange = arr[3]
  218. h.Remark = arr[4]
  219. h.Location = arr[5]
  220. h.Flow = new(file.Flow)
  221. h.NoStore = true
  222. }
  223. return
  224. }
  225. //send task info
  226. func (s *Conn) SendConfigInfo(c *config.CommonConfig) (int, error) {
  227. /*
  228. The task info is formed as follows:
  229. +----+-----+---------+
  230. |type| len | content |
  231. +----+---------------+
  232. | 4 | 4 | ... |
  233. +----+---------------+
  234. */
  235. raw := bytes.NewBuffer([]byte{})
  236. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONF))
  237. common.BinaryWrite(raw, c.Cnf.U, c.Cnf.P, common.GetStrByBool(c.Cnf.Crypt), common.GetStrByBool(c.Cnf.Compress), strconv.Itoa(c.Client.RateLimit),
  238. strconv.Itoa(int(c.Client.Flow.FlowLimit)), strconv.Itoa(c.Client.MaxConn), c.Client.Remark)
  239. s.Lock()
  240. defer s.Unlock()
  241. return s.Write(raw.Bytes())
  242. }
  243. //get task info
  244. func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
  245. var l int
  246. buf := pool.BufPoolMax.Get().([]byte)
  247. defer pool.PutBufPoolMax(buf)
  248. if l, err = s.GetLen(); err != nil {
  249. return
  250. } else if _, err = s.ReadLen(l, buf); err != nil {
  251. return
  252. } else {
  253. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  254. c = file.NewClient("", true, false)
  255. c.Cnf.U = arr[0]
  256. c.Cnf.P = arr[1]
  257. c.Cnf.Crypt = common.GetBoolByStr(arr[2])
  258. c.Cnf.Compress = common.GetBoolByStr(arr[3])
  259. c.RateLimit = common.GetIntNoErrByStr(arr[4])
  260. c.Flow.FlowLimit = int64(common.GetIntNoErrByStr(arr[5]))
  261. c.MaxConn = common.GetIntNoErrByStr(arr[6])
  262. c.Remark = arr[7]
  263. }
  264. return
  265. }
  266. //send task info
  267. func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
  268. /*
  269. The task info is formed as follows:
  270. +----+-----+---------+
  271. |type| len | content |
  272. +----+---------------+
  273. | 4 | 4 | ... |
  274. +----+---------------+
  275. */
  276. raw := bytes.NewBuffer([]byte{})
  277. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
  278. common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark, t.TargetAddr, t.Password, t.LocalPath, t.StripPre)
  279. s.Lock()
  280. defer s.Unlock()
  281. return s.Write(raw.Bytes())
  282. }
  283. //get task info
  284. func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
  285. var l int
  286. buf := pool.BufPoolMax.Get().([]byte)
  287. defer pool.PutBufPoolMax(buf)
  288. if l, err = s.GetLen(); err != nil {
  289. return
  290. } else if _, err = s.ReadLen(l, buf); err != nil {
  291. return
  292. } else {
  293. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  294. t = new(file.Tunnel)
  295. t.Mode = arr[0]
  296. t.Ports = arr[1]
  297. t.Target = arr[2]
  298. t.Id = file.GetCsvDb().GetTaskId()
  299. t.Status = true
  300. t.Flow = new(file.Flow)
  301. t.Remark = arr[3]
  302. t.TargetAddr = arr[4]
  303. t.Password = arr[5]
  304. t.LocalPath = arr[6]
  305. t.StripPre = arr[7]
  306. t.NoStore = true
  307. }
  308. return
  309. }
  310. //close
  311. func (s *Conn) Close() error {
  312. return s.Conn.Close()
  313. }
  314. //write
  315. func (s *Conn) Write(b []byte) (int, error) {
  316. return s.Conn.Write(b)
  317. }
  318. //read
  319. func (s *Conn) Read(b []byte) (int, error) {
  320. return s.Conn.Read(b)
  321. }
  322. //write sign flag
  323. func (s *Conn) WriteClose() (int, error) {
  324. return s.Write([]byte(common.RES_CLOSE))
  325. }
  326. //write main
  327. func (s *Conn) WriteMain() (int, error) {
  328. s.Lock()
  329. defer s.Unlock()
  330. return s.Write([]byte(common.WORK_MAIN))
  331. }
  332. //write main
  333. func (s *Conn) WriteConfig() (int, error) {
  334. s.Lock()
  335. defer s.Unlock()
  336. return s.Write([]byte(common.WORK_CONFIG))
  337. }
  338. //write chan
  339. func (s *Conn) WriteChan() (int, error) {
  340. s.Lock()
  341. defer s.Unlock()
  342. return s.Write([]byte(common.WORK_CHAN))
  343. }
  344. //获取长度+内容
  345. func GetLenBytes(buf []byte) (b []byte, err error) {
  346. raw := bytes.NewBuffer([]byte{})
  347. if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
  348. return
  349. }
  350. if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
  351. return
  352. }
  353. b = raw.Bytes()
  354. return
  355. }
  356. func SetUdpSession(sess *kcp.UDPSession) {
  357. sess.SetStreamMode(true)
  358. sess.SetWindowSize(1024, 1024)
  359. sess.SetReadBuffer(64 * 1024)
  360. sess.SetWriteBuffer(64 * 1024)
  361. sess.SetNoDelay(1, 10, 2, 1)
  362. sess.SetMtu(1600)
  363. sess.SetACKNoDelay(true)
  364. sess.SetWriteDelay(false)
  365. }
  366. //conn1 mux conn
  367. func CopyWaitGroup(conn1, conn2 io.ReadWriteCloser, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow) {
  368. var in, out int64
  369. var wg sync.WaitGroup
  370. conn1 = GetConn(conn1, crypt, snappy, rate)
  371. go func(in *int64) {
  372. wg.Add(1)
  373. *in, _ = common.CopyBuffer(conn1, conn2)
  374. conn1.Close()
  375. conn2.Close()
  376. wg.Done()
  377. }(&in)
  378. out, _ = common.CopyBuffer(conn2, conn1)
  379. conn1.Close()
  380. conn2.Close()
  381. wg.Wait()
  382. if flow != nil {
  383. flow.Add(in, out)
  384. }
  385. }
  386. //get crypt or snappy conn
  387. func GetConn(conn io.ReadWriteCloser, crypt, snappy bool, rate *rate.Rate) (io.ReadWriteCloser) {
  388. if crypt {
  389. conn = NewCryptConn(conn, true, rate)
  390. } else if snappy {
  391. conn = NewSnappyConn(conn, crypt, rate)
  392. }
  393. return conn
  394. }
  395. //read length or id (content length=4)
  396. func GetLen(reader io.Reader) (int, error) {
  397. var l int32
  398. return int(l), binary.Read(reader, binary.LittleEndian, &l)
  399. }