Skip to content

Commit

Permalink
3.21.8
Browse files Browse the repository at this point in the history
  • Loading branch information
TenderIronh committed Oct 20, 2024
1 parent c68094c commit df1e16e
Show file tree
Hide file tree
Showing 14 changed files with 188 additions and 49 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ wintun.dll
.vscode/
app/.idea/
*_debug_bin*
cmd/openp2p
cmd/openp2p
vendor/
2 changes: 1 addition & 1 deletion README-ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Windows默认会阻止没有花钱买它家证书签名过的程序,选择“
服务端有个调度模型,根据带宽、ping值、稳定性、服务时长,尽可能地使共享节点均匀地提供服务。连接共享节点使用TOTP密码,hmac-sha256算法校验,它是一次性密码,和我们平时使用的手机验证码或银行密码器一样的原理。

## 编译
go version go1.18.1+
go version 1.20 only (支持win7)
cd到代码根目录,执行
```
make
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ That's right, the relay node is naturally an man-in-middle, so AES encryption is
The server side has a scheduling model, which calculate bandwith, ping value,stability and service duration to provide a well-proportioned service to every share node. It uses TOTP(Time-based One-time Password) with hmac-sha256 algorithem, its theory as same as the cellphone validation code or bank cipher coder.

## Build
go version go1.18.1+
go version 1.20 only (support win7)
cd root directory of the socure code and execute
```
make
Expand Down
13 changes: 13 additions & 0 deletions core/common_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package openp2p

import (
"fmt"
"log"
"testing"
)
Expand Down Expand Up @@ -114,3 +115,15 @@ func TestIsIPv6(t *testing.T) {
}
}
}

func TestNodeID(t *testing.T) {
node1 := "n1-stable"
node2 := "tony-stable"
nodeID1 := NodeNameToID(node1)
nodeID2 := NodeNameToID(node2)
if nodeID1 < nodeID2 {
fmt.Printf("%s < %s\n", node1, node2)
} else {
fmt.Printf("%s >= %s\n", node1, node2)
}
}
38 changes: 20 additions & 18 deletions core/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,13 @@ type Config struct {
Apps []*AppConfig `json:"apps"`

LogLevel int
MaxLogSize int
daemonMode bool
mtx sync.Mutex
sdwanMtx sync.Mutex
sdwan SDWANInfo
delNodes []SDWANNode
addNodes []SDWANNode
delNodes []*SDWANNode
addNodes []*SDWANNode
}

