conn.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. s.Lock()
  140. defer s.Unlock()
  141. return s.Write(raw.Bytes())
  142. }
  143. //get link info from conn
  144. func (s *Conn) GetLinkInfo() (lk *Link, err error) {
  145. lk = new(Link)
  146. var l int
  147. buf := pool.BufPoolMax.Get().([]byte)
  148. defer pool.PutBufPoolMax(buf)
  149. if l, err = s.GetLen(); err != nil {
  150. return
  151. } else if _, err = s.ReadLen(l, buf); err != nil {
  152. return
  153. } else {
  154. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  155. lk.ConnType = arr[0]
  156. lk.Host = arr[1]
  157. lk.Compress = common.GetBoolByStr(arr[2])
  158. lk.Crypt = common.GetBoolByStr(arr[3])
  159. lk.RemoteAddr = arr[4]
  160. }
  161. return
  162. }
  163. //send host info
  164. func (s *Conn) SendHostInfo(h *file.Host) (int, error) {
  165. /*
  166. The task info is formed as follows:
  167. +----+-----+---------+
  168. |type| len | content |
  169. +----+---------------+
  170. | 4 | 4 | ... |
  171. +----+---------------+
  172. */
  173. raw := bytes.NewBuffer([]byte{})
  174. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_HOST))
  175. common.BinaryWrite(raw, h.Host, h.Target, h.HeaderChange, h.HostChange, h.Remark, h.Location)
  176. s.Lock()
  177. defer s.Unlock()
  178. return s.Write(raw.Bytes())
  179. }
  180. //get task or host result of add
  181. func (s *Conn) GetAddStatus() (b bool) {
  182. binary.Read(s.Conn, binary.LittleEndian, &b)
  183. return
  184. }
  185. func (s *Conn) WriteAddOk() error {
  186. return binary.Write(s.Conn, binary.LittleEndian, true)
  187. }
  188. func (s *Conn) WriteAddFail() error {
  189. defer s.Close()
  190. return binary.Write(s.Conn, binary.LittleEndian, false)
  191. }
  192. //get task info
  193. func (s *Conn) GetHostInfo() (h *file.Host, err error) {
  194. var l int
  195. buf := pool.BufPoolMax.Get().([]byte)
  196. defer pool.PutBufPoolMax(buf)
  197. if l, err = s.GetLen(); err != nil {
  198. return
  199. } else if _, err = s.ReadLen(l, buf); err != nil {
  200. return
  201. } else {
  202. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  203. h = new(file.Host)
  204. h.Id = file.GetCsvDb().GetHostId()
  205. h.Host = arr[0]
  206. h.Target = arr[1]
  207. h.HeaderChange = arr[2]
  208. h.HostChange = arr[3]
  209. h.Remark = arr[4]
  210. h.Location = arr[5]
  211. h.Flow = new(file.Flow)
  212. h.NoStore = true
  213. }
  214. return
  215. }
  216. //send task info
  217. func (s *Conn) SendConfigInfo(c *config.CommonConfig) (int, error) {
  218. /*
  219. The task info is formed as follows:
  220. +----+-----+---------+
  221. |type| len | content |
  222. +----+---------------+
  223. | 4 | 4 | ... |
  224. +----+---------------+
  225. */
  226. raw := bytes.NewBuffer([]byte{})
  227. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONF))
  228. common.BinaryWrite(raw, c.Cnf.U, c.Cnf.P, common.GetStrByBool(c.Cnf.Crypt), common.GetStrByBool(c.Cnf.Compress), strconv.Itoa(c.Client.RateLimit),
  229. strconv.Itoa(int(c.Client.Flow.FlowLimit)), strconv.Itoa(c.Client.MaxConn), c.Client.Remark)
  230. s.Lock()
  231. defer s.Unlock()
  232. return s.Write(raw.Bytes())
  233. }
  234. //get task info
  235. func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
  236. var l int
  237. buf := pool.BufPoolMax.Get().([]byte)
  238. defer pool.PutBufPoolMax(buf)
  239. if l, err = s.GetLen(); err != nil {
  240. return
  241. } else if _, err = s.ReadLen(l, buf); err != nil {
  242. return
  243. } else {
  244. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  245. c = file.NewClient("", true, false)
  246. c.Cnf.U = arr[0]
  247. c.Cnf.P = arr[1]
  248. c.Cnf.Crypt = common.GetBoolByStr(arr[2])
  249. c.Cnf.Compress = common.GetBoolByStr(arr[3])
  250. c.RateLimit = common.GetIntNoErrByStr(arr[4])
  251. c.Flow.FlowLimit = int64(common.GetIntNoErrByStr(arr[5]))
  252. c.MaxConn = common.GetIntNoErrByStr(arr[6])
  253. c.Remark = arr[7]
  254. }
  255. return
  256. }
  257. //send task info
  258. func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
  259. /*
  260. The task info is formed as follows:
  261. +----+-----+---------+
  262. |type| len | content |
  263. +----+---------------+
  264. | 4 | 4 | ... |
  265. +----+---------------+
  266. */
  267. raw := bytes.NewBuffer([]byte{})
  268. binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
  269. common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark, t.TargetAddr, t.Password, t.LocalPath, t.StripPre)
  270. s.Lock()
  271. defer s.Unlock()
  272. return s.Write(raw.Bytes())
  273. }
  274. //get task info
  275. func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
  276. var l int
  277. buf := pool.BufPoolMax.Get().([]byte)
  278. defer pool.PutBufPoolMax(buf)
  279. if l, err = s.GetLen(); err != nil {
  280. return
  281. } else if _, err = s.ReadLen(l, buf); err != nil {
  282. return
  283. } else {
  284. arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
  285. t = new(file.Tunnel)
  286. t.Mode = arr[0]
  287. t.Ports = arr[1]
  288. t.Target = arr[2]
  289. t.Id = file.GetCsvDb().GetTaskId()
  290. t.Status = true
  291. t.Flow = new(file.Flow)
  292. t.Remark = arr[3]
  293. t.TargetAddr = arr[4]
  294. t.Password = arr[5]
  295. t.LocalPath = arr[6]
  296. t.StripPre = arr[7]
  297. t.NoStore = true
  298. }
  299. return
  300. }
  301. //close
  302. func (s *Conn) Close() error {
  303. return s.Conn.Close()
  304. }
  305. //write
  306. func (s *Conn) Write(b []byte) (int, error) {
  307. return s.Conn.Write(b)
  308. }
  309. //read
  310. func (s *Conn) Read(b []byte) (int, error) {
  311. return s.Conn.Read(b)
  312. }
  313. //write sign flag
  314. func (s *Conn) WriteClose() (int, error) {
  315. return s.Write([]byte(common.RES_CLOSE))
  316. }
  317. //write main
  318. func (s *Conn) WriteMain() (int, error) {
  319. s.Lock()
  320. defer s.Unlock()
  321. return s.Write([]byte(common.WORK_MAIN))
  322. }
  323. //write main
  324. func (s *Conn) WriteConfig() (int, error) {
  325. s.Lock()
  326. defer s.Unlock()
  327. return s.Write([]byte(common.WORK_CONFIG))
  328. }
  329. //write chan
  330. func (s *Conn) WriteChan() (int, error) {
  331. s.Lock()
  332. defer s.Unlock()
  333. return s.Write([]byte(common.WORK_CHAN))
  334. }
  335. //获取长度+内容
  336. func GetLenBytes(buf []byte) (b []byte, err error) {
  337. raw := bytes.NewBuffer([]byte{})
  338. if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
  339. return
  340. }
  341. if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
  342. return
  343. }
  344. b = raw.Bytes()
  345. return
  346. }
  347. func SetUdpSession(sess *kcp.UDPSession) {
  348. sess.SetStreamMode(true)
  349. sess.SetWindowSize(1024, 1024)
  350. sess.SetReadBuffer(64 * 1024)
  351. sess.SetWriteBuffer(64 * 1024)
  352. sess.SetNoDelay(1, 10, 2, 1)
  353. sess.SetMtu(1600)
  354. sess.SetACKNoDelay(true)
  355. sess.SetWriteDelay(false)
  356. }
  357. //conn1 mux conn
  358. func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool) {
  359. var in, out int64
  360. var wg sync.WaitGroup
  361. connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
  362. go func(in *int64) {
  363. wg.Add(1)
  364. *in, _ = common.CopyBuffer(connHandle, conn2)
  365. connHandle.Close()
  366. conn2.Close()
  367. wg.Done()
  368. }(&in)
  369. out, _ = common.CopyBuffer(conn2, connHandle)
  370. connHandle.Close()
  371. conn2.Close()
  372. wg.Wait()
  373. if flow != nil {
  374. flow.Add(in, out)
  375. }
  376. }
  377. //get crypt or snappy conn
  378. func GetConn(conn net.Conn, cpt, snappy bool, rate *rate.Rate, isServer bool) (io.ReadWriteCloser) {
  379. if cpt {
  380. if isServer {
  381. return crypt.NewTlsServerConn(conn)
  382. }
  383. return crypt.NewTlsClientConn(conn)
  384. } else if snappy {
  385. return NewSnappyConn(conn, cpt, rate)
  386. }
  387. return conn
  388. }
  389. //read length or id (content length=4)
  390. func GetLen(reader io.Reader) (int, error) {
  391. var l int32
  392. return int(l), binary.Read(reader, binary.LittleEndian, &l)
  393. }