p2p secret

This commit is contained in:
刘河
2019-04-13 19:48:34 +08:00
parent 0cc0e82c5d
commit 6a978515ca
7 changed files with 39 additions and 19 deletions

View File

@@ -357,19 +357,30 @@ func sendP2PTestMsg(remoteAddr string, localAddr string) (string, error) {
return "", err
}
localConn, err := newUdpConnByAddr(localAddr)
defer localConn.Close()
if err != nil {
return "", err
}
buf := make([]byte, 10)
for i := 20; i > 0; i-- {
logs.Trace("try send test packet to target %s", remoteAddr)
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
return "", err
defer localConn.Close()
ticker := time.NewTicker(time.Millisecond * 500)
go func(ticker *time.Ticker) {
for {
select {
case <-ticker.C:
logs.Trace("try send test packet to target %s", remoteAddr)
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
return
}
}
}
localConn.SetReadDeadline(time.Now().Add(time.Millisecond * 500))
}(ticker)
buf := make([]byte, 10)
for {
localConn.SetReadDeadline(time.Now().Add(time.Second * 30))
n, addr, err := localConn.ReadFromUDP(buf)
localConn.SetReadDeadline(time.Time{})
if err != nil {
break
}
switch string(buf[:n]) {
case common.WORK_P2P_SUCCESS:
for i := 20; i > 0; i-- {
@@ -391,9 +402,12 @@ func sendP2PTestMsg(remoteAddr string, localAddr string) (string, error) {
time.Sleep(time.Second)
}
}()
default:
continue
}
ticker.Stop()
}
localConn.Close()
ticker.Stop()
return "", errors.New("connect to the target failed, maybe the nat type is not support p2p")
}

View File

@@ -20,6 +20,7 @@ var (
muxSession *mux.Mux
fileServer []*http.Server
lock sync.Mutex
hasP2PTry bool
)
func CloseLocalServer() {
@@ -81,12 +82,18 @@ func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *con
restart:
lock.Lock()
if udpConn == nil {
newUdpConn(config, l)
if !hasP2PTry {
hasP2PTry = true
newUdpConn(config, l)
}
if udpConn == nil {
lock.Unlock()
logs.Notice("new conn, P2P can not penetrate successfully, traffic will be transferred through the server")
handleSecret(localTcpConn, config, l)
return
} else {
muxSession = mux.NewMux(udpConn, "kcp")
}
muxSession = mux.NewMux(udpConn, "kcp")
}
lock.Unlock()
logs.Trace("start trying to connect with the server")