diff --git a/README.md b/README.md index c48ea58..589e032 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,13 @@ ## 更新日志 +- 2022-12-19 +***修复***:某些场景下丢包导致服务端意外退出 +***优化***:新增隧道时,不指定服务端口时,将自动生成端口号 +***优化***:API返回ID, `/client/add/, /index/addhost/,/index/add/ ` +***优化***:域名解析、隧道页面,增加[唯一验证密钥],方便搜查 + + - 2022-10-30 ***新增***:在管理面板中新增客户端时,可以配置多个黑名单IP,用于防止被肉鸡扫描端口或被恶意攻击。 ***优化***:0.26.12 版本还原了注册系统功能,使用方式和以前一样。无论是否注册了系统服务,直接执行 nps 时只会读取当前目录下的配置文件。 diff --git a/bridge/bridge.go b/bridge/bridge.go index 41568df..410c3d1 100755 --- a/bridge/bridge.go +++ b/bridge/bridge.go @@ -1,7 +1,7 @@ package bridge import ( - "ehang.io/nps-mux" + "ehang.io/nps/lib/nps_mux" "encoding/binary" "errors" "fmt" diff --git a/client/client.go b/client/client.go index b9b709b..085c2c9 100755 --- a/client/client.go +++ b/client/client.go @@ -3,7 +3,7 @@ package client import ( "bufio" "bytes" - "ehang.io/nps-mux" + "ehang.io/nps/lib/nps_mux" "net" "net/http" "strconv" diff --git a/client/local.go b/client/local.go index 9be690c..cf4d6aa 100644 --- a/client/local.go +++ b/client/local.go @@ -1,7 +1,7 @@ package client import ( - "ehang.io/nps-mux" + "ehang.io/nps/lib/nps_mux" "errors" "net" "net/http" diff --git a/go.mod b/go.mod index ed1f665..3195c39 100644 --- a/go.mod +++ b/go.mod @@ -3,13 +3,11 @@ module ehang.io/nps go 1.15 require ( - ehang.io/nps-mux v0.0.0-20210407130203-4afa0c10c992 fyne.io/fyne/v2 v2.0.2 github.com/astaxie/beego v1.12.0 github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect github.com/c4milo/unpackit v0.0.0-20170704181138-4ed373e9ef1c github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d - github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f github.com/dsnet/compress v0.0.1 // indirect github.com/golang/snappy v0.0.3 github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214 // indirect diff --git a/go.sum b/go.sum index 84616fe..61be7ae 100644 --- a/go.sum +++ b/go.sum @@ -31,8 +31,6 @@ github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGii github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f h1:q/DpyjJjZs94bziQ7YkBmIlpqbVP7yw179rnzoNVX1M= -github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f/go.mod h1:QGrK8vMWWHQYQ3QU9bw9Y9OPNfxccGzfb41qjvVeXtY= github.com/dsnet/compress v0.0.1 h1:PlZu0n3Tuv04TzpfPbrnI0HW/YwodEXDS+oPKahKF0Q= github.com/dsnet/compress v0.0.1/go.mod h1:Aw8dCMJ7RioblQeTqt88akK31OvO8Dhf5JflhBbQEHo= github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY= diff --git a/lib/file/db.go b/lib/file/db.go index 8552d5e..86cfac6 100644 --- a/lib/file/db.go +++ b/lib/file/db.go @@ -181,7 +181,7 @@ func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, in for _, key := range keys { if value, ok := s.JsonDb.Hosts.Load(key); ok { v := value.(*Host) - if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search)) { + if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Client.VerifyKey, search)) { continue } if id == 0 || v.Client.Id == id { diff --git a/lib/nps_mux/conn.go b/lib/nps_mux/conn.go new file mode 100644 index 0000000..daffcd8 --- /dev/null +++ b/lib/nps_mux/conn.go @@ -0,0 +1,692 @@ +package nps_mux + +import ( + "errors" + "io" + "log" + "math" + "net" + "runtime" + "sync" + "sync/atomic" + "time" +) + +type conn struct { + net.Conn + connStatusOkCh chan struct{} + connStatusFailCh chan struct{} + connId int32 + isClose bool + closingFlag bool // closing conn flag + receiveWindow *receiveWindow + sendWindow *sendWindow + once sync.Once +} + +func NewConn(connId int32, mux *Mux) *conn { + c := &conn{ + connStatusOkCh: make(chan struct{}), + connStatusFailCh: make(chan struct{}), + connId: connId, + receiveWindow: new(receiveWindow), + sendWindow: new(sendWindow), + once: sync.Once{}, + } + c.receiveWindow.New(mux) + c.sendWindow.New(mux) + return c +} + +func (s *conn) Read(buf []byte) (n int, err error) { + if s.isClose || buf == nil { + return 0, errors.New("the conn has closed") + } + if len(buf) == 0 { + return 0, nil + } + // waiting for takeout from receive window finish or timeout + n, err = s.receiveWindow.Read(buf, s.connId) + return +} + +func (s *conn) Write(buf []byte) (n int, err error) { + if s.isClose { + return 0, errors.New("the conn has closed") + } + if s.closingFlag { + return 0, errors.New("io: write on closed conn") + } + if len(buf) == 0 { + return 0, nil + } + n, err = s.sendWindow.WriteFull(buf, s.connId) + return +} + +func (s *conn) Close() (err error) { + s.once.Do(s.closeProcess) + return +} + +func (s *conn) closeProcess() { + s.isClose = true + s.receiveWindow.mux.connMap.Delete(s.connId) + if !s.receiveWindow.mux.IsClose { + // if server or user close the conn while reading, will Get a io.EOF + // and this Close method will be invoke, send this signal to close other side + s.receiveWindow.mux.sendInfo(muxConnClose, s.connId, nil) + } + s.sendWindow.CloseWindow() + s.receiveWindow.CloseWindow() + return +} + +func (s *conn) LocalAddr() net.Addr { + return s.receiveWindow.mux.conn.LocalAddr() +} + +func (s *conn) RemoteAddr() net.Addr { + return s.receiveWindow.mux.conn.RemoteAddr() +} + +func (s *conn) SetDeadline(t time.Time) error { + _ = s.SetReadDeadline(t) + _ = s.SetWriteDeadline(t) + return nil +} + +func (s *conn) SetReadDeadline(t time.Time) error { + s.receiveWindow.SetTimeOut(t) + return nil +} + +func (s *conn) SetWriteDeadline(t time.Time) error { + s.sendWindow.SetTimeOut(t) + return nil +} + +type window struct { + maxSizeDone uint64 + // 64bit alignment + // maxSizeDone contains 4 parts + // 1 31 1 31 + // wait maxSize useless done + // wait zero means false, one means true + off uint32 + closeOp bool + closeOpCh chan struct{} + mux *Mux +} + +const windowBits = 31 +const waitBits = dequeueBits + windowBits +const mask1 = 1 +const mask31 = 1<> dequeueBits) & mask31) + done = uint32(ptrs & mask31) + if ((ptrs >> waitBits) & mask1) == 1 { + wait = true + return + } + return +} + +func (Self *window) pack(maxSize, done uint32, wait bool) uint64 { + if wait { + return (uint64(1)< 0 { + n = uint32(l) + } + return +} + +func (Self *receiveWindow) calcSize() { + // calculating maximum receive window size + if Self.count == 0 { + muxBw := Self.mux.bw.Get() + connBw := Self.bw.Get() + latency := math.Float64frombits(atomic.LoadUint64(&Self.mux.latency)) + var n uint32 + if connBw > 0 && muxBw > 0 { + if connBw > muxBw { + connBw = muxBw + Self.bw.GrowRatio() + } + n = uint32(latency * (muxBw + connBw)) + } + if n < maximumSegmentSize*30 { + n = maximumSegmentSize * 30 + } + if n < uint32(float64(maximumSegmentSize*3000)*latency) { + // latency gain + // if there are some latency more than 10ms will trigger this gain + // network pipeline need fill more data that we can measure the max bandwidth + n = uint32(float64(maximumSegmentSize*3000) * latency) + } + for { + ptrs := atomic.LoadUint64(&Self.maxSizeDone) + size, read, wait := Self.unpack(ptrs) + rem := Self.remainingSize(size, 0) + ra := float64(rem) / float64(size) + if ra > 0.8 { + // low fill window gain + // if receive window keep low fill, maybe pipeline fill the data, we need a gain + // less than 20% fill, gain will trigger + n = uint32(float64(n) * 1.5625 * ra * ra) + } + if n < size/2 { + n = size / 2 + // half reduce + } + // set the minimal size + if n > 2*size { + if size == maximumSegmentSize*30 { + // we give more ratio when the initial window size, to reduce the time window grow up + if n > size*6 { + n = size * 6 + } + } else { + n = 2 * size + // twice grow + } + } + if connBw > 0 && muxBw > 0 { + limit := uint32(maximumWindowSize * (connBw / (muxBw + connBw))) + if n > limit { + log.Println("window too large, calculated:", n, "limit:", limit, connBw, muxBw) + n = limit + } + } + // set the maximum size + if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(n, read, wait)) { + // only change the maxSize + break + } + } + Self.count = -10 + } + Self.count += 1 + return +} + +func (Self *receiveWindow) Write(buf []byte, l uint16, part bool, id int32) (err error) { + if Self.closeOp { + return errors.New("conn.receiveWindow: write on closed window") + } + element, err := newListElement(buf, l, part) + if err != nil { + return + } + Self.calcSize() // calculate the max window size + var wait bool + var maxSize, read uint32 +start: + ptrs := atomic.LoadUint64(&Self.maxSizeDone) + maxSize, read, wait = Self.unpack(ptrs) + remain := Self.remainingSize(maxSize, l) + // calculate the remaining window size now, plus the element we will push + if remain == 0 && !wait { + wait = true + if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, read, wait)) { + // only change the wait status, not send the read size + goto start + // another goroutine change the status, make sure shall we need wait + } + } else if !wait { + if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, 0, wait)) { + // reset read size here, and send the read size directly + goto start + // another goroutine change the status, make sure shall we need wait + } + } // maybe there are still some data received even if window is full, just keep the wait status + // and push into queue. when receive window read enough, send window will be acknowledged. + Self.bufQueue.Push(element) + // status check finish, now we can push the element into the queue + if !wait { + Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false)) + // send the current status to send window + } + return nil +} + +func (Self *receiveWindow) Read(p []byte, id int32) (n int, err error) { + if Self.closeOp { + return 0, io.EOF // receive close signal, returns eof + } + Self.bw.StartRead() + n, err = Self.readFromQueue(p, id) + Self.bw.SetCopySize(uint16(n)) + return +} + +func (Self *receiveWindow) readFromQueue(p []byte, id int32) (n int, err error) { + pOff := 0 + l := 0 +copyData: + if Self.off == uint32(Self.element.L) { + // on the first Read method invoked, Self.off and Self.element.l + // both zero value + listEle.Put(Self.element) + if Self.closeOp { + return 0, io.EOF + } + Self.element, err = Self.bufQueue.Pop() + // if the queue is empty, Pop method will wait until one element push + // into the queue successful, or timeout. + // timer start on timeout parameter is set up + Self.off = 0 + if err != nil { + Self.CloseWindow() // also close the window, to avoid read twice + return // queue receive stop or time out, break the loop and return + } + } + l = copy(p[pOff:], Self.element.Buf[Self.off:Self.element.L]) + pOff += l + Self.off += uint32(l) + n += l + l = 0 + if Self.off == uint32(Self.element.L) { + windowBuff.Put(Self.element.Buf) + Self.sendStatus(id, Self.element.L) + // check the window full status + } + if pOff < len(p) && Self.element.Part { + // element is a part of the segments, trying to fill up buf p + goto copyData + } + return // buf p is full or all of segments in buf, return +} + +func (Self *receiveWindow) sendStatus(id int32, l uint16) { + var maxSize, read uint32 + var wait bool + for { + ptrs := atomic.LoadUint64(&Self.maxSizeDone) + maxSize, read, wait = Self.unpack(ptrs) + if read <= (read+uint32(l))&mask31 { + read += uint32(l) + remain := Self.remainingSize(maxSize, 0) + if wait && remain > 0 || read >= maxSize/2 || remain == maxSize { + if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, 0, false)) { + // now we get the current window status success + // receive window free up some space we need acknowledge send window, also reset the read size + // still having a condition that receive window is empty and not send the status to send window + // so send the status here + Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false)) + break + } + } else { + if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, read, wait)) { + // receive window not into the wait status, or still not having any space now, + // just change the read size + break + } + } + } else { + //overflow + if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, uint32(l), wait)) { + // reset to l + Self.mux.sendInfo(muxMsgSendOk, id, Self.pack(maxSize, read, false)) + break + } + } + runtime.Gosched() + // another goroutine change remaining or wait status, make sure + } + return +} + +func (Self *receiveWindow) SetTimeOut(t time.Time) { + // waiting for FIFO queue Pop method + Self.bufQueue.SetTimeOut(t) +} + +func (Self *receiveWindow) Stop() { + // queue has no more data to push, so unblock pop method + Self.once.Do(Self.bufQueue.Stop) +} + +func (Self *receiveWindow) CloseWindow() { + Self.window.CloseWindow() + Self.Stop() + Self.release() +} + +func (Self *receiveWindow) release() { + //if Self.element != nil { + // if Self.element.Buf != nil { + // common.WindowBuff.Put(Self.element.Buf) + // } + // common.ListElementPool.Put(Self.element) + //} + for { + ele := Self.bufQueue.TryPop() + if ele == nil { + return + } + if ele.Buf != nil { + windowBuff.Put(ele.Buf) + } + listEle.Put(ele) + } // release resource +} + +type sendWindow struct { + window + buf []byte + setSizeCh chan struct{} + timeout time.Time + // send window receive the receive window max size and read size + // done size store the size send window has send, send and read will be totally equal + // so send minus read, send window can get the current window size remaining +} + +func (Self *sendWindow) New(mux *Mux) { + Self.setSizeCh = make(chan struct{}) + Self.maxSizeDone = Self.pack(maximumSegmentSize*30, 0, false) + Self.mux = mux + Self.window.New() +} + +func (Self *sendWindow) SetSendBuf(buf []byte) { + // send window buff from conn write method, set it to send window + Self.buf = buf + Self.off = 0 +} + +func (Self *sendWindow) remainingSize(maxSize, send uint32) uint32 { + l := int64(maxSize&mask31) - int64(send&mask31) + if l > 0 { + return uint32(l) + } + return 0 +} + +func (Self *sendWindow) SetSize(currentMaxSizeDone uint64) (closed bool) { + // set the window size from receive window + defer func() { + if recover() != nil { + closed = true + } + }() + if Self.closeOp { + close(Self.setSizeCh) + return true + } + var maxsize, send uint32 + var wait, newWait bool + currentMaxSize, read, _ := Self.unpack(currentMaxSizeDone) + for { + ptrs := atomic.LoadUint64(&Self.maxSizeDone) + maxsize, send, wait = Self.unpack(ptrs) + if read > send { + log.Println("window read > send: max size:", currentMaxSize, "read:", read, "send", send) + return + } + if read == 0 && currentMaxSize == maxsize { + return + } + send -= read + remain := Self.remainingSize(currentMaxSize, send) + if remain == 0 && wait { + // just keep the wait status + newWait = true + } + // remain > 0, change wait to false. or remain == 0, wait is false, just keep it + if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(currentMaxSize, send, newWait)) { + //log.Printf("currentMaxSize:%d read:%d send:%d", currentMaxSize, read, send) + break + } + // anther goroutine change wait status or window size + } + if wait && !newWait { + // send window into the wait status, need notice the channel + Self.allow() + } + // send window not into the wait status, so just do slide + return false +} + +func (Self *sendWindow) allow() { + select { + case Self.setSizeCh <- struct{}{}: + return + case <-Self.closeOpCh: + close(Self.setSizeCh) + return + } +} + +func (Self *sendWindow) sent(sentSize uint32) { + var maxSie, send uint32 + var wait bool + for { + ptrs := atomic.LoadUint64(&Self.maxSizeDone) + maxSie, send, wait = Self.unpack(ptrs) + if (send+sentSize)&mask31 < send { + // overflow + runtime.Gosched() + continue + } + if atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSie, send+sentSize, wait)) { + // set the send size + break + } + } +} + +func (Self *sendWindow) WriteTo() (p []byte, sendSize uint32, part bool, err error) { + // returns buf segments, return only one segments, need a loop outside + // until err = io.EOF + if Self.closeOp { + return nil, 0, false, errors.New("conn.writeWindow: window closed") + } + if Self.off >= uint32(len(Self.buf)) { + return nil, 0, false, io.EOF + // send window buff is drain, return eof and get another one + } + var maxSize, send uint32 +start: + ptrs := atomic.LoadUint64(&Self.maxSizeDone) + maxSize, send, _ = Self.unpack(ptrs) + remain := Self.remainingSize(maxSize, send) + if remain == 0 { + if !atomic.CompareAndSwapUint64(&Self.maxSizeDone, ptrs, Self.pack(maxSize, send, true)) { + // just change the status wait status + goto start // another goroutine change the window, try again + } + // into the wait status + err = Self.waitReceiveWindow() + if err != nil { + return nil, 0, false, err + } + goto start + } + + if Self.off > uint32(len(Self.buf)) { + return nil, 0, false, io.EOF + } + + //logs.Info("Self size:", len(Self.buf), "Self.off " ,Self.off) + // there are still remaining window + if len(Self.buf[Self.off:]) > maximumSegmentSize { + sendSize = maximumSegmentSize + } else { + sendSize = uint32(len(Self.buf[Self.off:])) + } + if remain < sendSize { + // usable window size is small than + // window MAXIMUM_SEGMENT_SIZE or send buf left + sendSize = remain + } + if sendSize < uint32(len(Self.buf[Self.off:])) { + part = true + } + p = Self.buf[Self.off : sendSize+Self.off] + Self.off += sendSize + Self.sent(sendSize) + //logs.Info("sendSize", sendSize, "Self.off " ,Self.off) + return +} + +func (Self *sendWindow) waitReceiveWindow() (err error) { + t := Self.timeout.Sub(time.Now()) + if t < 0 { // not set the timeout, wait for it as long as connection close + select { + case _, ok := <-Self.setSizeCh: + if !ok { + return errors.New("conn.writeWindow: window closed") + } + return nil + case <-Self.closeOpCh: + return errors.New("conn.writeWindow: window closed") + } + } + timer := time.NewTimer(t) + defer timer.Stop() + // waiting for receive usable window size, or timeout + select { + case _, ok := <-Self.setSizeCh: + if !ok { + return errors.New("conn.writeWindow: window closed") + } + return nil + case <-timer.C: + return errors.New("conn.writeWindow: write to time out") + case <-Self.closeOpCh: + return errors.New("conn.writeWindow: window closed") + } +} + +func (Self *sendWindow) WriteFull(buf []byte, id int32) (n int, err error) { + Self.SetSendBuf(buf) // set the buf to send window + var bufSeg []byte + var part bool + var l uint32 + for { + bufSeg, l, part, err = Self.WriteTo() + // get the buf segments from send window + if bufSeg == nil && part == false && err == io.EOF { + // send window is drain, break the loop + err = nil + break + } + if err != nil { + break + } + n += int(l) + l = 0 + if part { + Self.mux.sendInfo(muxNewMsgPart, id, bufSeg) + } else { + Self.mux.sendInfo(muxNewMsg, id, bufSeg) + } + // send to other side, not send nil data to other side + } + return +} + +func (Self *sendWindow) SetTimeOut(t time.Time) { + // waiting for receive a receive window size + Self.timeout = t +} + +type writeBandwidth struct { + writeBW uint64 // store in bits, but it's float64 + readEnd time.Time + duration float64 + bufLength uint32 + ratio uint32 +} + +const writeCalcThreshold uint32 = 5 * 1024 * 1024 + +func newWriteBandwidth() *writeBandwidth { + return &writeBandwidth{ratio: 1} +} + +func (Self *writeBandwidth) StartRead() { + if Self.readEnd.IsZero() { + Self.readEnd = time.Now() + } + Self.duration += time.Now().Sub(Self.readEnd).Seconds() + if Self.bufLength >= writeCalcThreshold*atomic.LoadUint32(&Self.ratio) { + Self.calcBandWidth() + } +} + +func (Self *writeBandwidth) SetCopySize(n uint16) { + Self.bufLength += uint32(n) + Self.endRead() +} + +func (Self *writeBandwidth) endRead() { + Self.readEnd = time.Now() +} + +func (Self *writeBandwidth) calcBandWidth() { + atomic.StoreUint64(&Self.writeBW, math.Float64bits(float64(Self.bufLength)/Self.duration)) + Self.bufLength = 0 + Self.duration = 0 +} + +func (Self *writeBandwidth) Get() (bw float64) { + // The zero value, 0 for numeric types + bw = math.Float64frombits(atomic.LoadUint64(&Self.writeBW)) + if bw <= 0 { + bw = 0 + } + return +} + +func (Self *writeBandwidth) GrowRatio() { + atomic.AddUint32(&Self.ratio, 1) +} diff --git a/lib/nps_mux/map.go b/lib/nps_mux/map.go new file mode 100644 index 0000000..c5cb6f5 --- /dev/null +++ b/lib/nps_mux/map.go @@ -0,0 +1,53 @@ +package nps_mux + +import ( + "sync" +) + +type connMap struct { + cMap map[int32]*conn + //closeCh chan struct{} + sync.RWMutex +} + +func NewConnMap() *connMap { + cMap := &connMap{ + cMap: make(map[int32]*conn), + } + return cMap +} + +func (s *connMap) Size() (n int) { + s.RLock() + n = len(s.cMap) + s.RUnlock() + return +} + +func (s *connMap) Get(id int32) (*conn, bool) { + s.RLock() + v, ok := s.cMap[id] + s.RUnlock() + if ok && v != nil { + return v, true + } + return nil, false +} + +func (s *connMap) Set(id int32, v *conn) { + s.Lock() + s.cMap[id] = v + s.Unlock() +} + +func (s *connMap) Close() { + for _, v := range s.cMap { + _ = v.Close() // close all the connections in the mux + } +} + +func (s *connMap) Delete(id int32) { + s.Lock() + delete(s.cMap, id) + s.Unlock() +} diff --git a/lib/nps_mux/mux.go b/lib/nps_mux/mux.go new file mode 100644 index 0000000..6a712a6 --- /dev/null +++ b/lib/nps_mux/mux.go @@ -0,0 +1,514 @@ +package nps_mux + +import ( + "errors" + "io" + "log" + "math" + "net" + "os" + "sync/atomic" + "time" +) + +const ( + muxPingFlag uint8 = iota + muxNewConnOk + muxNewConnFail + muxNewMsg + muxNewMsgPart + muxMsgSendOk + muxNewConn + muxConnClose + muxPingReturn + muxPing int32 = -1 + maximumSegmentSize = poolSizeWindow + maximumWindowSize = 1 << 27 // 1<<31-1 TCP slide window size is very large, + // we use 128M, reduce memory usage +) + +type Mux struct { + latency uint64 // we store latency in bits, but it's float64 + net.Listener + conn net.Conn + connMap *connMap + newConnCh chan *conn + id int32 + closeChan chan struct{} + IsClose bool + counter *latencyCounter + bw *bandwidth + pingCh chan []byte + pingCheckTime uint32 // we check the ping per 5s + pingCheckThreshold uint32 + connType string + writeQueue priorityQueue + newConnQueue connQueue +} + +func NewMux(c net.Conn, connType string, pingCheckThreshold int) *Mux { + //c.(*net.TCPConn).SetReadBuffer(0) + //c.(*net.TCPConn).SetWriteBuffer(0) + fd, err := getConnFd(c) + if err != nil { + log.Println(err) + } + var checkThreshold uint32 + if pingCheckThreshold <= 0 { + if connType == "kcp" { + checkThreshold = 20 + } else { + checkThreshold = 60 + } + } else { + checkThreshold = uint32(pingCheckThreshold) + } + m := &Mux{ + conn: c, + connMap: NewConnMap(), + id: 0, + closeChan: make(chan struct{}, 1), + newConnCh: make(chan *conn), + bw: NewBandwidth(fd), + IsClose: false, + connType: connType, + pingCh: make(chan []byte), + pingCheckThreshold: checkThreshold, + counter: newLatencyCounter(), + } + m.writeQueue.New() + m.newConnQueue.New() + //read session by flag + m.readSession() + //ping + m.ping() + m.writeSession() + return m +} + +func (s *Mux) NewConn() (*conn, error) { + if s.IsClose { + return nil, errors.New("the mux has closed") + } + conn := NewConn(s.getId(), s) + //it must be Set before send + s.connMap.Set(conn.connId, conn) + s.sendInfo(muxNewConn, conn.connId, nil) + //Set a timer timeout 120 second + timer := time.NewTimer(time.Minute * 2) + defer timer.Stop() + select { + case <-conn.connStatusOkCh: + return conn, nil + case <-timer.C: + } + return nil, errors.New("create connection fail,the server refused the connection") +} + +func (s *Mux) Accept() (net.Conn, error) { + if s.IsClose { + return nil, errors.New("accpet error,the mux has closed") + } + conn := <-s.newConnCh + if conn == nil { + return nil, errors.New("accpet error,the conn has closed") + } + return conn, nil +} + +func (s *Mux) Addr() net.Addr { + return s.conn.LocalAddr() +} + +func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) { + if s.IsClose { + return + } + var err error + pack := muxPack.Get() + err = pack.Set(flag, id, data) + if err != nil { + muxPack.Put(pack) + log.Println("mux: New Pack err", err) + _ = s.Close() + return + } + s.writeQueue.Push(pack) + return +} + +func (s *Mux) writeSession() { + go func() { + for { + if s.IsClose { + break + } + pack := s.writeQueue.Pop() + if s.IsClose { + break + } + //if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart { + // if pack.length >= 100 { + // log.Println("write session id", pack.id, "\n", string(pack.content[:100])) + // } else { + // log.Println("write session id", pack.id, "\n", string(pack.content[:pack.length])) + // } + //} + err := pack.Pack(s.conn) + muxPack.Put(pack) + if err != nil { + log.Println("mux: Pack err", err) + _ = s.Close() + break + } + } + }() +} + +func (s *Mux) ping() { + go func() { + now, _ := time.Now().UTC().MarshalText() + s.sendInfo(muxPingFlag, muxPing, now) + // send the ping flag and Get the latency first + ticker := time.NewTicker(time.Second * 5) + defer ticker.Stop() + for { + if s.IsClose { + break + } + select { + case <-ticker.C: + } + if atomic.LoadUint32(&s.pingCheckTime) > s.pingCheckThreshold { + log.Println("mux: ping time out, checktime", s.pingCheckTime, "threshold", s.pingCheckThreshold) + _ = s.Close() + // more than limit times not receive the ping return package, + // mux conn is damaged, maybe a packet drop, close it + break + } + now, _ = time.Now().UTC().MarshalText() + s.sendInfo(muxPingFlag, muxPing, now) + atomic.AddUint32(&s.pingCheckTime, 1) + } + return + }() + + go func() { + var now time.Time + var data []byte + for { + if s.IsClose { + break + } + select { + case data = <-s.pingCh: + atomic.StoreUint32(&s.pingCheckTime, 0) + case <-s.closeChan: + break + } + _ = now.UnmarshalText(data) + latency := time.Now().UTC().Sub(now).Seconds() + if latency > 0 { + atomic.StoreUint64(&s.latency, math.Float64bits(s.counter.Latency(latency))) + // convert float64 to bits, store it atomic + //log.Println("ping", math.Float64frombits(atomic.LoadUint64(&s.latency))) + } + if cap(data) > 0 && !s.IsClose { + windowBuff.Put(data) + } + } + }() +} + +func (s *Mux) readSession() { + go func() { + var connection *conn + for { + if s.IsClose { + break + } + connection = s.newConnQueue.Pop() + if s.IsClose { + break // make sure that is closed + } + s.connMap.Set(connection.connId, connection) //it has been Set before send ok + s.newConnCh <- connection + s.sendInfo(muxNewConnOk, connection.connId, nil) + } + }() + go func() { + var pack *muxPackager + var l uint16 + var err error + for { + if s.IsClose { + return + } + pack = muxPack.Get() + s.bw.StartRead() + if l, err = pack.UnPack(s.conn); err != nil { + log.Println("mux: read session unpack from connection err", err) + _ = s.Close() + break + } + s.bw.SetCopySize(l) + //if pack.flag == muxNewMsg || pack.flag == muxNewMsgPart { + // if pack.length >= 100 { + // log.Printf("read session id %d pointer %p\n%v", pack.id, pack.content, string(pack.content[:100])) + // } else { + // log.Printf("read session id %d pointer %p\n%v", pack.id, pack.content, string(pack.content[:pack.length])) + // } + //} + switch pack.flag { + case muxNewConn: //New connection + connection := NewConn(pack.id, s) + s.newConnQueue.Push(connection) + continue + case muxPingFlag: //ping + s.sendInfo(muxPingReturn, muxPing, pack.content) + windowBuff.Put(pack.content) + continue + case muxPingReturn: + s.pingCh <- pack.content + continue + } + if connection, ok := s.connMap.Get(pack.id); ok && !connection.isClose { + switch pack.flag { + case muxNewMsg, muxNewMsgPart: //New msg from remote connection + err = s.newMsg(connection, pack) + if err != nil { + log.Println("mux: read session connection New msg err", err) + _ = connection.Close() + } + continue + case muxNewConnOk: //connection ok + connection.connStatusOkCh <- struct{}{} + continue + case muxNewConnFail: + connection.connStatusFailCh <- struct{}{} + continue + case muxMsgSendOk: + if connection.isClose { + continue + } + connection.sendWindow.SetSize(pack.window) + continue + case muxConnClose: //close the connection + connection.closingFlag = true + connection.receiveWindow.Stop() // close signal to receive window + continue + } + } else if pack.flag == muxConnClose { + continue + } + muxPack.Put(pack) + } + }() +} + +func (s *Mux) newMsg(connection *conn, pack *muxPackager) (err error) { + if connection.isClose { + err = io.ErrClosedPipe + return + } + //insert into queue + if pack.flag == muxNewMsgPart { + err = connection.receiveWindow.Write(pack.content, pack.length, true, pack.id) + } + if pack.flag == muxNewMsg { + err = connection.receiveWindow.Write(pack.content, pack.length, false, pack.id) + } + return +} + +func (s *Mux) Close() (err error) { + if s.IsClose { + return errors.New("the mux has closed") + } + s.IsClose = true + log.Println("close mux") + s.connMap.Close() + //s.connMap = nil + s.closeChan <- struct{}{} + close(s.newConnCh) + // while target host close socket without finish steps, conn.Close method maybe blocked + // and tcp status change to CLOSE WAIT or TIME WAIT, so we close it in other goroutine + _ = s.conn.SetDeadline(time.Now().Add(time.Second * 5)) + go s.conn.Close() + s.release() + return +} + +func (s *Mux) release() { + for { + pack := s.writeQueue.TryPop() + if pack == nil { + break + } + if pack.basePackager.content != nil { + windowBuff.Put(pack.basePackager.content) + } + muxPack.Put(pack) + } + for { + connection := s.newConnQueue.TryPop() + if connection == nil { + break + } + connection = nil + } + s.writeQueue.Stop() + s.newConnQueue.Stop() +} + +//Get New connId as unique flag +func (s *Mux) getId() (id int32) { + //Avoid going beyond the scope + if (math.MaxInt32 - s.id) < 10000 { + atomic.StoreInt32(&s.id, 0) + } + id = atomic.AddInt32(&s.id, 1) + if _, ok := s.connMap.Get(id); ok { + return s.getId() + } + return +} + +type bandwidth struct { + readBandwidth uint64 // store in bits, but it's float64 + readStart time.Time + lastReadStart time.Time + bufLength uint32 + fd *os.File + calcThreshold uint32 +} + +func NewBandwidth(fd *os.File) *bandwidth { + return &bandwidth{fd: fd} +} + +func (Self *bandwidth) StartRead() { + if Self.readStart.IsZero() { + Self.readStart = time.Now() + } + if Self.bufLength >= Self.calcThreshold { + Self.lastReadStart, Self.readStart = Self.readStart, time.Now() + Self.calcBandWidth() + } +} + +func (Self *bandwidth) SetCopySize(n uint16) { + Self.bufLength += uint32(n) +} + +func (Self *bandwidth) calcBandWidth() { + t := Self.readStart.Sub(Self.lastReadStart) + bufferSize, err := sysGetSock(Self.fd) + if err != nil { + log.Println(err) + Self.bufLength = 0 + return + } + if Self.bufLength >= uint32(bufferSize) { + atomic.StoreUint64(&Self.readBandwidth, math.Float64bits(float64(Self.bufLength)/t.Seconds())) + // calculate the whole socket buffer, the time meaning to fill the buffer + } else { + Self.calcThreshold = uint32(bufferSize) + } + // socket buffer size is bigger than bufLength, so we don't calculate it + Self.bufLength = 0 +} + +func (Self *bandwidth) Get() (bw float64) { + // The zero value, 0 for numeric types + bw = math.Float64frombits(atomic.LoadUint64(&Self.readBandwidth)) + if bw <= 0 { + bw = 0 + } + return +} + +const counterBits = 4 +const counterMask = 1<> counterBits) & counterMask + // we Set head is 4 bits + min = idxs & counterMask + return +} + +func (Self *latencyCounter) pack(head, min uint8) uint8 { + return head< value { + min = head + } + head++ + Self.headMin = Self.pack(head, min) +} + +func (Self *latencyCounter) minimal() (min uint8) { + var val float64 + var i uint8 + for i = 0; i < counterMask; i++ { + if Self.buf[i] > 0 { + if val > Self.buf[i] { + val = Self.buf[i] + min = i + } + } + } + return +} + +func (Self *latencyCounter) Latency(value float64) (latency float64) { + Self.add(value) + latency = Self.countSuccess() + return +} + +const lossRatio = 3 + +func (Self *latencyCounter) countSuccess() (successRate float64) { + var i, success uint8 + _, min := Self.unpack(Self.headMin) + for i = 0; i < counterMask; i++ { + if Self.buf[i] <= lossRatio*Self.buf[min] && Self.buf[i] > 0 { + success++ + successRate += Self.buf[i] + } + } + // counting all the data in the ring buf, except zero + successRate = successRate / float64(success) + return +} diff --git a/lib/nps_mux/mux_test.go b/lib/nps_mux/mux_test.go new file mode 100644 index 0000000..6a88261 --- /dev/null +++ b/lib/nps_mux/mux_test.go @@ -0,0 +1,703 @@ +package nps_mux + +import ( + "bufio" + "bytes" + "fmt" + "io" + "log" + "math" + "net" + "net/http" + "net/http/httputil" + _ "net/http/pprof" + "os" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + "unsafe" +) + +var conn1 net.Conn +var conn2 net.Conn +var clientIp = "172.18.0.5" +var serverIp = "172.18.0.2" +var appIp = "172.18.0.3" +var userIp = "172.18.0.4" +var bridgePort = "9999" +var appPort = "9998" +var serverPort = "9997" +var appResultFileName = "app.txt" +var userResultFileName = "user.txt" +var serverResultFileName = "server.txt" +var clientResultFileName = "client.txt" +var dockerNetWorkName = "test" +var network = "172.18.0.0/16" +var fileSavePath = "/usr/src/myapp/" +var dataSize = 1024 * 1024 * 100 + +func TestMux(t *testing.T) { + pwd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + wg.Add(3) + _ = createNetwork(dockerNetWorkName, network) + go func() { + defer wg.Done() + _ = runDocker("server", dockerNetWorkName, serverIp, "TestServer", pwd) + }() + time.Sleep(time.Second * 5) + go func() { + defer wg.Done() + _ = runDocker("client", dockerNetWorkName, clientIp, "TestClient", pwd) + }() + go func() { + defer wg.Done() + _ = runDocker("app", dockerNetWorkName, appIp, "TestApp", pwd) + }() + time.Sleep(time.Second * 5) + _ = runDocker("user", dockerNetWorkName, userIp, "TestUser", pwd) + wg.Wait() + _ = deleteNetwork(dockerNetWorkName) +} + +func writeResult(values []float64, outfile string) error { + file, err := os.Create(fileSavePath + outfile) + if err != nil { + fmt.Println("writer", err) + return err + } + defer file.Close() + writer := bufio.NewWriter(file) + for _, v := range values { + _, _ = writer.WriteString(fmt.Sprintf("%.2f", v)) + _, _ = writer.WriteString("\n") + _ = writer.Flush() + } + return err +} + +func appendResult(values []float64, outfile string) error { + file, err := os.OpenFile(fileSavePath+outfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + fmt.Println("writer", err) + return err + } + defer file.Close() + writer := bufio.NewWriter(file) + for _, v := range values { + _, _ = writer.WriteString(fmt.Sprintf("%.2f", v)) + _, _ = writer.WriteString("\n") + _ = writer.Flush() + } + return err +} + +func TestServer(t *testing.T) { + tc, err := NewTrafficControl(serverIp) + if err != nil { + t.Fatal(err, tc) + } + // do some tc settings + tc.delay("add", "50ms", "10ms", "10%") + _ = tc.Run() + _ = tc.bandwidth("1Mbit") + // start bridge + bridgeListener, err := net.Listen("tcp", serverIp+":"+bridgePort) + if err != nil { + t.Fatal(err) + } + // wait for client + clientBridgeConn, err := bridgeListener.Accept() + if err != nil { + t.Fatal(err) + } + defer clientBridgeConn.Close() + // new mux + mux := NewMux(clientBridgeConn, "tcp", 60) + // start server port + serverListener, err := net.Listen("tcp", serverIp+":"+serverPort) + if err != nil { + t.Fatal(err) + } + defer serverListener.Close() + for { + // accept user connection + userConn, err := serverListener.Accept() + if err != nil { + t.Fatal(err) + } + go func(userConn net.Conn) { + // create a conn from mux + clientConn, err := mux.NewConn() + if err != nil { + t.Fatal(err) + } + go io.Copy(userConn, clientConn) + go func() { + _ = writeResult([]float64{ + mux.bw.Get() / 1024 / 1024, + math.Float64frombits(atomic.LoadUint64(&mux.latency)), + }, serverResultFileName) + ticker := time.NewTicker(time.Second * 1) + for { + select { + case <-ticker.C: + fmt.Println(mux.bw.Get()/1024/1024, math.Float64frombits(atomic.LoadUint64(&mux.latency))) + _ = appendResult([]float64{ + mux.bw.Get() / 1024 / 1024, + math.Float64frombits(atomic.LoadUint64(&mux.latency)), + }, serverResultFileName) + } + } + }() + _, _ = io.Copy(clientConn, userConn) + os.Exit(0) + }(userConn) + } +} +func TestClient(t *testing.T) { + tc, err := NewTrafficControl(clientIp) + if err != nil { + t.Fatal(err, tc) + } + // do some tc settings + tc.delay("add", "30ms", "10ms", "5%") + _ = tc.Run() + _ = tc.bandwidth("1Mbit") + serverConn, err := net.Dial("tcp", serverIp+":"+bridgePort) + if err != nil { + t.Fatal(err) + } + // crete mux by serverConn + mux := NewMux(serverConn, "tcp", 60) + // start accept user connection + for { + userConn, err := mux.Accept() + if err != nil { + t.Fatal(err) + } + go func(userConn net.Conn) { + // connect to app + appConn, err := net.Dial("tcp", appIp+":"+appPort) + if err != nil { + t.Fatal() + } + defer appConn.Close() + defer userConn.Close() + go io.Copy(userConn, appConn) + go func() { + _ = writeResult([]float64{ + mux.bw.Get() / 1024 / 1024, + math.Float64frombits(atomic.LoadUint64(&mux.latency)), + }, clientResultFileName) + ticker := time.NewTicker(time.Second * 1) + for { + select { + case <-ticker.C: + _ = appendResult([]float64{ + mux.bw.Get() / 1024 / 1024, + math.Float64frombits(atomic.LoadUint64(&mux.latency)), + }, clientResultFileName) + } + } + }() + _, _ = io.Copy(appConn, userConn) + os.Exit(0) + }(userConn) + } +} +func TestApp(t *testing.T) { + tc, err := NewTrafficControl(appIp) + if err != nil { + t.Fatal(err, tc) + } + // do some tc settings + tc.delay("add", "40ms", "5ms", "1%") + _ = tc.Run() + _ = tc.bandwidth("1Mbit") + appListener, err := net.Listen("tcp", appIp+":"+appPort) + if err != nil { + t.Fatal(err) + } + for { + userConn, err := appListener.Accept() + if err != nil { + t.Fatal(err) + } + go func(userConn net.Conn) { + b := bytes.Repeat([]byte{0}, 1024) + startTime := time.Now() + // send data to user + for i := 0; i < dataSize/1024; i++ { + n, err := userConn.Write(b) + if err != nil { + t.Fatal(err) + } + if n != 1024 { + t.Fatal("the write len is not right") + } + } + // send bandwidth + writeBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds() + // get 100md from user + startTime = time.Now() + readLen := 0 + for i := 0; i < 2<<32; i++ { + n, err := userConn.Read(b) + fmt.Println(n) + if err != nil { + log.Fatal(err) + } + fmt.Println(readLen) + readLen += n + if readLen == dataSize { + break + } + } + if readLen != dataSize { + t.Fatal("the read len is not right") + } + _, _ = userConn.Write([]byte{0}) + // read bandwidth + readBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds() + // save result + err := writeResult([]float64{writeBw, readBw}, appResultFileName) + if err != nil { + t.Fatal(err) + } + os.Exit(0) + }(userConn) + } +} +func TestUser(t *testing.T) { + tc, err := NewTrafficControl(userIp) + if err != nil { + t.Fatal(err, tc) + } + // do some tc settings + tc.delay("add", "20ms", "40ms", "50%") + _ = tc.Run() + _ = tc.bandwidth("1Mbit") + appConn, err := net.Dial("tcp", serverIp+":"+serverPort) + if err != nil { + t.Fatal(err) + } + b := bytes.Repeat([]byte{0}, 1024) + startTime := time.Now() + // get 100md from app + readLen := 0 + for i := 0; i < 2<<32; i++ { + n, err := appConn.Read(b) + if err != nil { + log.Fatal(err) + } + readLen += n + if readLen == dataSize { + break + } + } + if readLen != dataSize { + t.Fatal("the read len is not right", readLen, dataSize) + } + // read bandwidth + readBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds() + // send 100mb data to app + startTime = time.Now() + b = bytes.Repeat([]byte{0}, 1024) + for i := 0; i < dataSize/1024; i++ { + n, err := appConn.Write(b) + if err != nil { + t.Fatal(err) + } + if n != 1024 { + t.Fatal("the write len is not right") + } + } + b = make([]byte, 1) + _, err = io.ReadFull(appConn, b) + if err != nil { + t.Fatal(err) + } + // send bandwidth + writeBw := float64(dataSize/1024/1024) / time.Now().Sub(startTime).Seconds() + // save result + err = writeResult([]float64{readBw, writeBw}, userResultFileName) + if err != nil { + t.Fatal(err) + } +} +func TestNewMux2(t *testing.T) { + tc, err := NewTrafficControl("") + if err != nil { + t.Fatal(err) + } + err = tc.RunNetRangeTest(func() { + server(tc.Eth.EthAddr) + client(tc.Eth.EthAddr) + time.Sleep(time.Second * 3) + rate := NewRate(1024 * 1024 * 3) + rate.Start() + conn2 = NewRateConn(rate, conn2) + go func() { + m2 := NewMux(conn2, "tcp", 60) + for { + c, err := m2.Accept() + if err != nil { + log.Println(err) + continue + } + go func() { + _, _ = c.Write(bytes.Repeat([]byte{0}, 1024*1024*100)) + _ = c.Close() + }() + } + }() + + m1 := NewMux(conn1, "tcp", 60) + tmpCpnn, err := m1.NewConn() + if err != nil { + log.Println("nps new conn err ", err) + return + } + buf := make([]byte, 1024*1024) + var count float64 + count = 0 + start := time.Now() + for { + n, err := tmpCpnn.Read(buf) + count += float64(n) + log.Println(m1.bw.Get()) + log.Println(uint32(math.Float64frombits(atomic.LoadUint64(&m1.latency)))) + if err != nil { + log.Println(err) + break + } + } + log.Println("now rate", count/time.Now().Sub(start).Seconds()/1024/1024) + }) + log.Println(err.Error()) +} +func TestNewMux(t *testing.T) { + go func() { + _ = http.ListenAndServe("0.0.0.0:8889", nil) + }() + server("") + client("") + time.Sleep(time.Second * 3) + go func() { + m2 := NewMux(conn2, "tcp", 60) + for { + //log.Println("npc starting accept") + c, err := m2.Accept() + if err != nil { + log.Println(err) + continue + } + //log.Println("npc accept success ") + c2, err := net.Dial("tcp", "127.0.0.1:80") + if err != nil { + log.Println(err) + _ = c.Close() + continue + } + //c2.(*net.TCPConn).SetReadBuffer(0) + //c2.(*net.TCPConn).SetReadBuffer(0) + go func(c2 net.Conn, c *conn) { + go func() { + buf := make([]byte, 32<<10) + _, err = io.CopyBuffer(c2, c, buf) + //if err != nil { + // log.Println("close npc by copy from nps", err, c.connId) + //} + _ = c2.Close() + _ = c.Close() + }() + buf := make([]byte, 32<<10) + _, err = io.CopyBuffer(c, c2, buf) + //if err != nil { + // log.Println("close npc by copy from server", err, c.connId) + //} + _ = c2.Close() + _ = c.Close() + }(c2, c.(*conn)) + } + }() + + go func() { + m1 := NewMux(conn1, "tcp", 60) + l, err := net.Listen("tcp", "127.0.0.1:7777") + if err != nil { + log.Println(err) + } + for { + //log.Println("nps starting accept") + conns, err := l.Accept() + if err != nil { + log.Println(err) + continue + } + //conns.(*net.TCPConn).SetReadBuffer(0) + //conns.(*net.TCPConn).SetReadBuffer(0) + //log.Println("nps accept success starting New conn") + tmpCpnn, err := m1.NewConn() + if err != nil { + log.Println("nps New conn err ", err) + continue + } + //logs.Warn("nps New conn success ", tmpCpnn.connId) + go func(tmpCpnn *conn, conns net.Conn) { + go func() { + buf := make([]byte, 32<<10) + _, _ = io.CopyBuffer(tmpCpnn, conns, buf) + //if err != nil { + // log.Println("close nps by copy from user", tmpCpnn.connId, err) + //} + _ = conns.Close() + _ = tmpCpnn.Close() + }() + time.Sleep(time.Second) + buf := make([]byte, 32<<10) + _, err = io.CopyBuffer(conns, tmpCpnn, buf) + //if err != nil { + // log.Println("close nps by copy from npc ", tmpCpnn.connId, err) + //} + _ = conns.Close() + _ = tmpCpnn.Close() + }(tmpCpnn, conns) + } + }() + + //go NewLogServer() + time.Sleep(time.Second * 5) + //for i := 0; i < 1; i++ { + // go test_raw(i) + //} + //test_request() + + for { + time.Sleep(time.Second * 5) + } +} + +func server(ip string) { + if ip == "" { + ip = "127.0.0.1" + } + var err error + l, err := net.Listen("tcp", ip+":9999") + if err != nil { + log.Println(err) + } + go func() { + conn1, err = l.Accept() + if err != nil { + log.Println(err) + } + }() + return +} + +func client(ip string) { + if ip == "" { + ip = "127.0.0.1" + } + var err error + conn2, err = net.Dial("tcp", ip+":9999") + if err != nil { + log.Println(err) + } +} + +func test_request() { + conn, _ := net.Dial("tcp", "127.0.0.1:7777") + for i := 0; i < 1000; i++ { + _, _ = conn.Write([]byte(`GET / HTTP/1.1 +Host: 127.0.0.1:7777 +Connection: keep-alive + + +`)) + r, err := http.ReadResponse(bufio.NewReader(conn), nil) + if err != nil { + log.Println("close by read response err", err) + break + } + log.Println("read response success", r) + b, err := httputil.DumpResponse(r, true) + if err != nil { + log.Println("close by dump response err", err) + break + } + fmt.Println(string(b[:20]), err) + //time.Sleep(time.Second) + } + log.Println("finish") +} + +func test_raw(k int) { + for i := 0; i < 1000; i++ { + ti := time.Now() + conn, err := net.Dial("tcp", "127.0.0.1:7777") + if err != nil { + log.Println("conn dial err", err) + } + tid := time.Now() + _, _ = conn.Write([]byte(`GET /videojs5/video.js HTTP/1.1 +Host: 127.0.0.1:7777 + + +`)) + tiw := time.Now() + buf := make([]byte, 3572) + n, err := io.ReadFull(conn, buf) + //n, err := conn.Read(buf) + if err != nil { + log.Println("close by read response err", err) + break + } + log.Println(n, string(buf[:50]), "\n--------------\n", string(buf[n-50:n])) + //time.Sleep(time.Second) + err = conn.Close() + if err != nil { + log.Println("close conn err ", err) + } + now := time.Now() + du := now.Sub(ti).Seconds() + dud := now.Sub(tid).Seconds() + duw := now.Sub(tiw).Seconds() + if du > 1 { + log.Println("duration long", du, dud, duw, k, i) + } + if n != 3572 { + log.Println("n loss", n, string(buf)) + } + } + log.Println("finish") +} + +func TestNewConn(t *testing.T) { + buf := make([]byte, 1024) + log.Println(len(buf), cap(buf)) + //b := pool.GetBufPoolCopy() + //b[0] = 1 + //b[1] = 2 + //b[2] = 3 + b := []byte{1, 2, 3} + log.Println(copy(buf[:3], b), len(buf), cap(buf)) + log.Println(len(buf), buf[0]) +} + +func TestDQueue(t *testing.T) { + d := new(bufDequeue) + d.vals = make([]unsafe.Pointer, 8) + go func() { + time.Sleep(time.Second) + for i := 0; i < 10; i++ { + log.Println(i) + log.Println(d.popTail()) + } + }() + go func() { + time.Sleep(time.Second) + for i := 0; i < 10; i++ { + data := "test" + go log.Println(i, unsafe.Pointer(&data), d.pushHead(unsafe.Pointer(&data))) + } + }() + time.Sleep(time.Second * 3) +} + +func TestChain(t *testing.T) { + go func() { + log.Println(http.ListenAndServe("0.0.0.0:8889", nil)) + }() + time.Sleep(time.Second * 5) + d := new(bufChain) + d.new(256) + go func() { + time.Sleep(time.Second) + for i := 0; i < 30000; i++ { + unsa, ok := d.popTail() + str := (*string)(unsa) + if ok { + fmt.Println(i, str, *str, ok) + //logs.Warn(i, str, *str, ok) + } else { + fmt.Println("nil", i, ok) + //logs.Warn("nil", i, ok) + } + } + }() + go func() { + time.Sleep(time.Second) + for i := 0; i < 3000; i++ { + go func(i int) { + for n := 0; n < 10; n++ { + data := "test " + strconv.Itoa(i) + strconv.Itoa(n) + fmt.Println(data, unsafe.Pointer(&data)) + //logs.Warn(data, unsafe.Pointer(&data)) + d.pushHead(unsafe.Pointer(&data)) + } + }(i) + } + }() + time.Sleep(time.Second * 100000) +} + +//func TestReceive(t *testing.T) { +// go func() { +// log.Println(http.ListenAndServe("0.0.0.0:8889", nil)) +// }() +// logs.EnableFuncCallDepth(true) +// logs.SetLogFuncCallDepth(3) +// time.Sleep(time.Second * 5) +// mux := New(Mux) +// mux.bw.readBandwidth = float64(1*1024*1024) +// mux.latency = float64(1/1000) +// wind := New(receiveWindow) +// wind.New(mux) +// wind. +// go func() { +// time.Sleep(time.Second) +// for i := 0; i < 36000; i++ { +// data := d.Pop() +// //fmt.Println(i, string(data.buf), err) +// logs.Warn(i, string(data.content), data) +// } +// }() +// go func() { +// time.Sleep(time.Second*10) +// for i := 0; i < 3000; i++ { +// go func(i int) { +// for n := 0; n < 10; n++{ +// data := New(common.muxPackager) +// by := []byte("test " + strconv.Itoa(i) + strconv.Itoa(n)) +// _ = data.NewPac(common.MUX_NEW_MSG_PART, int32(i), by) +// //fmt.Println(string((*data).buf), data) +// logs.Warn(string((*data).content), data) +// d.Push(data) +// } +// }(i) +// go func(i int) { +// data := New(common.muxPackager) +// _ = data.NewPac(common.MUX_NEW_CONN, int32(i), nil) +// //fmt.Println(string((*data).buf), data) +// logs.Warn(data) +// d.Push(data) +// }(i) +// go func(i int) { +// data := New(common.muxPackager) +// _ = data.NewPac(common.MUX_NEW_CONN_OK, int32(i), nil) +// //fmt.Println(string((*data).buf), data) +// logs.Warn(data) +// d.Push(data) +// }(i) +// } +// }() +// time.Sleep(time.Second * 100000) +//} diff --git a/lib/nps_mux/netpackager.go b/lib/nps_mux/netpackager.go new file mode 100644 index 0000000..003a86b --- /dev/null +++ b/lib/nps_mux/netpackager.go @@ -0,0 +1,165 @@ +package nps_mux + +import ( + "encoding/binary" + "errors" + "github.com/astaxie/beego/logs" + "io" +) + +type basePackager struct { + buf []byte + // buf contain the mux protocol struct binary data, we copy data to buf firstly. + // replace binary.Read/Write method, it may use reflect shows slowly. + // also reduce conn.Read/Write calls which use syscall. + // due to our test, conn.Write method reduce by two-thirds CPU times, + // conn.Write method has 20% reduction of the CPU times, + // totally provides more than twice of the CPU performance improvement. + length uint16 + content []byte +} + +func (Self *basePackager) Set(content []byte) (err error) { + Self.reset() + if content != nil { + n := len(content) + //fmt.Println(content) + if n == 0 { + // 长度为0的包,不应该向上抛,不然客户端会EOF,这里暂时没解决空包的问题 TODO + //logs.Error("mux:packer: newpack content is zero length") + //err = errors.New("mux:packer: newpack content is zero length") + } + if n > maximumSegmentSize { + logs.Error("mux:packer: newpack content segment too large") + //err = errors.New("mux:packer: newpack content segment too large") + return + } + Self.content = Self.content[:n] + copy(Self.content, content) + } else { + logs.Error("mux:packer: newpack content is nil") + return + //panic("mux:packer: newpack content is nil") + //err = errors.New("mux:packer: newpack content is nil") + } + Self.setLength() + return +} + +func (Self *basePackager) Pack(writer io.Writer) (err error) { + binary.LittleEndian.PutUint16(Self.buf[5:7], Self.length) + _, err = writer.Write(Self.buf[:7]) + if err != nil { + return + } + _, err = writer.Write(Self.content[:Self.length]) + return +} + +func (Self *basePackager) UnPack(reader io.Reader) (n uint16, err error) { + Self.reset() + l, err := io.ReadFull(reader, Self.buf[5:7]) + if err != nil { + return + } + n += uint16(l) + Self.length = binary.LittleEndian.Uint16(Self.buf[5:7]) + if int(Self.length) > cap(Self.content) { + err = errors.New("mux:packer: unpack err, content length too large") + return + } + if Self.length > maximumSegmentSize { + err = errors.New("mux:packer: unpack content segment too large") + return + } + Self.content = Self.content[:int(Self.length)] + l, err = io.ReadFull(reader, Self.content) + n += uint16(l) + return +} + +func (Self *basePackager) setLength() { + Self.length = uint16(len(Self.content)) + return +} + +func (Self *basePackager) reset() { + Self.length = 0 + Self.content = Self.content[:0] // reset length +} + +type muxPackager struct { + flag uint8 + id int32 + window uint64 + basePackager +} + +func (Self *muxPackager) Set(flag uint8, id int32, content interface{}) (err error) { + Self.buf = windowBuff.Get() + Self.flag = flag + Self.id = id + switch flag { + case muxPingFlag, muxPingReturn, muxNewMsg, muxNewMsgPart: + Self.content = windowBuff.Get() + if content != nil { + err = Self.basePackager.Set(content.([]byte)) + } + case muxMsgSendOk: + // MUX_MSG_SEND_OK contains one data + Self.window = content.(uint64) + } + return +} + +func (Self *muxPackager) Pack(writer io.Writer) (err error) { + Self.buf = Self.buf[0:13] + Self.buf[0] = byte(Self.flag) + binary.LittleEndian.PutUint32(Self.buf[1:5], uint32(Self.id)) + switch Self.flag { + case muxNewMsg, muxNewMsgPart, muxPingFlag, muxPingReturn: + err = Self.basePackager.Pack(writer) + windowBuff.Put(Self.content) + case muxMsgSendOk: + binary.LittleEndian.PutUint64(Self.buf[5:13], Self.window) + _, err = writer.Write(Self.buf[:13]) + default: + _, err = writer.Write(Self.buf[:5]) + } + windowBuff.Put(Self.buf) + return +} + +func (Self *muxPackager) UnPack(reader io.Reader) (n uint16, err error) { + Self.buf = windowBuff.Get() + Self.buf = Self.buf[0:13] + l, err := io.ReadFull(reader, Self.buf[:5]) + if err != nil { + return + } + n += uint16(l) + Self.flag = uint8(Self.buf[0]) + Self.id = int32(binary.LittleEndian.Uint32(Self.buf[1:5])) + switch Self.flag { + case muxNewMsg, muxNewMsgPart, muxPingFlag, muxPingReturn: + var m uint16 + Self.content = windowBuff.Get() // need Get a window buf from pool + m, err = Self.basePackager.UnPack(reader) + n += m + case muxMsgSendOk: + l, err = io.ReadFull(reader, Self.buf[5:13]) + Self.window = binary.LittleEndian.Uint64(Self.buf[5:13]) + n += uint16(l) // uint64 + } + windowBuff.Put(Self.buf) + return +} + +func (Self *muxPackager) reset() { + Self.id = 0 + Self.flag = 0 + Self.length = 0 + Self.content = nil + Self.window = 0 + Self.buf = nil +} diff --git a/lib/nps_mux/pool.go b/lib/nps_mux/pool.go new file mode 100644 index 0000000..8878ed9 --- /dev/null +++ b/lib/nps_mux/pool.go @@ -0,0 +1,100 @@ +package nps_mux + +import ( + "sync" +) + +const ( + poolSizeBuffer = 4096 + //poolSizeBuffer = 4096 * 10 // a mux packager total length + poolSizeWindow = poolSizeBuffer - 2 - 4 - 4 - 1 // content length +) + +type windowBufferPool struct { + pool sync.Pool +} + +func newWindowBufferPool() *windowBufferPool { + return &windowBufferPool{ + pool: sync.Pool{ + New: func() interface{} { + return make([]byte, poolSizeWindow, poolSizeWindow) + }, + }, + } +} + +//func trace(buf []byte, ty string) { +// pc := make([]uintptr, 10) // at least 1 entry needed +// n := runtime.Callers(0, pc) +// for i := 0; i < n; i++ { +// f := runtime.FuncForPC(pc[i]) +// file, line := f.FileLine(pc[i]) +// log.Printf("%v %p %s:%d %s\n", ty, buf, file, line, f.Name()) +// } +//} + +func (Self *windowBufferPool) Get() (buf []byte) { + buf = Self.pool.Get().([]byte) + //trace(buf, "get") + return buf[:poolSizeWindow] +} + +func (Self *windowBufferPool) Put(x []byte) { + //trace(x, "put") + Self.pool.Put(x[:poolSizeWindow]) // make buf to full +} + +type muxPackagerPool struct { + pool sync.Pool +} + +func newMuxPackagerPool() *muxPackagerPool { + return &muxPackagerPool{ + pool: sync.Pool{ + New: func() interface{} { + pack := muxPackager{} + return &pack + }, + }, + } +} + +func (Self *muxPackagerPool) Get() *muxPackager { + return Self.pool.Get().(*muxPackager) +} + +func (Self *muxPackagerPool) Put(pack *muxPackager) { + pack.reset() + Self.pool.Put(pack) +} + +type listElementPool struct { + pool sync.Pool +} + +func newListElementPool() *listElementPool { + return &listElementPool{ + pool: sync.Pool{ + New: func() interface{} { + element := listElement{} + return &element + }, + }, + } +} + +func (Self *listElementPool) Get() *listElement { + return Self.pool.Get().(*listElement) +} + +func (Self *listElementPool) Put(element *listElement) { + element.Reset() + Self.pool.Put(element) +} + +var ( + muxPack = newMuxPackagerPool() + windowBuff = newWindowBufferPool() + listEle = newListElementPool() +) diff --git a/lib/nps_mux/queue.go b/lib/nps_mux/queue.go new file mode 100644 index 0000000..a4bfb14 --- /dev/null +++ b/lib/nps_mux/queue.go @@ -0,0 +1,590 @@ +package nps_mux + +import ( + "errors" + "io" + "math" + "runtime" + "sync" + "sync/atomic" + "time" + "unsafe" +) + +type priorityQueue struct { + highestChain *bufChain + middleChain *bufChain + lowestChain *bufChain + starving uint8 + stop bool + cond *sync.Cond +} + +func (Self *priorityQueue) New() { + Self.highestChain = new(bufChain) + Self.highestChain.new(4) + Self.middleChain = new(bufChain) + Self.middleChain.new(32) + Self.lowestChain = new(bufChain) + Self.lowestChain.new(256) + locker := new(sync.Mutex) + Self.cond = sync.NewCond(locker) +} + +func (Self *priorityQueue) Push(packager *muxPackager) { + Self.push(packager) + Self.cond.Broadcast() + return +} + +func (Self *priorityQueue) push(packager *muxPackager) { + switch packager.flag { + case muxPingFlag, muxPingReturn: + Self.highestChain.pushHead(unsafe.Pointer(packager)) + // the ping package need highest priority + // prevent ping calculation error + case muxNewConn, muxNewConnOk, muxNewConnFail: + // the New conn package need some priority too + Self.middleChain.pushHead(unsafe.Pointer(packager)) + default: + Self.lowestChain.pushHead(unsafe.Pointer(packager)) + } +} + +const maxStarving uint8 = 8 + +func (Self *priorityQueue) Pop() (packager *muxPackager) { + var iter bool + for { + packager = Self.TryPop() + if packager != nil { + return + } + if Self.stop { + return + } + if iter { + break + // trying to pop twice + } + iter = true + runtime.Gosched() + } + Self.cond.L.Lock() + defer Self.cond.L.Unlock() + for packager = Self.TryPop(); packager == nil; { + if Self.stop { + return + } + Self.cond.Wait() + // wait for it with no more iter + packager = Self.TryPop() + } + return +} + +func (Self *priorityQueue) TryPop() (packager *muxPackager) { + ptr, ok := Self.highestChain.popTail() + if ok { + packager = (*muxPackager)(ptr) + return + } + if Self.starving < maxStarving { + // not pop too much, lowestChain will wait too long + ptr, ok = Self.middleChain.popTail() + if ok { + packager = (*muxPackager)(ptr) + Self.starving++ + return + } + } + ptr, ok = Self.lowestChain.popTail() + if ok { + packager = (*muxPackager)(ptr) + if Self.starving > 0 { + Self.starving = Self.starving / 2 + } + return + } + if Self.starving > 0 { + ptr, ok = Self.middleChain.popTail() + if ok { + packager = (*muxPackager)(ptr) + Self.starving++ + return + } + } + return +} + +func (Self *priorityQueue) Stop() { + Self.stop = true + Self.cond.Broadcast() +} + +type connQueue struct { + chain *bufChain + starving uint8 + stop bool + cond *sync.Cond +} + +func (Self *connQueue) New() { + Self.chain = new(bufChain) + Self.chain.new(32) + locker := new(sync.Mutex) + Self.cond = sync.NewCond(locker) +} + +func (Self *connQueue) Push(connection *conn) { + Self.chain.pushHead(unsafe.Pointer(connection)) + Self.cond.Broadcast() + return +} + +func (Self *connQueue) Pop() (connection *conn) { + var iter bool + for { + connection = Self.TryPop() + if connection != nil { + return + } + if Self.stop { + return + } + if iter { + break + // trying to pop twice + } + iter = true + runtime.Gosched() + } + Self.cond.L.Lock() + defer Self.cond.L.Unlock() + for connection = Self.TryPop(); connection == nil; { + if Self.stop { + return + } + Self.cond.Wait() + // wait for it with no more iter + connection = Self.TryPop() + } + return +} + +func (Self *connQueue) TryPop() (connection *conn) { + ptr, ok := Self.chain.popTail() + if ok { + connection = (*conn)(ptr) + return + } + return +} + +func (Self *connQueue) Stop() { + Self.stop = true + Self.cond.Broadcast() +} + +type listElement struct { + Buf []byte + L uint16 + Part bool +} + +func (Self *listElement) Reset() { + Self.L = 0 + Self.Buf = nil + Self.Part = false +} + +func newListElement(buf []byte, l uint16, part bool) (element *listElement, err error) { + if uint16(len(buf)) != l { + err = errors.New("listElement: buf length not match") + return + } + element = listEle.Get() + element.Buf = buf + element.L = l + element.Part = part + return +} + +type receiveWindowQueue struct { + lengthWait uint64 + chain *bufChain + stopOp chan struct{} + readOp chan struct{} + // https://golang.org/pkg/sync/atomic/#pkg-note-BUG + // On non-Linux ARM, the 64-bit functions use instructions unavailable before the ARMv6k core. + // On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility + // to arrange for 64-bit alignment of 64-bit words accessed atomically. + // The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned. + + // if there are implicit struct, careful the first word + timeout time.Time +} + +func newReceiveWindowQueue() *receiveWindowQueue { + queue := receiveWindowQueue{ + chain: new(bufChain), + stopOp: make(chan struct{}, 2), + readOp: make(chan struct{}), + } + queue.chain.new(64) + return &queue +} + +func (Self *receiveWindowQueue) Push(element *listElement) { + var length, wait uint32 + for { + ptrs := atomic.LoadUint64(&Self.lengthWait) + length, wait = Self.chain.head.unpack(ptrs) + length += uint32(element.L) + if atomic.CompareAndSwapUint64(&Self.lengthWait, ptrs, Self.chain.head.pack(length, 0)) { + break + } + // another goroutine change the length or into wait, make sure + } + Self.chain.pushHead(unsafe.Pointer(element)) + if wait == 1 { + Self.allowPop() + } + return +} + +func (Self *receiveWindowQueue) Pop() (element *listElement, err error) { + var length uint32 +startPop: + ptrs := atomic.LoadUint64(&Self.lengthWait) + length, _ = Self.chain.head.unpack(ptrs) + if length == 0 { + if !atomic.CompareAndSwapUint64(&Self.lengthWait, ptrs, Self.chain.head.pack(0, 1)) { + goto startPop // another goroutine is pushing + } + err = Self.waitPush() + // there is no more data in queue, wait for it + if err != nil { + return + } + goto startPop // wait finish, trying to Get the New status + } + // length is not zero, so try to pop + for { + element = Self.TryPop() + if element != nil { + return + } + runtime.Gosched() // another goroutine is still pushing + } +} + +func (Self *receiveWindowQueue) TryPop() (element *listElement) { + ptr, ok := Self.chain.popTail() + if ok { + element = (*listElement)(ptr) + atomic.AddUint64(&Self.lengthWait, ^(uint64(element.L)<> dequeueBits) & mask) + tail = uint32(ptrs & mask) + return +} + +func (d *bufDequeue) pack(head, tail uint32) uint64 { + const mask = 1< 0 { + runtime.Gosched() + } + for { + ptrs := atomic.LoadUint64(&d.headTail) + head, tail := d.unpack(ptrs) + if (tail+uint32(len(d.vals)))&(1<= 3 && atomic.LoadUint32(&d.starving) > 0 { + atomic.StoreUint32(&d.starving, 0) + } + break + } + starve++ + if starve >= 3 { + atomic.StoreUint32(&d.starving, 1) + } + } + // The head slot is free, so we own it. + *slot = val + return true +} + +// popTail removes and returns the element at the tail of the queue. +// It returns false if the queue is empty. It may be called by any +// number of consumers. +func (d *bufDequeue) popTail() (unsafe.Pointer, bool) { + var val unsafe.Pointer + var head, tail uint32 + for { + ptrs := atomic.LoadUint64(&d.headTail) + head, tail = d.unpack(ptrs) + if tail == head { + // Queue is empty. + return nil, false + } + slot := &d.vals[tail&uint32(len(d.vals)-1)] + val = atomic.LoadPointer(slot) + if val != nil { + // We now get a slot. + if atomic.CompareAndSwapPointer(slot, val, nil) { + break + // Tell pushHead that we're done with this slot. Zeroing the + // slot is also important so we don't leave behind references + // that could keep this object live longer than necessary. + // + // We write to val first and then publish that we're done with + } + } + // Maybe the value was taken by other goroutine or not push yet. + } + // At this point pushHead owns the slot. + if tail < math.MaxUint32 { + atomic.AddUint64(&d.headTail, 1) + } else { + atomic.AddUint64(&d.headTail, ^uint64(math.MaxUint32-1)) + } + return val, true +} + +// bufChain is a dynamically-sized version of bufDequeue. +// +// This is implemented as a doubly-linked list queue of poolDequeues +// where each dequeue is double the size of the previous one. Once a +// dequeue fills up, this allocates a New one and only ever pushes to +// the latest dequeue. Pops happen from the other end of the list and +// once a dequeue is exhausted, it gets removed from the list. +type bufChain struct { + // head is the bufDequeue to push to. This is only accessed + // by the producer, so doesn't need to be synchronized. + head *bufChainElt + + // tail is the bufDequeue to popTail from. This is accessed + // by consumers, so reads and writes must be atomic. + tail *bufChainElt + newChain uint32 +} + +type bufChainElt struct { + bufDequeue + + // next and prev link to the adjacent poolChainElts in this + // bufChain. + // + // next is written atomically by the producer and read + // atomically by the consumer. It only transitions from nil to + // non-nil. + // + // prev is written atomically by the consumer and read + // atomically by the producer. It only transitions from + // non-nil to nil. + next, prev *bufChainElt +} + +func storePoolChainElt(pp **bufChainElt, v *bufChainElt) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(pp)), unsafe.Pointer(v)) +} + +func loadPoolChainElt(pp **bufChainElt) *bufChainElt { + return (*bufChainElt)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(pp)))) +} + +func (c *bufChain) new(initSize int) { + // Initialize the chain. + // initSize must be a power of 2 + d := new(bufChainElt) + d.vals = make([]unsafe.Pointer, initSize) + storePoolChainElt(&c.head, d) + storePoolChainElt(&c.tail, d) +} + +func (c *bufChain) pushHead(val unsafe.Pointer) { +startPush: + for { + if atomic.LoadUint32(&c.newChain) > 0 { + runtime.Gosched() + } else { + break + } + } + + d := loadPoolChainElt(&c.head) + + if d.pushHead(val) { + return + } + + // The current dequeue is full. Allocate a New one of twice + // the size. + if atomic.CompareAndSwapUint32(&c.newChain, 0, 1) { + newSize := len(d.vals) * 2 + if newSize >= dequeueLimit { + // Can't make it any bigger. + newSize = dequeueLimit + } + + d2 := &bufChainElt{prev: d} + d2.vals = make([]unsafe.Pointer, newSize) + d2.pushHead(val) + storePoolChainElt(&c.head, d2) + storePoolChainElt(&d.next, d2) + atomic.StoreUint32(&c.newChain, 0) + return + } + goto startPush +} + +func (c *bufChain) popTail() (unsafe.Pointer, bool) { + d := loadPoolChainElt(&c.tail) + if d == nil { + return nil, false + } + + for { + // It's important that we load the next pointer + // *before* popping the tail. In general, d may be + // transiently empty, but if next is non-nil before + // the TryPop and the TryPop fails, then d is permanently + // empty, which is the only condition under which it's + // safe to drop d from the chain. + d2 := loadPoolChainElt(&d.next) + + if val, ok := d.popTail(); ok { + return val, ok + } + + if d2 == nil { + // This is the only dequeue. It's empty right + // now, but could be pushed to in the future. + return nil, false + } + + // The tail of the chain has been drained, so move on + // to the next dequeue. Try to drop it from the chain + // so the next TryPop doesn't have to look at the empty + // dequeue again. + if atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&c.tail)), unsafe.Pointer(d), unsafe.Pointer(d2)) { + // We won the race. Clear the prev pointer so + // the garbage collector can collect the empty + // dequeue and so popHead doesn't back up + // further than necessary. + storePoolChainElt(&d2.prev, nil) + } + d = d2 + } +} diff --git a/lib/nps_mux/rate.go b/lib/nps_mux/rate.go new file mode 100644 index 0000000..d81d612 --- /dev/null +++ b/lib/nps_mux/rate.go @@ -0,0 +1,132 @@ +package nps_mux + +import ( + "net" + "sync/atomic" + "time" +) + +type Rate struct { + bucketSize int64 + bucketSurplusSize int64 + bucketAddSize int64 + stopChan chan bool + NowRate int64 +} + +func NewRate(addSize int64) *Rate { + return &Rate{ + bucketSize: addSize * 2, + bucketSurplusSize: 0, + bucketAddSize: addSize, + stopChan: make(chan bool), + } +} + +func (s *Rate) Start() { + go s.session() +} + +func (s *Rate) add(size int64) { + if res := s.bucketSize - s.bucketSurplusSize; res < s.bucketAddSize { + atomic.AddInt64(&s.bucketSurplusSize, res) + return + } + atomic.AddInt64(&s.bucketSurplusSize, size) +} + +//回桶 +func (s *Rate) ReturnBucket(size int64) { + s.add(size) +} + +//停止 +func (s *Rate) Stop() { + s.stopChan <- true +} + +func (s *Rate) Get(size int64) { + if s.bucketSurplusSize >= size { + atomic.AddInt64(&s.bucketSurplusSize, -size) + return + } + ticker := time.NewTicker(time.Millisecond * 100) + for { + select { + case <-ticker.C: + if s.bucketSurplusSize >= size { + atomic.AddInt64(&s.bucketSurplusSize, -size) + ticker.Stop() + return + } + } + } +} + +func (s *Rate) session() { + ticker := time.NewTicker(time.Second * 1) + for { + select { + case <-ticker.C: + if rs := s.bucketAddSize - s.bucketSurplusSize; rs > 0 { + s.NowRate = rs + } else { + s.NowRate = s.bucketSize - s.bucketSurplusSize + } + s.add(s.bucketAddSize) + case <-s.stopChan: + ticker.Stop() + return + } + } +} + +type Conn struct { + conn net.Conn + rate *Rate +} + +func NewRateConn(rate *Rate, conn net.Conn) *Conn { + return &Conn{ + conn: conn, + rate: rate, + } +} + +func (conn *Conn) Read(b []byte) (n int, err error) { + defer func() { + conn.rate.Get(int64(n)) + }() + return conn.conn.Read(b) +} + +func (conn *Conn) Write(b []byte) (n int, err error) { + defer func() { + conn.rate.Get(int64(n)) + }() + return conn.conn.Write(b) +} + +func (conn *Conn) LocalAddr() net.Addr { + return conn.conn.LocalAddr() +} + +func (conn *Conn) RemoteAddr() net.Addr { + return conn.conn.RemoteAddr() +} + +func (conn *Conn) SetDeadline(t time.Time) error { + return conn.conn.SetDeadline(t) +} + +func (conn *Conn) SetWriteDeadline(t time.Time) error { + return conn.conn.SetWriteDeadline(t) +} + +func (conn *Conn) SetReadDeadline(t time.Time) error { + return conn.conn.SetReadDeadline(t) +} + +func (conn *Conn) Close() error { + return conn.conn.Close() +} diff --git a/lib/nps_mux/sysGetsock_nowindows.go b/lib/nps_mux/sysGetsock_nowindows.go new file mode 100644 index 0000000..c27ffc6 --- /dev/null +++ b/lib/nps_mux/sysGetsock_nowindows.go @@ -0,0 +1,37 @@ +//go:build !windows +// +build !windows + +package nps_mux + +import ( + "net" + "os" + "syscall" +) + +func sysGetSock(fd *os.File) (bufferSize int, err error) { + if fd != nil { + return syscall.GetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_RCVBUF) + } else { + return 5 * 1024 * 1024, nil + } +} + +func getConnFd(c net.Conn) (fd *os.File, err error) { + switch c.(type) { + case *net.TCPConn: + fd, err = c.(*net.TCPConn).File() + if err != nil { + return + } + return + case *net.UDPConn: + fd, err = c.(*net.UDPConn).File() + if err != nil { + return + } + return + default: + return + } +} diff --git a/lib/nps_mux/sysGetsock_windows.go b/lib/nps_mux/sysGetsock_windows.go new file mode 100644 index 0000000..814eb65 --- /dev/null +++ b/lib/nps_mux/sysGetsock_windows.go @@ -0,0 +1,37 @@ +//go:build windows +// +build windows + +package nps_mux + +import ( + "net" + "os" +) + +func sysGetSock(fd *os.File) (bufferSize int, err error) { + // https://github.com/golang/sys/blob/master/windows/syscall_windows.go#L1184 + // not support, WTF??? + // Todo + // return syscall.GetsockoptInt((syscall.Handle)(unsafe.Pointer(fd.Fd())), syscall.SOL_SOCKET, syscall.SO_RCVBUF) + bufferSize = 15 * 1024 * 1024 + return +} + +func getConnFd(c net.Conn) (fd *os.File, err error) { + switch c.(type) { + case *net.TCPConn: + //fd, err = c.(*net.TCPConn).File() + //if err != nil { + // return + //} + return + case *net.UDPConn: + //fd, err = c.(*net.UDPConn).File() + //if err != nil { + // return + //} + return + default: + return + } +} diff --git a/lib/nps_mux/tc.go b/lib/nps_mux/tc.go new file mode 100644 index 0000000..751a89d --- /dev/null +++ b/lib/nps_mux/tc.go @@ -0,0 +1,224 @@ +package nps_mux + +import ( + "bytes" + "errors" + "fmt" + "math" + "net" + "os/exec" + "strings" +) + +type Eth struct { + EthName string + EthAddr string +} + +type TrafficControl struct { + Eth *Eth + params []string +} + +func Ips() (map[string]string, error) { + + ips := make(map[string]string) + + interfaces, err := net.Interfaces() + if err != nil { + return nil, err + } + + for _, i := range interfaces { + byName, err := net.InterfaceByName(i.Name) + if err != nil { + return nil, err + } + if !strings.Contains(byName.Name, "Loopback") && !strings.Contains(byName.Name, "isatap") { + addresses, _ := byName.Addrs() + for _, v := range addresses { + ips[byName.Name] = v.String() + } + } + } + return ips, nil +} + +// get ip and Eth information by Eth name +func GetEthByIp(ipAddr string) (eth *Eth, err error) { + var interfaces []net.Interface + interfaces, err = net.Interfaces() + if err != nil { + return + } + for _, i := range interfaces { + var byName *net.Interface + byName, err = net.InterfaceByName(i.Name) + if err != nil { + return + } + // except lo + if !strings.Contains(byName.Name, "Loopback") && !strings.Contains(byName.Name, "isatap") && !strings.Contains(byName.Name, "lo") { + addresses, _ := byName.Addrs() + for _, v := range addresses { + ipMask := strings.Split(v.String(), "/") + if len(ipMask) == 2 { + if ipAddr == "" || ipMask[0] == ipAddr { + eth = new(Eth) + eth.EthAddr = ipMask[0] + eth.EthName = byName.Name + return + } + } + } + } + } + err = errors.New("not found interface") + return +} + +type tcFunc func() + +func getArrayExhaustivity(arr []tcFunc) (result [][]tcFunc) { + var l = int(math.Pow(float64(2), float64(len(arr))) - 1) + var t []tcFunc + for i := 1; i <= l; i++ { + s := i + t = []tcFunc{} + for k := 0; s > 0; k++ { + if s&1 == 1 { + t = append(t, arr[k]) + } + s >>= 1 + } + result = append(result, t) + } + return +} + +func NewTrafficControl(ipAddr string) (*TrafficControl, error) { + Eth, err := GetEthByIp(ipAddr) + if err != nil { + return nil, err + } + t := new(TrafficControl) + t.params = make([]string, 0) + t.Eth = Eth + return t, nil +} + +// test the network randomly +func (tc *TrafficControl) RunNetRangeTest(f func()) error { + funcs := tc.getTestVariable() + groups := getArrayExhaustivity(funcs) + for _, v := range groups { + tc.del() + // execute bandwidth control, not good work + //if err := tc.bandwidth("1mbit"); err != nil { + // return err + //} + // execute random strategy + for _, vv := range v { + vv() + } + err := tc.Run() + if err != nil { + return err + } + // execute test func + f() + // clear strategy + if err := tc.del(); err != nil { + return err + } + } + return nil +} + +// create test variables +func (tc *TrafficControl) getTestVariable() []tcFunc { + return []tcFunc{ + func() { tc.delay("add", "100ms", "10ms", "30%") }, + func() { tc.loss("add", "1%", "30%") }, + func() { tc.duplicate("add", "1%") }, + func() { tc.corrupt("add", "0.2%") }, + } +} + +// this command sets the transmission of the network card to delayVal. At the same time, +// about waveRatio of the packets will be delayed by ± wave. +func (tc *TrafficControl) delay(opt, delayVal, wave, waveRatio string) { + tc.params = append(tc.params, []string{"delay", delayVal, wave, waveRatio}...) +} + +// this command sets the transmission of the network card to randomly drop lossRatio of packets with a success rate of lossSuccessRatio. +func (tc *TrafficControl) loss(opt, lossRatio, lossSuccessRatio string) { + tc.params = append(tc.params, []string{"loss", lossRatio, lossSuccessRatio}...) +} + +// this command sets the transmission of the network card to randomly generate repeatRatio duplicate packets +func (tc *TrafficControl) duplicate(opt, duplicateRatio string) { + tc.params = append(tc.params, []string{"duplicate", duplicateRatio}...) +} + +// this command sets the transmission of the network card to randomly generate corruptRatio corrupted packets. +// the kernel version must be above 2.6.16 +func (tc *TrafficControl) corrupt(opt, corruptRatio string) { + tc.params = append(tc.params, []string{"corrupt", corruptRatio}...) +} + +func (tc *TrafficControl) Run() error { + tc.params = append([]string{"qdisc", "add", "dev", tc.Eth.EthName, "root", "netem"}, tc.params...) + return runCmd(exec.Command("tc", tc.params...)) +} + +// remove all tc setting +func (tc *TrafficControl) del() error { + tc.clear() + return runCmd(exec.Command("tc", "qdisc", "del", "dev", tc.Eth.EthName, "root")) +} + +// clear the old settings +func (tc *TrafficControl) clear() { + tc.params = tc.params[:0] +} + +// remove all tc setting +func (tc *TrafficControl) bandwidth(bw string) error { + runCmd(exec.Command("tc", "qdisc", "add", "dev", tc.Eth.EthName, "root", "handle", "2:", "htb", "default", "30")) + return runCmd(exec.Command("tc", "qdisc", "add", "dev", tc.Eth.EthName, "parent", "2:", "classid", "2:30", "htb", "rate", bw)) +} + +func runCmd(cmd *exec.Cmd) error { + fmt.Println("run cmd:", cmd.Args) + var out bytes.Buffer + var stderr bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &stderr + err := cmd.Run() + if err != nil { + fmt.Println(fmt.Sprint(err) + ": " + stderr.String()) + return err + } + return nil +} + +func createNetwork(name, networok string) error { + // docker network create --subnet=172.18.0.0/16 test + return runCmd(exec.Command("docker", "network", "create", "--subnet="+networok, name)) +} + +func deleteNetwork(name string) error { + return runCmd(exec.Command("docker", "network", "rm", name)) +} + +func runDocker(dockerName, networkName, ip, testFunName, nowDir string) error { + // docker run --env GOPROXY=https://goproxy.cn --rm --name client --net test --cap-add=NET_ADMIN --ip 172.18.0.5 -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang go test -v -run TestClient ./ + return runCmd(exec.Command("docker", "run", "--env", "GOPROXY=https://goproxy.cn", "--rm", "--name", dockerName, "--net", networkName, + "--cap-add=NET_ADMIN", "--ip", ip, "-v", nowDir+`:/usr/src/myapp`, "-w", `/usr/src/myapp`, "golang", "go", "test", + "-v", "-run", testFunName, "./")) +} + +func stopDocker(dockerName string) error { + return runCmd(exec.Command("docker", "stop", dockerName)) +} diff --git a/server/server.go b/server/server.go index cafadce..2c53df4 100644 --- a/server/server.go +++ b/server/server.go @@ -249,7 +249,7 @@ func GetTunnel(start, length int, typeVal string, clientId int, search string) ( if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) { continue } - if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search)) { + if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search) || strings.Contains(v.Client.VerifyKey, search)) { continue } cnt++ diff --git a/server/tool/utils.go b/server/tool/utils.go index 38e40dc..fb37c16 100644 --- a/server/tool/utils.go +++ b/server/tool/utils.go @@ -2,6 +2,7 @@ package tool import ( "math" + "math/rand" "strconv" "time" @@ -50,6 +51,20 @@ func TestServerPort(p int, m string) (b bool) { return } +func GenerateServerPort(m string) int { + for { + //生成随机数 1024 - 65535 + serverPort := rand.Intn(65535) + if serverPort < 1024 { + serverPort = 1024 + } + + if TestServerPort(serverPort, m) { + return serverPort + } + } +} + func getSeverStatus() { for { if len(ServerStatus) < 10 { diff --git a/web/controllers/base.go b/web/controllers/base.go index d1cd799..95da9b9 100755 --- a/web/controllers/base.go +++ b/web/controllers/base.go @@ -125,6 +125,13 @@ func (s *BaseController) AjaxOk(str string) { s.StopRun() } +//ajax正确返回 +func (s *BaseController) AjaxOkWithId(str string, id int) { + s.Data["json"] = ajaxWithId(str, 1, id) + s.ServeJSON() + s.StopRun() +} + //ajax错误返回 func (s *BaseController) AjaxErr(str string) { s.Data["json"] = ajax(str, 0) @@ -140,6 +147,15 @@ func ajax(str string, status int) map[string]interface{} { return json } +//组装ajax +func ajaxWithId(str string, status int, id int) map[string]interface{} { + json := make(map[string]interface{}) + json["status"] = status + json["msg"] = str + json["id"] = id + return json +} + //ajax table返回 func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int, kwargs map[string]interface{}) { json := make(map[string]interface{}) diff --git a/web/controllers/client.go b/web/controllers/client.go index 5d4a82a..34e398a 100644 --- a/web/controllers/client.go +++ b/web/controllers/client.go @@ -44,9 +44,10 @@ func (s *ClientController) Add() { s.SetInfo("add client") s.display() } else { + id := int(file.GetDb().JsonDb.GetClientId()) t := &file.Client{ VerifyKey: s.getEscapeString("vkey"), - Id: int(file.GetDb().JsonDb.GetClientId()), + Id: id, Status: true, Remark: s.getEscapeString("remark"), Cnf: &file.Config{ @@ -71,7 +72,7 @@ func (s *ClientController) Add() { if err := file.GetDb().NewClient(t); err != nil { s.AjaxErr(err.Error()) } - s.AjaxOk("add success") + s.AjaxOkWithId("add success", id) } } func (s *ClientController) GetClient() { diff --git a/web/controllers/index.go b/web/controllers/index.go index 0e7fc53..57c7d2c 100755 --- a/web/controllers/index.go +++ b/web/controllers/index.go @@ -92,12 +92,13 @@ func (s *IndexController) Add() { s.SetInfo("add tunnel") s.display() } else { + id := int(file.GetDb().JsonDb.GetTaskId()) t := &file.Tunnel{ Port: s.GetIntNoErr("port"), ServerIp: s.getEscapeString("server_ip"), Mode: s.getEscapeString("type"), Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")}, - Id: int(file.GetDb().JsonDb.GetTaskId()), + Id: id, Status: true, Remark: s.getEscapeString("remark"), Password: s.getEscapeString("password"), @@ -105,6 +106,11 @@ func (s *IndexController) Add() { StripPre: s.getEscapeString("strip_pre"), Flow: &file.Flow{}, } + + if t.Port <= 0 { + t.Port = tool.GenerateServerPort(t.Mode) + } + if !tool.TestServerPort(t.Port, t.Mode) { s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.") } @@ -121,7 +127,7 @@ func (s *IndexController) Add() { if err := server.AddTask(t); err != nil { s.AjaxErr(err.Error()) } else { - s.AjaxOk("add success") + s.AjaxOkWithId("add success", id) } } } @@ -158,11 +164,16 @@ func (s *IndexController) Edit() { t.Client = client } if s.GetIntNoErr("port") != t.Port { + t.Port = s.GetIntNoErr("port") + + if t.Port <= 0 { + t.Port = tool.GenerateServerPort(t.Mode) + } + if !tool.TestServerPort(s.GetIntNoErr("port"), t.Mode) { s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.") return } - t.Port = s.GetIntNoErr("port") } t.ServerIp = s.getEscapeString("server_ip") t.Mode = s.getEscapeString("type") @@ -248,8 +259,9 @@ func (s *IndexController) AddHost() { s.SetInfo("add host") s.display("index/hadd") } else { + id := int(file.GetDb().JsonDb.GetHostId()) h := &file.Host{ - Id: int(file.GetDb().JsonDb.GetHostId()), + Id: id, Host: s.getEscapeString("host"), Target: &file.Target{TargetStr: s.getEscapeString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")}, HeaderChange: s.getEscapeString("header"), @@ -268,7 +280,7 @@ func (s *IndexController) AddHost() { if err := file.GetDb().NewHost(h); err != nil { s.AjaxErr("add fail" + err.Error()) } - s.AjaxOk("add success") + s.AjaxOkWithId("add success", id) } } diff --git a/web/static/css/style.css b/web/static/css/style.css index 0a9c3f3..996bbf0 100644 --- a/web/static/css/style.css +++ b/web/static/css/style.css @@ -1,5 +1,5 @@ -@import url("https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700"); -@import url("https://fonts.googleapis.com/css?family=Roboto:400,300,500,700"); +/*@import url("https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700");*/ +/*@import url("https://fonts.googleapis.com/css?family=Roboto:400,300,500,700");*/ /* * * INSPINIA - Responsive Admin Theme diff --git a/web/static/page/languages.xml b/web/static/page/languages.xml index 1d173c7..e9c2be9 100644 --- a/web/static/page/languages.xml +++ b/web/static/page/languages.xml @@ -432,7 +432,7 @@ Server IP - 服务端端口 + 服务端端口(留空自动生成) Server Port diff --git a/web/views/index/hlist.html b/web/views/index/hlist.html index e3613c4..f19a9df 100644 --- a/web/views/index/hlist.html +++ b/web/views/index/hlist.html @@ -97,6 +97,12 @@ halign: 'center', visible: true//false表示不显示 }, + { + field: 'Client.VerifyKey',//域值 + title: '',//标题 + halign: 'center', + visible: true//false表示不显示 + }, { field: 'Host',//域值 title: '',//标题 diff --git a/web/views/index/list.html b/web/views/index/list.html index 2bd63ef..dbd5738 100644 --- a/web/views/index/list.html +++ b/web/views/index/list.html @@ -114,6 +114,12 @@ halign: 'center', visible: true//false表示不显示 }, + { + field: 'Client.VerifyKey',//域值 + title: '',//标题 + halign: 'center', + visible: true//false表示不显示 + }, { field: 'Mode',//域值 title: '',//标题