123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431 |
- package conn
- import (
- "bufio"
- "bytes"
- "ehang.io/nps/lib/goroutine"
- "encoding/binary"
- "encoding/json"
- "errors"
- "github.com/astaxie/beego/logs"
- "io"
- "net"
- "net/http"
- "net/url"
- "strconv"
- "strings"
- "sync"
- "time"
- "ehang.io/nps/lib/common"
- "ehang.io/nps/lib/crypt"
- "ehang.io/nps/lib/file"
- "ehang.io/nps/lib/pmux"
- "ehang.io/nps/lib/rate"
- "github.com/xtaci/kcp-go"
- )
- type Conn struct {
- Conn net.Conn
- Rb []byte
- }
- func NewConn(conn net.Conn) *Conn {
- return &Conn{Conn: conn}
- }
- func (s *Conn) readRequest(buf []byte) (n int, err error) {
- var rd int
- for {
- rd, err = s.Read(buf[n:])
- if err != nil {
- return
- }
- n += rd
- if n < 4 {
- continue
- }
- if string(buf[n-4:n]) == "\r\n\r\n" {
- return
- }
-
- if n == cap(buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- }
- }
- func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
- var b [32 * 1024]byte
- var n int
- if n, err = s.readRequest(b[:]); err != nil {
- return
- }
- rb = b[:n]
- r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
- if err != nil {
- return
- }
- hostPortURL, err := url.Parse(r.Host)
- if err != nil {
- address = r.Host
- err = nil
- return
- }
- if hostPortURL.Opaque == "443" {
- if strings.Index(r.Host, ":") == -1 {
- address = r.Host + ":443"
- } else {
- address = r.Host
- }
- } else {
- if strings.Index(r.Host, ":") == -1 {
- address = r.Host + ":80"
- } else {
- address = r.Host
- }
- }
- return
- }
- func (s *Conn) GetShortLenContent() (b []byte, err error) {
- var l int
- if l, err = s.GetLen(); err != nil {
- return
- }
- if l < 0 || l > 32<<10 {
- err = errors.New("read length error")
- return
- }
- return s.GetShortContent(l)
- }
- func (s *Conn) GetShortContent(l int) (b []byte, err error) {
- buf := make([]byte, l)
- return buf, binary.Read(s, binary.LittleEndian, &buf)
- }
- func (s *Conn) ReadLen(cLen int, buf []byte) (int, error) {
- if cLen > len(buf) || cLen <= 0 {
- return 0, errors.New("长度错误" + strconv.Itoa(cLen))
- }
- if n, err := io.ReadFull(s, buf[:cLen]); err != nil || n != cLen {
- return n, errors.New("Error reading specified length " + err.Error())
- }
- return cLen, nil
- }
- func (s *Conn) GetLen() (int, error) {
- var l int32
- err := binary.Read(s, binary.LittleEndian, &l)
- return int(l), err
- }
- func (s *Conn) WriteLenContent(buf []byte) (err error) {
- var b []byte
- if b, err = GetLenBytes(buf); err != nil {
- return
- }
- return binary.Write(s.Conn, binary.LittleEndian, b)
- }
- func (s *Conn) ReadFlag() (string, error) {
- buf := make([]byte, 4)
- return string(buf), binary.Read(s, binary.LittleEndian, &buf)
- }
- func (s *Conn) SetAlive(tp string) {
- switch s.Conn.(type) {
- case *kcp.UDPSession:
- s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Time{})
- case *net.TCPConn:
- conn := s.Conn.(*net.TCPConn)
- conn.SetReadDeadline(time.Time{})
-
-
- case *pmux.PortConn:
- s.Conn.(*pmux.PortConn).SetReadDeadline(time.Time{})
- }
- }
- func (s *Conn) SetReadDeadlineBySecond(t time.Duration) {
- switch s.Conn.(type) {
- case *kcp.UDPSession:
- s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
- case *net.TCPConn:
- s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
- case *pmux.PortConn:
- s.Conn.(*pmux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
- }
- }
- func (s *Conn) GetLinkInfo() (lk *Link, err error) {
- err = s.getInfo(&lk)
- return
- }
- func (s *Conn) SendHealthInfo(info, status string) (int, error) {
- raw := bytes.NewBuffer([]byte{})
- common.BinaryWrite(raw, info, status)
- return s.Write(raw.Bytes())
- }
- func (s *Conn) GetHealthInfo() (info string, status bool, err error) {
- var l int
- buf := common.BufPoolMax.Get().([]byte)
- defer common.PutBufPoolMax(buf)
- if l, err = s.GetLen(); err != nil {
- return
- } else if _, err = s.ReadLen(l, buf); err != nil {
- return
- } else {
- arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
- if len(arr) >= 2 {
- return arr[0], common.GetBoolByStr(arr[1]), nil
- }
- }
- return "", false, errors.New("receive health info error")
- }
- func (s *Conn) GetHostInfo() (h *file.Host, err error) {
- err = s.getInfo(&h)
- h.Id = int(file.GetDb().JsonDb.GetHostId())
- h.Flow = new(file.Flow)
- h.NoStore = true
- return
- }
- func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
- err = s.getInfo(&c)
- c.NoStore = true
- c.Status = true
- if c.Flow == nil {
- c.Flow = new(file.Flow)
- }
- c.NoDisplay = false
- return
- }
- func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
- err = s.getInfo(&t)
- t.Id = int(file.GetDb().JsonDb.GetTaskId())
- t.NoStore = true
- t.Flow = new(file.Flow)
- return
- }
- func (s *Conn) SendInfo(t interface{}, flag string) (int, error) {
-
- raw := bytes.NewBuffer([]byte{})
- if flag != "" {
- binary.Write(raw, binary.LittleEndian, []byte(flag))
- }
- b, err := json.Marshal(t)
- if err != nil {
- return 0, err
- }
- lenBytes, err := GetLenBytes(b)
- if err != nil {
- return 0, err
- }
- binary.Write(raw, binary.LittleEndian, lenBytes)
- return s.Write(raw.Bytes())
- }
- func (s *Conn) getInfo(t interface{}) (err error) {
- var l int
- buf := common.BufPoolMax.Get().([]byte)
- defer common.PutBufPoolMax(buf)
- if l, err = s.GetLen(); err != nil {
- return
- } else if _, err = s.ReadLen(l, buf); err != nil {
- return
- } else {
- json.Unmarshal(buf[:l], &t)
- }
- return
- }
- func (s *Conn) Close() error {
- return s.Conn.Close()
- }
- func (s *Conn) Write(b []byte) (int, error) {
- return s.Conn.Write(b)
- }
- func (s *Conn) Read(b []byte) (n int, err error) {
- if s.Rb != nil {
-
- if len(s.Rb) > 0 {
- n = copy(b, s.Rb)
- s.Rb = s.Rb[n:]
- return
- }
- s.Rb = nil
- }
- return s.Conn.Read(b)
- }
- func (s *Conn) WriteClose() (int, error) {
- return s.Write([]byte(common.RES_CLOSE))
- }
- func (s *Conn) WriteMain() (int, error) {
- return s.Write([]byte(common.WORK_MAIN))
- }
- func (s *Conn) WriteConfig() (int, error) {
- return s.Write([]byte(common.WORK_CONFIG))
- }
- func (s *Conn) WriteChan() (int, error) {
- return s.Write([]byte(common.WORK_CHAN))
- }
- func (s *Conn) GetAddStatus() (b bool) {
- binary.Read(s.Conn, binary.LittleEndian, &b)
- return
- }
- func (s *Conn) WriteAddOk() error {
- return binary.Write(s.Conn, binary.LittleEndian, true)
- }
- func (s *Conn) WriteAddFail() error {
- defer s.Close()
- return binary.Write(s.Conn, binary.LittleEndian, false)
- }
- func (s *Conn) LocalAddr() net.Addr {
- return s.Conn.LocalAddr()
- }
- func (s *Conn) RemoteAddr() net.Addr {
- return s.Conn.RemoteAddr()
- }
- func (s *Conn) SetDeadline(t time.Time) error {
- return s.Conn.SetDeadline(t)
- }
- func (s *Conn) SetWriteDeadline(t time.Time) error {
- return s.Conn.SetWriteDeadline(t)
- }
- func (s *Conn) SetReadDeadline(t time.Time) error {
- return s.Conn.SetReadDeadline(t)
- }
- func GetLenBytes(buf []byte) (b []byte, err error) {
- raw := bytes.NewBuffer([]byte{})
- if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
- return
- }
- if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
- return
- }
- b = raw.Bytes()
- return
- }
- func SetUdpSession(sess *kcp.UDPSession) {
- sess.SetStreamMode(true)
- sess.SetWindowSize(1024, 1024)
- sess.SetReadBuffer(64 * 1024)
- sess.SetWriteBuffer(64 * 1024)
- sess.SetNoDelay(1, 10, 2, 1)
- sess.SetMtu(1600)
- sess.SetACKNoDelay(true)
- sess.SetWriteDelay(false)
- }
- func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool, rb []byte) {
-
-
- connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
- if rb != nil {
- connHandle.Write(rb)
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- wg := new(sync.WaitGroup)
- wg.Add(1)
- err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg))
- wg.Wait()
- if err != nil {
- logs.Error(err)
- }
- }
- func GetConn(conn net.Conn, cpt, snappy bool, rt *rate.Rate, isServer bool) io.ReadWriteCloser {
- if cpt {
- if isServer {
- return rate.NewRateConn(crypt.NewTlsServerConn(conn), rt)
- }
- return rate.NewRateConn(crypt.NewTlsClientConn(conn), rt)
- } else if snappy {
- return rate.NewRateConn(NewSnappyConn(conn), rt)
- }
- return rate.NewRateConn(conn, rt)
- }
- type LenConn struct {
- conn io.Writer
- Len int
- }
- func NewLenConn(conn io.Writer) *LenConn {
- return &LenConn{conn: conn}
- }
- func (c *LenConn) Write(p []byte) (n int, err error) {
- n, err = c.conn.Write(p)
- c.Len += n
- return
- }
|