conn.go 11 KB

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