func (c *Config) getSDWAN() SDWANInfo {
Expand All @@ -92,23 +93,30 @@ func (c *Config) getSDWAN() SDWANInfo {
return c.sdwan
}

func (c *Config) getDelNodes() []SDWANNode {
func (c *Config) getDelNodes() []*SDWANNode {
c.sdwanMtx.Lock()
defer c.sdwanMtx.Unlock()
return c.delNodes
}

func (c *Config) getAddNodes() []SDWANNode {
func (c *Config) getAddNodes() []*SDWANNode {
c.sdwanMtx.Lock()
defer c.sdwanMtx.Unlock()
return c.addNodes
}

func (c *Config) resetSDWAN() {
c.sdwanMtx.Lock()
defer c.sdwanMtx.Unlock()
c.delNodes = []*SDWANNode{}
c.addNodes = []*SDWANNode{}
c.sdwan = SDWANInfo{}
}
func (c *Config) setSDWAN(s SDWANInfo) {
c.sdwanMtx.Lock()
defer c.sdwanMtx.Unlock()
// get old-new
c.delNodes = []SDWANNode{}
c.delNodes = []*SDWANNode{}
for _, oldNode := range c.sdwan.Nodes {
isDeleted := true
for _, newNode := range s.Nodes {
Expand All @@ -122,7 +130,7 @@ func (c *Config) setSDWAN(s SDWANInfo) {
}
}
// get new-old
c.addNodes = []SDWANNode{}
c.addNodes = []*SDWANNode{}
for _, newNode := range s.Nodes {
isNew := true
for _, oldNode := range c.sdwan.Nodes {
Expand Down Expand Up @@ -230,17 +238,8 @@ func (c *Config) delete(app AppConfig) {
defer c.mtx.Unlock()
defer c.save()
for i := 0; i < len(c.Apps); i++ {
got := false
if app.SrcPort != 0 { // normal p2papp
if c.Apps[i].Protocol == app.Protocol && c.Apps[i].SrcPort == app.SrcPort {
got = true
}
} else { // memapp
if c.Apps[i].PeerNode == app.PeerNode {
got = true
}
}
if got {
if (app.SrcPort != 0 && c.Apps[i].Protocol == app.Protocol && c.Apps[i].SrcPort == app.SrcPort) || // normal app
(app.SrcPort == 0 && c.Apps[i].PeerNode == app.PeerNode) { // memapp
if i == len(c.Apps)-1 {
c.Apps = c.Apps[:i]
} else {
Expand All @@ -249,7 +248,6 @@ func (c *Config) delete(app AppConfig) {
return
}
}

}

func (c *Config) save() {
Expand Down Expand Up @@ -280,6 +278,7 @@ func (c *Config) saveCache() {

func init() {
gConf.LogLevel = int(LvINFO)
gConf.MaxLogSize = 1024 * 1024
gConf.Network.ShareBandwidth = 10
gConf.Network.ServerHost = "api.openp2p.cn"
gConf.Network.ServerPort = WsPort
Expand Down Expand Up @@ -463,6 +462,9 @@ func parseParams(subCommand string, cmd string) {
if f.Name == "loglevel" {
gConf.LogLevel = *logLevel
}
if f.Name == "maxlogsize" {
gConf.MaxLogSize = *maxLogSize
}
if f.Name == "tcpport" {
gConf.Network.TCPPort = *tcpPort
}
Expand Down
13 changes: 7 additions & 6 deletions core/optun_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func addRoute(dst, gw, ifname string) error {
}

func delRoute(dst, gw string) error {
err := exec.Command("route", "delete", dst, gw).Run()
err := exec.Command("route", "delete", dst, "-gateway", gw).Run()
return err
}
func delRoutesByGateway(gateway string) error {
Expand All @@ -68,13 +68,14 @@ func delRoutesByGateway(gateway string) error {
continue
}
fields := strings.Fields(line)
if len(fields) >= 7 && fields[0] == "default" && fields[len(fields)-1] == gateway {
delCmd := exec.Command("route", "delete", "default", gateway)
err := delCmd.Run()
if len(fields) >= 2 {
cmd := exec.Command("route", "delete", fields[0], gateway)
err := cmd.Run()
if err != nil {
return err
gLog.Printf(LvERROR, "Delete route %s error:%s", fields[0], err)
continue
}
fmt.Printf("Delete route ok: %s %s\n", "default", gateway)
gLog.Printf(LvINFO, "Delete route ok: %s %s\n", fields[0], gateway)
}
}
return nil
Expand Down
5 changes: 3 additions & 2 deletions core/optun_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,10 @@ func delRoutesByGateway(gateway string) error {
delCmd := exec.Command("route", "del", "-net", fields[0], "gw", gateway)
err := delCmd.Run()
if err != nil {
return err
gLog.Printf(LvERROR, "Delete route %s error:%s", fields[0], err)
continue
}
fmt.Printf("Delete route ok: %s %s %s\n", fields[0], fields[1], gateway)
gLog.Printf(LvINFO, "Delete route ok: %s %s %s\n", fields[0], fields[1], gateway)
}
}
return nil
Expand Down
5 changes: 3 additions & 2 deletions core/optun_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,10 @@ func delRoutesByGateway(gateway string) error {
cmd := exec.Command("route", "delete", fields[0], "mask", fields[1], gateway)
err := cmd.Run()
if err != nil {
fmt.Println("Delete route error:", err)
gLog.Printf(LvERROR, "Delete route %s error:%s", fields[0], err)
continue
}
fmt.Printf("Delete route ok: %s %s %s\n", fields[0], fields[1], gateway)
gLog.Printf(LvINFO, "Delete route ok: %s %s %s\n", fields[0], fields[1], gateway)
}
}
return nil
Expand Down
2 changes: 2 additions & 0 deletions core/p2pnetwork.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func (pn *P2PNetwork) run() {
pn.write(MsgHeartbeat, 0, "")
case <-pn.restartCh:
gLog.Printf(LvDEBUG, "got restart channel")
GNetwork.sdwan.reset()
pn.online = false
pn.wgReconnect.Wait() // wait read/autorunapp goroutine end
delay := ClientAPITimeout + time.Duration(rand.Int()%pn.loginMaxDelaySeconds)*time.Second
Expand All @@ -124,6 +125,7 @@ func (pn *P2PNetwork) run() {
gLog.Println(LvERROR, "P2PNetwork init error:", err)
}
gConf.retryAllApp()

case t := <-pn.tunnelCloseCh:
gLog.Printf(LvDEBUG, "got tunnelCloseCh %s", t.config.LogPeerNode())
pn.apps.Range(func(id, i interface{}) bool {
Expand Down
12 changes: 6 additions & 6 deletions core/p2ptunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ func (t *P2PTunnel) connectUnderlayTCPSymmetric() (c underlay, err error) {
}
_, buff, err := ul.ReadBuffer()
if err != nil {
gLog.Printf(LvERROR, "utcp.ReadBuffer error:", err)
gLog.Println(LvDEBUG, "c2s ul.ReadBuffer error:", err)
return
}
req := P2PHandshakeReq{}
Expand Down Expand Up @@ -455,7 +455,7 @@ func (t *P2PTunnel) connectUnderlayTCPSymmetric() (c underlay, err error) {

_, buff, err := ul.ReadBuffer()
if err != nil {
gLog.Printf(LvERROR, "utcp.ReadBuffer error:", err)
gLog.Println(LvDEBUG, "s2c ul.ReadBuffer error:", err)
return
}
req := P2PHandshakeReq{}
Expand Down Expand Up @@ -512,14 +512,14 @@ func (t *P2PTunnel) connectUnderlayTCP6() (c underlay, err error) {
t.pn.read(t.config.PeerNode, MsgPush, MsgPushUnderlayConnect, ReadMsgTimeout)
gLog.Println(LvDEBUG, "TCP6 dial to ", t.config.peerIPv6)
ul, err = dialTCP6(t.config.peerIPv6, t.config.peerConeNatPort)
if err != nil {
if err != nil || ul == nil {
return nil, fmt.Errorf("TCP6 dial to %s:%d error:%s", t.config.peerIPv6, t.config.peerConeNatPort, err)
}
handshakeBegin := time.Now()
ul.WriteBytes(MsgP2P, MsgTunnelHandshake, []byte("OpenP2P,hello"))
_, buff, err := ul.ReadBuffer()
if err != nil {
return nil, fmt.Errorf("read MsgTunnelHandshake error:%s", err)
_, buff, errR := ul.ReadBuffer()
if errR != nil {
return nil, fmt.Errorf("read MsgTunnelHandshake error:%s", errR)
}
if buff != nil {
gLog.Println(LvDEBUG, string(buff))
Expand Down
87 changes: 87 additions & 0 deletions core/ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package openp2p

import (
"fmt"
"net"
"os"
"time"

"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
)

// 定义ICMP回显请求和应答的结构
type ICMPMessage struct {
Type uint8
Code uint8
Checksum uint16
Ident uint16
Seq uint16
Data []byte
}

// Ping sends an ICMP Echo request to the specified host and returns the response time.
func Ping(host string) (time.Duration, error) {
// Resolve the IP address of the host
ipAddr, err := net.ResolveIPAddr("ip4", host)
if err != nil {
return 0, fmt.Errorf("failed to resolve host: %v", err)
}

// Create an ICMP listener
conn, err := net.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
return 0, fmt.Errorf("failed to create ICMP connection: %v", err)
}
defer conn.Close()

// Create an ICMP Echo request message
message := icmp.Message{
Type: ipv4.ICMPTypeEcho,
Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff,
Seq: 1,
Data: []byte("HELLO-R-U-THERE"),
},
}

// Marshal the message into binary form
messageBytes, err := message.Marshal(nil)
if err != nil {
return 0, fmt.Errorf("failed to marshal ICMP message: %v", err)
}

// Send the ICMP Echo request
start := time.Now()
if _, err := conn.WriteTo(messageBytes, ipAddr); err != nil {
return 0, fmt.Errorf("failed to send ICMP request: %v", err)
}

// Set a deadline for the response
err = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
if err != nil {
return 0, fmt.Errorf("failed to set read deadline: %v", err)
}

// Read the ICMP response
response := make([]byte, 1500)
n, _, err := conn.ReadFrom(response)
if err != nil {
return 0, fmt.Errorf("failed to read ICMP response: %v", err)
}

// Parse the ICMP response message
parsedMessage, err := icmp.ParseMessage(ipv4.ICMPTypeEchoReply.Protocol(), response[:n])
if err != nil {
return 0, fmt.Errorf("failed to parse ICMP response: %v", err)
}

// Check if the response is an Echo reply
if parsedMessage.Type == ipv4.ICMPTypeEchoReply {
duration := time.Since(start)
return duration, nil
} else {
return 0, fmt.Errorf("unexpected ICMP message: %+v", parsedMessage)
}
}
4 changes: 2 additions & 2 deletions core/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"time"
)

const OpenP2PVersion = "3.19.0"
const OpenP2PVersion = "3.21.8"
const ProductName string = "openp2p"
const LeastSupportVersion = "3.0.0"
const SyncServerTimeVersion = "3.9.0"
Expand Down Expand Up @@ -495,7 +495,7 @@ type SDWANInfo struct {
ForceRelay int32 `json:"forceRelay,omitempty"`
PunchPriority int32 `json:"punchPriority,omitempty"`
Enable int32 `json:"enable,omitempty"`
Nodes []SDWANNode
Nodes []*SDWANNode
}

const (
Expand Down
Loading

0 comments on commit df1e16e

Please sign in to comment.