nps/lib/conn/conn.go

432 lines
9.2 KiB
Go
Raw Normal View History

2019-02-09 09:07:47 +00:00
package conn
2018-11-29 11:55:24 +00:00
import (
2018-12-11 08:37:12 +00:00
"bufio"
2018-11-29 11:55:24 +00:00
"bytes"
2020-01-08 13:57:14 +00:00
"ehang.io/nps/lib/goroutine"
2018-11-29 11:55:24 +00:00
"encoding/binary"
2019-03-30 08:35:43 +00:00
"encoding/json"
2018-11-29 11:55:24 +00:00
"errors"
2019-11-09 15:02:29 +00:00
"github.com/astaxie/beego/logs"
2019-01-03 16:21:23 +00:00
"io"
2018-11-29 11:55:24 +00:00
"net"
2018-12-11 08:37:12 +00:00
"net/http"
2018-11-30 18:38:29 +00:00
"net/url"
2018-12-11 08:37:12 +00:00
"strconv"
2018-11-30 18:38:29 +00:00
"strings"
"sync"
2018-11-29 11:55:24 +00:00
"time"
2019-08-10 03:15:25 +00:00
2020-01-08 13:57:14 +00:00
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/file"
2020-01-09 14:59:24 +00:00
"ehang.io/nps/lib/pmux"
2020-01-08 13:57:14 +00:00
"ehang.io/nps/lib/rate"
2019-08-10 03:15:25 +00:00
"github.com/xtaci/kcp-go"
2018-11-29 11:55:24 +00:00
)
type Conn struct {
2019-01-09 12:33:00 +00:00
Conn net.Conn
2019-03-30 04:03:17 +00:00
Rb []byte
2018-11-29 11:55:24 +00:00
}
2019-01-03 16:21:23 +00:00
//new conn
2018-11-29 11:55:24 +00:00
func NewConn(conn net.Conn) *Conn {
2019-03-29 02:41:57 +00:00
return &Conn{Conn: conn}
2018-11-29 11:55:24 +00:00
}
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
2020-02-11 06:01:16 +00:00
if n < 4 {
continue
}
if string(buf[n-4:n]) == "\r\n\r\n" {
return
}
// buf is full, can't contain the request
if n == cap(buf) {
err = io.ErrUnexpectedEOF
return
}
}
}
2019-03-29 02:41:57 +00:00
//get host 、connection type、method...from connection
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
}
2019-03-29 02:41:57 +00:00
if hostPortURL.Opaque == "443" {
if strings.Index(r.Host, ":") == -1 {
2019-02-02 16:54:43 +00:00
address = r.Host + ":443"
} else {
address = r.Host
}
2019-03-29 02:41:57 +00:00
} else {
if strings.Index(r.Host, ":") == -1 {
address = r.Host + ":80"
} else {
address = r.Host
}
}
return
}
func (s *Conn) GetShortLenContent() (b []byte, err error) {
2019-02-26 14:40:28 +00:00
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)
2019-02-26 14:40:28 +00:00
}
2019-01-03 16:21:23 +00:00
//读取指定长度内容
func (s *Conn) ReadLen(cLen int, buf []byte) (int, error) {
2019-12-03 19:56:04 +00:00
if cLen > len(buf) || cLen <= 0 {
return 0, errors.New("长度错误" + strconv.Itoa(cLen))
2019-01-12 16:09:12 +00:00
}
if n, err := io.ReadFull(s, buf[:cLen]); err != nil || n != cLen {
return n, errors.New("Error reading specified length " + err.Error())
2018-11-29 11:55:24 +00:00
}
return cLen, nil
2018-11-29 11:55:24 +00:00
}
func (s *Conn) GetLen() (int, error) {
2019-02-17 17:05:05 +00:00
var l int32
err := binary.Read(s, binary.LittleEndian, &l)
return int(l), err
2018-11-29 11:55:24 +00:00
}
2019-02-26 14:40:28 +00:00
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)
}
//read flag
2018-11-29 11:55:24 +00:00
func (s *Conn) ReadFlag() (string, error) {
buf := make([]byte, 4)
return string(buf), binary.Read(s, binary.LittleEndian, &buf)
2018-11-29 11:55:24 +00:00
}
2019-03-29 02:41:57 +00:00
//set alive
2019-02-09 09:07:47 +00:00
func (s *Conn) SetAlive(tp string) {
2019-03-05 01:23:18 +00:00
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{})
//conn.SetKeepAlive(false)
//conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
2020-01-09 14:59:24 +00:00
case *pmux.PortConn:
s.Conn.(*pmux.PortConn).SetReadDeadline(time.Time{})
2019-02-09 09:07:47 +00:00
}
}
2019-03-29 02:41:57 +00:00
//set read deadline
2019-03-30 08:35:43 +00:00
func (s *Conn) SetReadDeadlineBySecond(t time.Duration) {
2019-03-05 01:23:18 +00:00
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))
2020-01-09 14:59:24 +00:00
case *pmux.PortConn:
s.Conn.(*pmux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
2019-02-09 09:07:47 +00:00
}
}
//get link info from conn
2019-02-09 09:07:47 +00:00
func (s *Conn) GetLinkInfo() (lk *Link, err error) {
2019-03-30 08:35:43 +00:00
err = s.getInfo(&lk)
2019-02-09 09:07:47 +00:00
return
}
2019-03-15 06:03:49 +00:00
//send info for link
func (s *Conn) SendHealthInfo(info, status string) (int, error) {
raw := bytes.NewBuffer([]byte{})
common.BinaryWrite(raw, info, status)
return s.Write(raw.Bytes())
}
//get health info from conn
func (s *Conn) GetHealthInfo() (info string, status bool, err error) {
var l int
buf := common.BufPoolMax.Get().([]byte)
defer common.PutBufPoolMax(buf)
2019-03-15 06:03:49 +00:00
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")
}
2019-02-12 19:54:00 +00:00
//get task info
func (s *Conn) GetHostInfo() (h *file.Host, err error) {
2019-03-30 08:35:43 +00:00
err = s.getInfo(&h)
h.Id = int(file.GetDb().JsonDb.GetHostId())
h.Flow = new(file.Flow)
h.NoStore = true
2019-02-12 19:54:00 +00:00
return
}
//get task info
2019-02-23 15:29:48 +00:00
func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
2019-03-30 08:35:43 +00:00
err = s.getInfo(&c)
c.NoStore = true
c.Status = true
if c.Flow == nil {
c.Flow = new(file.Flow)
2019-02-12 19:54:00 +00:00
}
2019-03-30 08:35:43 +00:00
c.NoDisplay = false
return
}
//get task info
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)
2019-02-12 19:54:00 +00:00
return
}
2019-03-30 08:35:43 +00:00
//send info
func (s *Conn) SendInfo(t interface{}, flag string) (int, error) {
2019-02-09 09:07:47 +00:00
/*
The task info is formed as follows:
+----+-----+---------+
|type| len | content |
+----+---------------+
| 4 | 4 | ... |
+----+---------------+
2019-02-16 12:43:26 +00:00
*/
2019-02-09 09:07:47 +00:00
raw := bytes.NewBuffer([]byte{})
2019-03-30 08:35:43 +00:00
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)
2019-02-09 09:07:47 +00:00
return s.Write(raw.Bytes())
}
//get task info
2019-03-30 08:35:43 +00:00
func (s *Conn) getInfo(t interface{}) (err error) {
2019-02-09 09:07:47 +00:00
var l int
buf := common.BufPoolMax.Get().([]byte)
defer common.PutBufPoolMax(buf)
2019-02-09 09:07:47 +00:00
if l, err = s.GetLen(); err != nil {
return
} else if _, err = s.ReadLen(l, buf); err != nil {
2019-02-09 09:07:47 +00:00
return
} else {
2019-03-30 08:35:43 +00:00
json.Unmarshal(buf[:l], &t)
}
2018-12-11 08:37:12 +00:00
return
}
2019-01-03 16:21:23 +00:00
//close
2018-12-11 08:37:12 +00:00
func (s *Conn) Close() error {
2019-01-09 12:33:00 +00:00
return s.Conn.Close()
2018-12-11 08:37:12 +00:00
}
2019-01-03 16:21:23 +00:00
//write
2018-12-11 08:37:12 +00:00
func (s *Conn) Write(b []byte) (int, error) {
2019-01-09 12:33:00 +00:00
return s.Conn.Write(b)
2018-12-11 08:37:12 +00:00
}
2019-01-03 16:21:23 +00:00
//read
2019-03-30 04:03:17 +00:00
func (s *Conn) Read(b []byte) (n int, err error) {
if s.Rb != nil {
2019-03-30 08:35:43 +00:00
//if the rb is not nil ,read rb first
2019-03-30 04:03:17 +00:00
if len(s.Rb) > 0 {
n = copy(b, s.Rb)
s.Rb = s.Rb[n:]
return
}
s.Rb = nil
}
2019-01-09 12:33:00 +00:00
return s.Conn.Read(b)
2018-12-11 08:37:12 +00:00
}
2019-01-28 06:45:55 +00:00
//write sign flag
func (s *Conn) WriteClose() (int, error) {
2019-02-09 09:07:47 +00:00
return s.Write([]byte(common.RES_CLOSE))
2019-01-28 06:45:55 +00:00
}
2019-01-03 16:21:23 +00:00
//write main
2019-01-09 12:33:00 +00:00
func (s *Conn) WriteMain() (int, error) {
2019-02-09 09:07:47 +00:00
return s.Write([]byte(common.WORK_MAIN))
}
2018-11-29 11:55:24 +00:00
2019-02-12 19:54:00 +00:00
//write main
func (s *Conn) WriteConfig() (int, error) {
return s.Write([]byte(common.WORK_CONFIG))
}
2019-01-03 16:21:23 +00:00
//write chan
2019-01-09 12:33:00 +00:00
func (s *Conn) WriteChan() (int, error) {
2019-02-09 09:07:47 +00:00
return s.Write([]byte(common.WORK_CHAN))
2018-11-29 11:55:24 +00:00
}
2019-03-29 07:21:30 +00:00
//get task or host result of add
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)
}
2019-03-30 08:35:43 +00:00
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)
}
2019-03-29 02:41:57 +00:00
//get the assembled amount data(len 4 and content)
2019-01-02 17:44:45 +00:00
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
}
2019-03-29 02:41:57 +00:00
//udp connection setting
2019-02-09 09:07:47 +00:00
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)
2019-02-26 14:40:28 +00:00
sess.SetWriteDelay(false)
2019-02-09 09:07:47 +00:00
}
//conn1 mux conn
2019-03-25 10:39:31 +00:00
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool, rb []byte) {
2019-11-09 15:02:29 +00:00
//var in, out int64
//var wg sync.WaitGroup
2019-03-05 01:23:18 +00:00
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
2019-03-25 10:39:31 +00:00
if rb != nil {
connHandle.Write(rb)
}
2019-11-09 15:02:29 +00:00
//go func(in *int64) {
// wg.Add(1)
// *in, _ = common.CopyBuffer(connHandle, conn2)
// connHandle.Close()
// conn2.Close()
// wg.Done()
//}(&in)
//out, _ = common.CopyBuffer(conn2, connHandle)
//connHandle.Close()
//conn2.Close()
//wg.Wait()
//if flow != nil {
// flow.Add(in, out)
//}
wg := new(sync.WaitGroup)
wg.Add(1)
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow, wg))
wg.Wait()
2019-11-09 15:02:29 +00:00
if err != nil {
logs.Error(err)
}
}
//get crypt or snappy conn
func GetConn(conn net.Conn, cpt, snappy bool, rt *rate.Rate, isServer bool) io.ReadWriteCloser {
2019-03-05 01:23:18 +00:00
if cpt {
if isServer {
return rate.NewRateConn(crypt.NewTlsServerConn(conn), rt)
2019-03-05 01:23:18 +00:00
}
return rate.NewRateConn(crypt.NewTlsClientConn(conn), rt)
} else if snappy {
2019-03-29 02:41:57 +00:00
return rate.NewRateConn(NewSnappyConn(conn), rt)
}
return rate.NewRateConn(conn, rt)
}
2019-04-12 09:40:27 +00:00
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
}