conn.go 11 KB

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