nps/lib/conn/conn.go

504 lines
12 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"
"encoding/binary"
"errors"
2019-02-09 09:07:47 +00:00
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/file"
"github.com/cnlh/nps/lib/pool"
"github.com/cnlh/nps/lib/rate"
2019-02-16 12:43:26 +00:00
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
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-01-09 12:33:00 +00:00
const cryptKey = "1234567812345678"
2018-11-29 11:55:24 +00:00
type Conn struct {
2019-01-09 12:33:00 +00:00
Conn net.Conn
sync.Mutex
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 {
c := new(Conn)
2019-01-09 12:33:00 +00:00
c.Conn = conn
2018-11-29 11:55:24 +00:00
return c
}
//从tcp报文中解析出host连接类型等
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.Read(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" { //https访问
2019-02-02 16:54:43 +00:00
if strings.Index(r.Host, ":") == -1 { //host不带端口 默认80
address = r.Host + ":443"
} else {
address = r.Host
}
} else { //http访问
2019-02-02 16:54:43 +00:00
if strings.Index(r.Host, ":") == -1 { //host不带端口 默认80
address = r.Host + ":80"
} else {
address = r.Host
}
}
return
}
2019-01-03 16:21:23 +00:00
//读取指定长度内容
2019-01-06 17:52:54 +00:00
func (s *Conn) ReadLen(cLen int) ([]byte, error) {
2019-02-09 09:07:47 +00:00
if cLen > pool.PoolSize {
2019-01-11 10:10:37 +00:00
return nil, errors.New("长度错误" + strconv.Itoa(cLen))
2019-01-06 17:52:54 +00:00
}
2019-01-12 16:09:12 +00:00
var buf []byte
2019-02-17 11:36:48 +00:00
if cLen < pool.PoolSizeSmall {
2019-02-09 09:07:47 +00:00
buf = pool.BufPoolSmall.Get().([]byte)[:cLen]
2019-02-17 11:36:48 +00:00
defer pool.PutBufPoolSmall(buf)
2019-01-12 16:09:12 +00:00
} else {
2019-02-09 09:07:47 +00:00
buf = pool.BufPoolMax.Get().([]byte)[:cLen]
2019-02-17 11:36:48 +00:00
defer pool.PutBufPoolMax(buf)
2019-01-12 16:09:12 +00:00
}
2019-01-06 17:52:54 +00:00
if n, err := io.ReadFull(s, buf); err != nil || n != cLen {
2019-02-16 12:43:26 +00:00
return buf, errors.New("Error reading specified length " + err.Error())
2018-11-29 11:55:24 +00:00
}
2019-01-02 17:44:45 +00:00
return buf, nil
2018-11-29 11:55:24 +00:00
}
//read length or id (content length=4)
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
}
//read flag
2018-11-29 11:55:24 +00:00
func (s *Conn) ReadFlag() (string, error) {
2019-01-03 16:21:23 +00:00
val, err := s.ReadLen(4)
if err != nil {
2018-11-29 11:55:24 +00:00
return "", err
}
return string(val), err
}
//read connect status
func (s *Conn) GetConnStatus() (id int, status bool, err error) {
id, err = s.GetLen()
2019-01-03 16:21:23 +00:00
if err != nil {
return
}
var b []byte
if b, err = s.ReadLen(1); err != nil {
return
} else {
2019-02-09 09:07:47 +00:00
status = common.GetBoolByStr(string(b[0]))
2018-11-29 11:55:24 +00:00
}
return
2018-11-29 11:55:24 +00:00
}
//设置连接为长连接
2019-02-09 09:07:47 +00:00
func (s *Conn) SetAlive(tp string) {
if tp == "kcp" {
s.setKcpAlive()
} else {
s.setTcpAlive()
}
}
//设置连接为长连接
func (s *Conn) setTcpAlive() {
2019-01-09 12:33:00 +00:00
conn := s.Conn.(*net.TCPConn)
2018-11-29 11:55:24 +00:00
conn.SetReadDeadline(time.Time{})
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
}
2019-02-09 09:07:47 +00:00
//设置连接为长连接
func (s *Conn) setKcpAlive() {
conn := s.Conn.(*kcp.UDPSession)
conn.SetReadDeadline(time.Time{})
}
//设置连接为长连接
func (s *Conn) SetReadDeadline(t time.Duration, tp string) {
if tp == "kcp" {
s.SetKcpReadDeadline(t)
} else {
s.SetTcpReadDeadline(t)
}
}
//set read dead time
2019-02-09 09:07:47 +00:00
func (s *Conn) SetTcpReadDeadline(t time.Duration) {
2019-01-28 06:45:55 +00:00
s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
}
2019-02-09 09:07:47 +00:00
//set read dead time
func (s *Conn) SetKcpReadDeadline(t time.Duration) {
s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
}
2019-01-03 16:21:23 +00:00
//单独读(加密|压缩)
2019-02-09 09:07:47 +00:00
func (s *Conn) ReadFrom(b []byte, compress int, crypt bool, rate *rate.Rate) (int, error) {
if common.COMPRESS_SNAPY_DECODE == compress {
2019-01-28 06:45:55 +00:00
return NewSnappyConn(s.Conn, crypt, rate).Read(b)
}
2019-01-28 06:45:55 +00:00
return NewCryptConn(s.Conn, crypt, rate).Read(b)
}
2019-01-03 16:21:23 +00:00
//单独写(加密|压缩)
2019-02-09 09:07:47 +00:00
func (s *Conn) WriteTo(b []byte, compress int, crypt bool, rate *rate.Rate) (n int, err error) {
if common.COMPRESS_SNAPY_ENCODE == compress {
2019-01-28 06:45:55 +00:00
return NewSnappyConn(s.Conn, crypt, rate).Write(b)
}
2019-01-28 06:45:55 +00:00
return NewCryptConn(s.Conn, crypt, rate).Write(b)
}
2018-11-29 11:55:24 +00:00
//send msg
func (s *Conn) SendMsg(content []byte, link *Link) (n int, err error) {
/*
The msg info is formed as follows:
+----+--------+
|id | content |
+----+--------+
| 4 | ... |
+----+--------+
2019-02-16 12:43:26 +00:00
*/
s.Lock()
defer s.Unlock()
2019-02-17 11:36:48 +00:00
if err = binary.Write(s.Conn, binary.LittleEndian, int32(link.Id)); err != nil {
return
}
2019-02-17 11:36:48 +00:00
n, err = s.WriteTo(content, link.En, link.Crypt, link.Rate)
return
2018-12-11 08:37:12 +00:00
}
//get msg content from conn
func (s *Conn) GetMsgContent(link *Link) (content []byte, err error) {
s.Lock()
defer s.Unlock()
2019-02-09 09:07:47 +00:00
buf := pool.BufPoolCopy.Get().([]byte)
if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil && n > 4 {
content = buf[:n]
}
return
}
//send info for link
func (s *Conn) SendLinkInfo(link *Link) (int, error) {
/*
The link info is formed as follows:
+----------+------+----------+------+----------+-----+
| id | len | type | hostlen | host | en | de |crypt |
+----------+------+----------+------+---------+------+
| 4 | 4 | 3 | 4 | host | 1 | 1 | 1 |
+----------+------+----------+------+----+----+------+
*/
raw := bytes.NewBuffer([]byte{})
2019-02-09 09:07:47 +00:00
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONN))
binary.Write(raw, binary.LittleEndian, int32(14+len(link.Host)))
binary.Write(raw, binary.LittleEndian, int32(link.Id))
binary.Write(raw, binary.LittleEndian, []byte(link.ConnType))
binary.Write(raw, binary.LittleEndian, int32(len(link.Host)))
binary.Write(raw, binary.LittleEndian, []byte(link.Host))
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.En)))
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.De)))
2019-02-09 09:07:47 +00:00
binary.Write(raw, binary.LittleEndian, []byte(common.GetStrByBool(link.Crypt)))
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
2019-02-09 09:07:47 +00:00
func (s *Conn) GetLinkInfo() (lk *Link, err error) {
s.Lock()
defer s.Unlock()
var hostLen, n int
var buf []byte
if n, err = s.GetLen(); err != nil {
return
}
2019-02-09 09:07:47 +00:00
lk = new(Link)
if buf, err = s.ReadLen(n); err != nil {
return
}
2019-02-09 09:07:47 +00:00
if lk.Id, err = GetLenByBytes(buf[:4]); err != nil {
2019-01-03 16:21:23 +00:00
return
}
2019-02-09 09:07:47 +00:00
lk.ConnType = string(buf[4:7])
if hostLen, err = GetLenByBytes(buf[7:11]); err != nil {
return
} else {
2019-02-09 09:07:47 +00:00
lk.Host = string(buf[11 : 11+hostLen])
lk.En = common.GetIntNoErrByStr(string(buf[11+hostLen]))
lk.De = common.GetIntNoErrByStr(string(buf[12+hostLen]))
lk.Crypt = common.GetBoolByStr(string(buf[13+hostLen]))
2019-02-17 11:36:48 +00:00
lk.MsgCh = make(chan []byte)
lk.StatusCh = make(chan bool)
2019-02-09 09:07:47 +00:00
}
return
}
2019-02-12 19:54:00 +00:00
//send host info
func (s *Conn) SendHostInfo(h *file.Host) (int, error) {
/*
The task info is formed as follows:
+----+-----+---------+
|type| len | content |
+----+---------------+
| 4 | 4 | ... |
+----+---------------+
2019-02-16 12:43:26 +00:00
*/
2019-02-12 19:54:00 +00:00
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_HOST))
2019-02-16 12:43:26 +00:00
common.BinaryWrite(raw, h.Host, h.Target, h.HeaderChange, h.HostChange, h.Remark, h.Location)
2019-02-12 19:54:00 +00:00
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
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)
}
//get task info
func (s *Conn) GetHostInfo() (h *file.Host, err error) {
var l int
var b []byte
if l, err = s.GetLen(); err != nil {
return
} else if b, err = s.ReadLen(l); err != nil {
return
} else {
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
h = new(file.Host)
2019-02-16 15:18:58 +00:00
h.Id = file.GetCsvDb().GetHostId()
2019-02-12 19:54:00 +00:00
h.Host = arr[0]
h.Target = arr[1]
h.HeaderChange = arr[2]
h.HostChange = arr[3]
h.Remark = arr[4]
2019-02-16 12:43:26 +00:00
h.Location = arr[5]
2019-02-12 19:54:00 +00:00
h.Flow = new(file.Flow)
h.NoStore = true
}
return
}
//send task info
func (s *Conn) SendConfigInfo(c *file.Config) (int, error) {
/*
The task info is formed as follows:
+----+-----+---------+
|type| len | content |
+----+---------------+
| 4 | 4 | ... |
+----+---------------+
2019-02-16 12:43:26 +00:00
*/
2019-02-12 19:54:00 +00:00
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONF))
common.BinaryWrite(raw, c.U, c.P, common.GetStrByBool(c.Crypt), c.Compress)
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
//get task info
func (s *Conn) GetConfigInfo() (c *file.Config, err error) {
var l int
var b []byte
if l, err = s.GetLen(); err != nil {
return
} else if b, err = s.ReadLen(l); err != nil {
return
} else {
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
c = new(file.Config)
c.U = arr[0]
c.P = arr[1]
c.Crypt = common.GetBoolByStr(arr[2])
c.Compress = arr[3]
c.CompressDecode, c.CompressDecode = common.GetCompressType(arr[3])
}
return
}
2019-02-09 09:07:47 +00:00
//send task info
func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
/*
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-02-12 19:54:00 +00:00
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
2019-02-15 14:59:28 +00:00
common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark)
2019-02-09 09:07:47 +00:00
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
//get task info
func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
var l int
var b []byte
if l, err = s.GetLen(); err != nil {
return
} else if b, err = s.ReadLen(l); err != nil {
return
} else {
2019-02-12 19:54:00 +00:00
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
t = new(file.Tunnel)
2019-02-09 09:07:47 +00:00
t.Mode = arr[0]
2019-02-15 14:59:28 +00:00
t.Ports = arr[1]
2019-02-09 09:07:47 +00:00
t.Target = arr[2]
t.Id = file.GetCsvDb().GetTaskId()
t.Status = true
t.Flow = new(file.Flow)
2019-02-12 19:54:00 +00:00
t.Remark = arr[3]
t.NoStore = true
}
2018-12-11 08:37:12 +00:00
return
}
2019-02-17 11:36:48 +00:00
func (s *Conn) WriteWriteSuccess(id int) error {
return binary.Write(s.Conn, binary.LittleEndian, int32(id))
}
//write connect success
func (s *Conn) WriteSuccess(id int) (int, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, int32(id))
binary.Write(raw, binary.LittleEndian, []byte("1"))
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
//write connect fail
func (s *Conn) WriteFail(id int) (int, error) {
raw := bytes.NewBuffer([]byte{})
binary.Write(raw, binary.LittleEndian, int32(id))
binary.Write(raw, binary.LittleEndian, []byte("0"))
s.Lock()
defer s.Unlock()
return s.Write(raw.Bytes())
}
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
2018-12-11 08:37:12 +00:00
func (s *Conn) Read(b []byte) (int, error) {
2019-01-09 12:33:00 +00:00
return s.Conn.Read(b)
2018-12-11 08:37:12 +00:00
}
2019-01-03 16:21:23 +00:00
//write error
2019-01-09 12:33:00 +00:00
func (s *Conn) WriteError() (int, error) {
2019-02-09 09:07:47 +00:00
return s.Write([]byte(common.RES_MSG))
2018-12-06 12:45:14 +00:00
}
2018-12-11 08:37:12 +00:00
2019-01-03 16:21:23 +00:00
//write sign flag
2019-01-09 12:33:00 +00:00
func (s *Conn) WriteSign() (int, error) {
2019-02-09 09:07:47 +00:00
return s.Write([]byte(common.RES_SIGN))
2018-11-29 11:55:24 +00:00
}
2018-12-06 12:45:14 +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) {
s.Lock()
defer s.Unlock()
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) {
s.Lock()
defer s.Unlock()
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) {
s.Lock()
defer s.Unlock()
2019-02-09 09:07:47 +00:00
return s.Write([]byte(common.WORK_CHAN))
2018-11-29 11:55:24 +00:00
}
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
}
//解析出长度
func GetLenByBytes(buf []byte) (int, error) {
nlen := binary.LittleEndian.Uint32(buf)
if nlen <= 0 {
return 0, errors.New("数据长度错误")
}
return int(nlen), nil
}
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)
}