New log option: LogNormal

This commit is contained in:
KusakabeSi 2021-08-25 08:13:53 +00:00
parent ad196d3f95
commit 89f3069e7f
28 changed files with 148 additions and 81 deletions

2
.vscode/launch.json vendored
View File

@ -11,7 +11,7 @@
"mode": "auto", "mode": "auto",
"program": "${workspaceFolder}", "program": "${workspaceFolder}",
"env": {"CGO_CFLAGS":"-I/usr/include/memif"}, "env": {"CGO_CFLAGS":"-I/usr/include/memif"},
"args":["-config","example_config/static_mode/n1.yaml","-mode","edge"/*,"-example"*/], "args":["-config","example_config/super_mode/n1.yaml","-mode","edge"/*,"-example"*/],
} }
] ]
} }

View File

@ -2,6 +2,16 @@ package config
import ( import (
"crypto/rand" "crypto/rand"
"strconv"
"math"
)
const (
Boardcast Vertex = math.MaxUint32 - iota // Normal boardcast, boardcast with route table
ControlMessage Vertex = math.MaxUint32 - iota // p2p mode: boardcast to every know keer and prevent dup/ super mode: send to supernode
PingMessage Vertex = math.MaxUint32 - iota // boardsact to every know peer but don't transit
SuperNodeMessage Vertex = math.MaxUint32 - iota
Special_NodeID Vertex = SuperNodeMessage
) )
type EdgeConfig struct { type EdgeConfig struct {
@ -24,7 +34,7 @@ type SuperConfig struct {
ListenPort int ListenPort int
LogLevel LoggerInfo LogLevel LoggerInfo
RePushConfigInterval float64 RePushConfigInterval float64
statepasswordd string StatePassword string
GraphRecalculateSetting GraphRecalculateSetting GraphRecalculateSetting GraphRecalculateSetting
Peers []PeerInfo Peers []PeerInfo
} }
@ -53,11 +63,27 @@ type LoggerInfo struct {
LogLevel string LogLevel string
LogTransit bool LogTransit bool
LogControl bool LogControl bool
LogNormal bool
} }
// Nonnegative integer ID of vertex // Nonnegative integer ID of vertex
type Vertex uint32 type Vertex uint32
func (v *Vertex) ToString() string {
switch *v{
case Boardcast:
return "B"
case ControlMessage:
return "C"
case PingMessage:
return "P"
case SuperNodeMessage:
return "S"
default:
return strconv.Itoa(int(*v))
}
}
type DynamicRouteInfo struct { type DynamicRouteInfo struct {
SendPingInterval float64 SendPingInterval float64
DupCheckTimeout float64 DupCheckTimeout float64

View File

@ -82,6 +82,8 @@ type Device struct {
Event_server_NhTable_changed chan struct{} Event_server_NhTable_changed chan struct{}
Event_save_config chan struct{} Event_save_config chan struct{}
Event_Supernode_OK chan struct{}
indexTable IndexTable indexTable IndexTable
cookieChecker CookieChecker cookieChecker CookieChecker
@ -90,8 +92,7 @@ type Device struct {
ID config.Vertex ID config.Vertex
graph *path.IG graph *path.IG
l2fib sync.Map l2fib sync.Map
LogTransit bool LogLevel config.LoggerInfo
LogControl bool
DRoute config.DynamicRouteInfo DRoute config.DynamicRouteInfo
DupData fixed_time_cache.Cache DupData fixed_time_cache.Cache
@ -160,7 +161,7 @@ func removePeerLocked(device *Device, peer *Peer, key NoisePublicKey) {
// remove from peer map // remove from peer map
id := peer.ID id := peer.ID
delete(device.peers.keyMap, key) delete(device.peers.keyMap, key)
if id == path.SuperNodeMessage { if id == config.SuperNodeMessage {
delete(device.peers.SuperPeer, key) delete(device.peers.SuperPeer, key)
} else { } else {
delete(device.peers.IDMap, id) delete(device.peers.IDMap, id)
@ -335,8 +336,7 @@ func NewDevice(tapDevice tap.Device, id config.Vertex, bind conn.Bind, logger *L
device.Event_server_pong = superevents.Event_server_pong device.Event_server_pong = superevents.Event_server_pong
device.Event_server_register = superevents.Event_server_register device.Event_server_register = superevents.Event_server_register
device.Event_server_NhTable_changed = superevents.Event_server_NhTable_changed device.Event_server_NhTable_changed = superevents.Event_server_NhTable_changed
device.LogTransit = sconfig.LogLevel.LogTransit device.LogLevel = sconfig.LogLevel
device.LogControl = sconfig.LogLevel.LogControl
device.SuperConfig = sconfig device.SuperConfig = sconfig
device.SuperConfigPath = configpath device.SuperConfigPath = configpath
go device.RoutineRecalculateNhTable() go device.RoutineRecalculateNhTable()
@ -347,8 +347,8 @@ func NewDevice(tapDevice tap.Device, id config.Vertex, bind conn.Bind, logger *L
device.DupData = *fixed_time_cache.NewCache(path.S2TD(econfig.DynamicRoute.DupCheckTimeout), false, path.S2TD(60)) device.DupData = *fixed_time_cache.NewCache(path.S2TD(econfig.DynamicRoute.DupCheckTimeout), false, path.S2TD(60))
device.event_tryendpoint = make(chan struct{}, 1<<6) device.event_tryendpoint = make(chan struct{}, 1<<6)
device.Event_save_config = make(chan struct{}, 1<<5) device.Event_save_config = make(chan struct{}, 1<<5)
device.LogTransit = econfig.LogLevel.LogTransit device.Event_Supernode_OK = make(chan struct{}, 4)
device.LogControl = econfig.LogLevel.LogControl device.LogLevel = econfig.LogLevel
device.ResetConnInterval = device.EdgeConfig.ResetConnInterval device.ResetConnInterval = device.EdgeConfig.ResetConnInterval
go device.RoutineSetEndpoint() go device.RoutineSetEndpoint()
go device.RoutineRegister() go device.RoutineRegister()

View File

@ -12,14 +12,12 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"strconv"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/KusakabeSi/EtherGuardVPN/config" "github.com/KusakabeSi/EtherGuardVPN/config"
"github.com/KusakabeSi/EtherGuardVPN/conn" "github.com/KusakabeSi/EtherGuardVPN/conn"
"github.com/KusakabeSi/EtherGuardVPN/path"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
@ -96,8 +94,8 @@ func (device *Device) NewPeer(pk NoisePublicKey, id config.Vertex) (*Peer, error
} }
// create peer // create peer
if device.LogControl { if device.LogLevel.LogControl {
fmt.Println("Create peer with ID : " + strconv.Itoa(int(id)) + " and PubKey:" + base64.StdEncoding.EncodeToString(pk[:])) fmt.Println("Create peer with ID : " + id.ToString() + " and PubKey:" + base64.StdEncoding.EncodeToString(pk[:]))
} }
peer := new(Peer) peer := new(Peer)
peer.Lock() peer.Lock()
@ -130,7 +128,7 @@ func (device *Device) NewPeer(pk NoisePublicKey, id config.Vertex) (*Peer, error
peer.endpoint = nil peer.endpoint = nil
// add // add
if id == path.SuperNodeMessage { // To communicate with supernode if id == config.SuperNodeMessage { // To communicate with supernode
device.peers.SuperPeer[pk] = peer device.peers.SuperPeer[pk] = peer
device.peers.keyMap[pk] = peer device.peers.keyMap[pk] = peer
} else { // Regular peer, other edgenodes } else { // Regular peer, other edgenodes
@ -356,7 +354,7 @@ func (device *Device) SaveToConfig(peer *Peer, endpoint conn.Endpoint) {
peerfile.EndPoint = url peerfile.EndPoint = url
} }
} else if peerfile.NodeID == peer.ID || peerfile.PubKey == pubkeystr { } else if peerfile.NodeID == peer.ID || peerfile.PubKey == pubkeystr {
panic("Found NodeID match " + strconv.Itoa(int(peer.ID)) + ", but PubKey Not match %s enrties in config file" + pubkeystr) panic("Found NodeID match " + peer.ID.ToString() + ", but PubKey Not match %s enrties in config file" + pubkeystr)
} }
} }
if !foundInFile { if !foundInFile {

View File

@ -459,24 +459,24 @@ func (peer *Peer) RoutineSequentialReceiver() {
if device.IsSuperNode { if device.IsSuperNode {
peer.LastPingReceived = time.Now() peer.LastPingReceived = time.Now()
switch dst_nodeID { switch dst_nodeID {
case path.ControlMessage: case config.ControlMessage:
should_process = true should_process = true
case path.SuperNodeMessage: case config.SuperNodeMessage:
should_process = true should_process = true
default: default:
device.log.Errorf("Invalid dst_nodeID received. Check your code for bug") device.log.Errorf("Invalid dst_nodeID received. Check your code for bug")
} }
} else { } else {
switch dst_nodeID { switch dst_nodeID {
case path.Boardcast: case config.Boardcast:
should_receive = true should_receive = true
should_transfer = true should_transfer = true
case path.PingMessage: case config.PingMessage:
peer.LastPingReceived = time.Now() peer.LastPingReceived = time.Now()
should_process = true should_process = true
case path.SuperNodeMessage: case config.SuperNodeMessage:
should_process = true should_process = true
case path.ControlMessage: case config.ControlMessage:
packet := elem.packet[path.EgHeaderLen:] //true packet packet := elem.packet[path.EgHeaderLen:] //true packet
if device.CheckNoDup(packet) { if device.CheckNoDup(packet) {
should_process = true should_process = true
@ -484,7 +484,7 @@ func (peer *Peer) RoutineSequentialReceiver() {
} else { } else {
should_process = false should_process = false
should_transfer = false should_transfer = false
if device.LogTransit { if device.LogLevel.LogTransit {
fmt.Printf("Duplicate packet received from %d through %d , src_nodeID = %d . Dropeed.\n", peer.ID, device.ID, src_nodeID) fmt.Printf("Duplicate packet received from %d through %d , src_nodeID = %d . Dropeed.\n", peer.ID, device.ID, src_nodeID)
} }
} }
@ -508,9 +508,9 @@ func (peer *Peer) RoutineSequentialReceiver() {
device.log.Verbosef("TTL is 0 %v", dst_nodeID) device.log.Verbosef("TTL is 0 %v", dst_nodeID)
} else { } else {
EgHeader.SetTTL(l2ttl - 1) EgHeader.SetTTL(l2ttl - 1)
if dst_nodeID == path.Boardcast { //Regular transfer algorithm if dst_nodeID == config.Boardcast { //Regular transfer algorithm
device.TransitBoardcastPacket(src_nodeID, peer.ID, elem.packet, MessageTransportOffsetContent) device.TransitBoardcastPacket(src_nodeID, peer.ID, elem.packet, MessageTransportOffsetContent)
} else if dst_nodeID == path.ControlMessage { // Control Message will try send to every know node regardless the connectivity } else if dst_nodeID == config.ControlMessage { // Control Message will try send to every know node regardless the connectivity
skip_list := make(map[config.Vertex]bool) skip_list := make(map[config.Vertex]bool)
skip_list[src_nodeID] = true //Don't send to conimg peer and source peer skip_list[src_nodeID] = true //Don't send to conimg peer and source peer
skip_list[peer.ID] = true skip_list[peer.ID] = true
@ -519,7 +519,7 @@ func (peer *Peer) RoutineSequentialReceiver() {
} else { } else {
next_id := *device.graph.NhTable[device.ID][dst_nodeID] next_id := *device.graph.NhTable[device.ID][dst_nodeID]
peer_out = device.peers.IDMap[next_id] peer_out = device.peers.IDMap[next_id]
if device.LogTransit { if device.LogLevel.LogTransit {
fmt.Printf("Transfer packet from %d through %d to %d\n", peer.ID, device.ID, peer_out.ID) fmt.Printf("Transfer packet from %d through %d to %d\n", peer.ID, device.ID, peer_out.ID)
} }
device.SendPacket(peer_out, elem.packet, MessageTransportOffsetContent) device.SendPacket(peer_out, elem.packet, MessageTransportOffsetContent)
@ -529,7 +529,7 @@ func (peer *Peer) RoutineSequentialReceiver() {
if should_process { if should_process {
if packet_type != path.NornalPacket { if packet_type != path.NornalPacket {
if device.LogControl { if device.LogLevel.LogControl {
if peer.GetEndpointDstStr() != "" { if peer.GetEndpointDstStr() != "" {
fmt.Printf("Received MID:" + strconv.Itoa(int(EgHeader.GetMessageID())) + " From:" + peer.GetEndpointDstStr() + " " + device.sprint_received(packet_type, elem.packet[path.EgHeaderLen:]) + "\n") fmt.Printf("Received MID:" + strconv.Itoa(int(EgHeader.GetMessageID())) + " From:" + peer.GetEndpointDstStr() + " " + device.sprint_received(packet_type, elem.packet[path.EgHeaderLen:]) + "\n")
} }
@ -543,6 +543,9 @@ func (peer *Peer) RoutineSequentialReceiver() {
if should_receive { // Write message to tap device if should_receive { // Write message to tap device
if packet_type == path.NornalPacket { if packet_type == path.NornalPacket {
if device.LogLevel.LogNormal {
fmt.Println("Reveived Normal packet From:" + peer.GetEndpointDstStr() + " SrcID:" + src_nodeID.ToString() + " DstID:" + dst_nodeID.ToString() + " Len:" + strconv.Itoa(len(elem.packet)))
}
if len(elem.packet) <= path.EgHeaderLen+12 { if len(elem.packet) <= path.EgHeaderLen+12 {
device.log.Errorf("Invalid normal packet from peer %v", peer) device.log.Errorf("Invalid normal packet from peer %v", peer)
goto skip goto skip

View File

@ -20,7 +20,14 @@ func (device *Device) SendPacket(peer *Peer, packet []byte, offset int) {
if peer == nil { if peer == nil {
return return
} }
if device.LogControl { if device.LogLevel.LogNormal {
EgHeader, _ := path.NewEgHeader(packet[:path.EgHeaderLen])
if EgHeader.GetUsage() == path.NornalPacket {
dst_nodeID := EgHeader.GetDst()
fmt.Println("Send Normal packet To:" + peer.GetEndpointDstStr() + " SrcID:" + device.ID.ToString() + " DstID:" + dst_nodeID.ToString() + " Len:" + strconv.Itoa(len(packet)))
}
}
if device.LogLevel.LogControl {
EgHeader, _ := path.NewEgHeader(packet[:path.EgHeaderLen]) EgHeader, _ := path.NewEgHeader(packet[:path.EgHeaderLen])
if EgHeader.GetUsage() != path.NornalPacket { if EgHeader.GetUsage() != path.NornalPacket {
device.MsgCount += 1 device.MsgCount += 1
@ -30,6 +37,7 @@ func (device *Device) SendPacket(peer *Peer, packet []byte, offset int) {
} }
} }
} }
var elem *QueueOutboundElement var elem *QueueOutboundElement
elem = device.NewOutboundElement() elem = device.NewOutboundElement()
copy(elem.buffer[offset:offset+len(packet)], packet) copy(elem.buffer[offset:offset+len(packet)], packet)
@ -59,7 +67,7 @@ func (device *Device) SpreadPacket(skip_list map[config.Vertex]bool, packet []by
device.peers.RLock() device.peers.RLock()
for peer_id, peer_out := range device.peers.IDMap { for peer_id, peer_out := range device.peers.IDMap {
if _, ok := skip_list[peer_id]; ok { if _, ok := skip_list[peer_id]; ok {
if device.LogTransit { if device.LogLevel.LogTransit {
fmt.Printf("Skipped Spread Packet packet through %d to %d\n", device.ID, peer_out.ID) fmt.Printf("Skipped Spread Packet packet through %d to %d\n", device.ID, peer_out.ID)
} }
continue continue
@ -74,7 +82,7 @@ func (device *Device) TransitBoardcastPacket(src_nodeID config.Vertex, in_id con
device.peers.RLock() device.peers.RLock()
for peer_id := range node_boardcast_list { for peer_id := range node_boardcast_list {
peer_out := device.peers.IDMap[peer_id] peer_out := device.peers.IDMap[peer_id]
if device.LogTransit { if device.LogLevel.LogTransit {
fmt.Printf("Transfer packet from %d through %d to %d\n", in_id, device.ID, peer_out.ID) fmt.Printf("Transfer packet from %d through %d to %d\n", in_id, device.ID, peer_out.ID)
} }
device.SendPacket(peer_out, packet, offset) device.SendPacket(peer_out, packet, offset)
@ -86,9 +94,9 @@ func (device *Device) Send2Super(packet []byte, offset int) {
device.peers.RLock() device.peers.RLock()
if device.DRoute.SuperNode.UseSuperNode { if device.DRoute.SuperNode.UseSuperNode {
for _, peer_out := range device.peers.SuperPeer { for _, peer_out := range device.peers.SuperPeer {
if device.LogTransit { /*if device.LogTransit {
fmt.Printf("Send to supernode %s\n", peer_out.endpoint.DstToString()) fmt.Printf("Send to supernode %s\n", peer_out.endpoint.DstToString())
} }*/
device.SendPacket(peer_out, packet, offset) device.SendPacket(peer_out, packet, offset)
} }
} }
@ -216,11 +224,11 @@ func (device *Device) process_ping(content path.PingMsg) error {
header.SetPacketLength(uint16(len(body))) header.SetPacketLength(uint16(len(body)))
copy(buf[path.EgHeaderLen:], body) copy(buf[path.EgHeaderLen:], body)
if device.DRoute.SuperNode.UseSuperNode { if device.DRoute.SuperNode.UseSuperNode {
header.SetDst(path.SuperNodeMessage) header.SetDst(config.SuperNodeMessage)
device.Send2Super(buf, MessageTransportOffsetContent) device.Send2Super(buf, MessageTransportOffsetContent)
} }
if device.DRoute.P2P.UseP2P { if device.DRoute.P2P.UseP2P {
header.SetDst(path.ControlMessage) header.SetDst(config.ControlMessage)
device.SpreadPacket(make(map[config.Vertex]bool), buf, MessageTransportOffsetContent) device.SpreadPacket(make(map[config.Vertex]bool), buf, MessageTransportOffsetContent)
} }
return nil return nil
@ -259,7 +267,7 @@ func (device *Device) process_UpdatePeerMsg(content path.UpdatePeerMsg) error {
} }
downloadurl := device.DRoute.SuperNode.APIUrl + "/peerinfo?PubKey=" + url.QueryEscape(PubKey2Str(device.staticIdentity.publicKey)) + "&State=" + url.QueryEscape(string(content.State_hash[:])) downloadurl := device.DRoute.SuperNode.APIUrl + "/peerinfo?PubKey=" + url.QueryEscape(PubKey2Str(device.staticIdentity.publicKey)) + "&State=" + url.QueryEscape(string(content.State_hash[:]))
if device.LogControl { if device.LogLevel.LogControl {
fmt.Println("Download peerinfo from :" + downloadurl) fmt.Println("Download peerinfo from :" + downloadurl)
} }
client := http.Client{ client := http.Client{
@ -276,6 +284,9 @@ func (device *Device) process_UpdatePeerMsg(content path.UpdatePeerMsg) error {
device.log.Errorf(err.Error()) device.log.Errorf(err.Error())
return err return err
} }
if device.LogLevel.LogControl {
fmt.Println("Download result :" + string(allbytes))
}
if err := json.Unmarshal(allbytes, &peer_infos); err != nil { if err := json.Unmarshal(allbytes, &peer_infos); err != nil {
device.log.Errorf(err.Error()) device.log.Errorf(err.Error())
return err return err
@ -348,8 +359,8 @@ func (device *Device) RoutineSetEndpoint() {
thepeer.endpoint_trylist.Delete(url) thepeer.endpoint_trylist.Delete(url)
return true return true
} }
if device.LogControl { if device.LogLevel.LogControl {
fmt.Println("Set endpoint to " + endpoint.DstToString() + " for NodeID:" + strconv.Itoa(int(thepeer.ID))) fmt.Println("Set endpoint to " + endpoint.DstToString() + " for NodeID:" + thepeer.ID.ToString())
} }
thepeer.SetEndpointFromPacket(endpoint) thepeer.SetEndpointFromPacket(endpoint)
NextRun = true NextRun = true
@ -394,15 +405,17 @@ func (device *Device) RoutineRegister() {
if !(device.DRoute.SuperNode.UseSuperNode) { if !(device.DRoute.SuperNode.UseSuperNode) {
return return
} }
_ = <-device.Event_Supernode_OK
for { for {
body, _ := path.GetByte(path.RegisterMsg{ body, _ := path.GetByte(path.RegisterMsg{
Node_id: device.ID, Node_id: device.ID,
PeerStateHash: device.peers.Peer_state, PeerStateHash: device.peers.Peer_state,
NhStateHash: device.graph.NhTableHash, NhStateHash: device.graph.NhTableHash,
Name: device.EdgeConfig.NodeName,
}) })
buf := make([]byte, path.EgHeaderLen+len(body)) buf := make([]byte, path.EgHeaderLen+len(body))
header, _ := path.NewEgHeader(buf[0:path.EgHeaderLen]) header, _ := path.NewEgHeader(buf[0:path.EgHeaderLen])
header.SetDst(path.SuperNodeMessage) header.SetDst(config.SuperNodeMessage)
header.SetTTL(0) header.SetTTL(0)
header.SetSrc(device.ID) header.SetSrc(device.ID)
header.SetUsage(path.Register) header.SetUsage(path.Register)
@ -441,7 +454,7 @@ func (device *Device) RoutineSpreadAllMyNeighbor() {
} }
for { for {
device.process_RequestPeerMsg(path.QueryPeerMsg{ device.process_RequestPeerMsg(path.QueryPeerMsg{
Request_ID: uint32(path.Boardcast), Request_ID: uint32(config.Boardcast),
}) })
time.Sleep(path.S2TD(device.DRoute.P2P.SendPeerInterval)) time.Sleep(path.S2TD(device.DRoute.P2P.SendPeerInterval))
} }
@ -483,7 +496,7 @@ func (device *Device) GeneratePingPacket(src_nodeID config.Vertex) ([]byte, erro
if err != nil { if err != nil {
return nil, err return nil, err
} }
header.SetDst(path.PingMessage) header.SetDst(config.PingMessage)
header.SetTTL(0) header.SetTTL(0)
header.SetSrc(device.ID) header.SetSrc(device.ID)
header.SetUsage(path.PingPacket) header.SetUsage(path.PingPacket)
@ -502,7 +515,7 @@ func (device *Device) process_UpdateNhTableMsg(content path.UpdateNhTableMsg) er
return nil return nil
} }
downloadurl := device.DRoute.SuperNode.APIUrl + "/nhtable?PubKey=" + url.QueryEscape(PubKey2Str(device.staticIdentity.publicKey)) + "&State=" + url.QueryEscape(string(content.State_hash[:])) downloadurl := device.DRoute.SuperNode.APIUrl + "/nhtable?PubKey=" + url.QueryEscape(PubKey2Str(device.staticIdentity.publicKey)) + "&State=" + url.QueryEscape(string(content.State_hash[:]))
if device.LogControl { if device.LogLevel.LogControl {
fmt.Println("Download NhTable from :" + downloadurl) fmt.Println("Download NhTable from :" + downloadurl)
} }
client := http.Client{ client := http.Client{
@ -519,6 +532,9 @@ func (device *Device) process_UpdateNhTableMsg(content path.UpdateNhTableMsg) er
device.log.Errorf(err.Error()) device.log.Errorf(err.Error())
return err return err
} }
if device.LogLevel.LogControl {
fmt.Println("Download result :" + string(allbytes))
}
if err := json.Unmarshal(allbytes, &NhTable); err != nil { if err := json.Unmarshal(allbytes, &NhTable); err != nil {
device.log.Errorf(err.Error()) device.log.Errorf(err.Error())
return err return err
@ -532,7 +548,7 @@ func (device *Device) process_RequestPeerMsg(content path.QueryPeerMsg) error {
if device.DRoute.P2P.UseP2P { if device.DRoute.P2P.UseP2P {
device.peers.RLock() device.peers.RLock()
for pubkey, peer := range device.peers.keyMap { for pubkey, peer := range device.peers.keyMap {
if peer.ID >= path.Special_NodeID { if peer.ID >= config.Special_NodeID {
continue continue
} }
if peer.endpoint == nil { if peer.endpoint == nil {
@ -554,7 +570,7 @@ func (device *Device) process_RequestPeerMsg(content path.QueryPeerMsg) error {
} }
buf := make([]byte, path.EgHeaderLen+len(body)) buf := make([]byte, path.EgHeaderLen+len(body))
header, _ := path.NewEgHeader(buf[0:path.EgHeaderLen]) header, _ := path.NewEgHeader(buf[0:path.EgHeaderLen])
header.SetDst(path.ControlMessage) header.SetDst(config.ControlMessage)
header.SetTTL(200) header.SetTTL(200)
header.SetSrc(device.ID) header.SetSrc(device.ID)
header.SetUsage(path.BoardcastPeer) header.SetUsage(path.BoardcastPeer)

View File

@ -9,7 +9,9 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt"
"os" "os"
"strconv"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
@ -251,9 +253,9 @@ func (device *Device) RoutineReadFromTUN() {
dstMacAddr := tap.GetDstMacAddr(elem.packet[path.EgHeaderLen:]) dstMacAddr := tap.GetDstMacAddr(elem.packet[path.EgHeaderLen:])
// lookup peer // lookup peer
if tap.IsNotUnicast(dstMacAddr) { if tap.IsNotUnicast(dstMacAddr) {
dst_nodeID = path.Boardcast dst_nodeID = config.Boardcast
} else if val, ok := device.l2fib.Load(dstMacAddr); !ok { //Lookup failed } else if val, ok := device.l2fib.Load(dstMacAddr); !ok { //Lookup failed
dst_nodeID = path.Boardcast dst_nodeID = config.Boardcast
} else { } else {
dst_nodeID = val.(config.Vertex) dst_nodeID = val.(config.Vertex)
} }
@ -263,17 +265,22 @@ func (device *Device) RoutineReadFromTUN() {
EgBody.SetTTL(200) EgBody.SetTTL(200)
EgBody.SetUsage(path.NornalPacket) EgBody.SetUsage(path.NornalPacket)
if dst_nodeID != path.Boardcast { if dst_nodeID != config.Boardcast {
var peer_out *Peer var peer *Peer
next_id := *device.graph.NhTable[device.ID][dst_nodeID] next_id := *device.graph.NhTable[device.ID][dst_nodeID]
peer_out = device.peers.IDMap[next_id] peer = device.peers.IDMap[next_id]
if peer_out == nil { if peer == nil {
continue continue
} }
if peer_out.isRunning.Get() { if device.LogLevel.LogNormal {
peer_out.StagePacket(elem) if device.LogLevel.LogNormal {
fmt.Println("Send Normal packet To:" + peer.GetEndpointDstStr() + " SrcID:" + device.ID.ToString() + " DstID:" + dst_nodeID.ToString() + " Len:" + strconv.Itoa(len(elem.packet)))
}
}
if peer.isRunning.Get() {
peer.StagePacket(elem)
elem = nil elem = nil
peer_out.SendStagedPackets() peer.SendStagedPackets()
} }
} else { } else {
device.BoardcastPacket(make(map[config.Vertex]bool, 0), elem.packet, offset) device.BoardcastPacket(make(map[config.Vertex]bool, 0), elem.packet, offset)

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -16,6 +16,7 @@ loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -1,5 +1,5 @@
interface: interface:
itype: stdio itype: udpsock
name: tap1 name: tap1
vppifaceid: 1 vppifaceid: 1
vppbridgeid: 0 vppbridgeid: 0
@ -15,7 +15,8 @@ listenport: 3001
loglevel: loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: false
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -8,14 +8,15 @@ interface:
recvaddr: 127.0.0.1:4002 recvaddr: 127.0.0.1:4002
sendaddr: 127.0.0.1:5002 sendaddr: 127.0.0.1:5002
l2headermode: kbdbg l2headermode: kbdbg
nodeid: 1 nodeid: 2
nodename: Node01 nodename: Node02
privkey: OH8BsVUU2Rqzeu9B2J5GPG8PUmxWfX8uVvNFZKhVF3o= privkey: OH8BsVUU2Rqzeu9B2J5GPG8PUmxWfX8uVvNFZKhVF3o=
listenport: 3002 listenport: 3002
loglevel: loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: false
lognormal: true
dynamicroute: dynamicroute:
sendpinginterval: 20 sendpinginterval: 20
dupchecktimeout: 40 dupchecktimeout: 40

View File

@ -2,10 +2,12 @@ nodename: NodeSuper
privkeyv4: mL5IW0GuqbjgDeOJuPHBU2iJzBPNKhaNEXbIGwwYWWk= privkeyv4: mL5IW0GuqbjgDeOJuPHBU2iJzBPNKhaNEXbIGwwYWWk=
privkeyv6: +EdOKIoBp/EvIusHDsvXhV1RJYbyN3Qr8nxlz35wl3I= privkeyv6: +EdOKIoBp/EvIusHDsvXhV1RJYbyN3Qr8nxlz35wl3I=
listenport: 3000 listenport: 3000
statepassword: passwd
loglevel: loglevel:
loglevel: normal loglevel: normal
logtransit: true logtransit: true
logcontrol: true logcontrol: true
lognormal: true
repushconfiginterval: 30 repushconfiginterval: 30
graphrecalculatesetting: graphrecalculatesetting:
jittertolerance: 5 jittertolerance: 5

View File

@ -203,7 +203,7 @@ func Edge(configPath string, useUAPI bool, printExample bool) (err error) {
for _, peerconf := range tconfig.Peers { for _, peerconf := range tconfig.Peers {
sk_slice, _ = base64.StdEncoding.DecodeString(peerconf.PubKey) sk_slice, _ = base64.StdEncoding.DecodeString(peerconf.PubKey)
copy(sk[:], sk_slice) copy(sk[:], sk_slice)
if peerconf.NodeID >= path.SuperNodeMessage { if peerconf.NodeID >= config.SuperNodeMessage {
return errors.New(fmt.Sprintf("Invalid Node_id at peer %s\n", peerconf.PubKey)) return errors.New(fmt.Sprintf("Invalid Node_id at peer %s\n", peerconf.PubKey))
} }
the_device.NewPeer(sk, peerconf.NodeID) the_device.NewPeer(sk, peerconf.NodeID)
@ -228,7 +228,7 @@ func Edge(configPath string, useUAPI bool, printExample bool) (err error) {
if err != nil { if err != nil {
return err return err
} }
peer, err := the_device.NewPeer(sk, path.SuperNodeMessage) peer, err := the_device.NewPeer(sk, config.SuperNodeMessage)
if err != nil { if err != nil {
return err return err
} }
@ -243,7 +243,7 @@ func Edge(configPath string, useUAPI bool, printExample bool) (err error) {
if err != nil { if err != nil {
return err return err
} }
peer, err := the_device.NewPeer(sk, path.SuperNodeMessage) peer, err := the_device.NewPeer(sk, config.SuperNodeMessage)
if err != nil { if err != nil {
return err return err
} }
@ -251,6 +251,7 @@ func Edge(configPath string, useUAPI bool, printExample bool) (err error) {
peer.ConnURL = tconfig.DynamicRoute.SuperNode.ConnURLV6 peer.ConnURL = tconfig.DynamicRoute.SuperNode.ConnURLV6
peer.SetEndpointFromPacket(endpoint) peer.SetEndpointFromPacket(endpoint)
} }
the_device.Event_Supernode_OK <- struct{}{}
} }
logger.Verbosef("Device started") logger.Verbosef("Device started")

View File

@ -152,5 +152,6 @@ func HttpServer(http_port int, apiprefix string) {
} }
mux.HandleFunc(apiprefix+"/peerinfo", get_peerinfo) mux.HandleFunc(apiprefix+"/peerinfo", get_peerinfo)
mux.HandleFunc(apiprefix+"/nhtable", get_nhtable) mux.HandleFunc(apiprefix+"/nhtable", get_nhtable)
mux.HandleFunc(apiprefix+"/peerstate", get_info)
http.ListenAndServe(":"+strconv.Itoa(http_port), mux) http.ListenAndServe(":"+strconv.Itoa(http_port), mux)
} }

View File

@ -99,6 +99,7 @@ func Super(configPath string, useUAPI bool, printExample bool) (err error) {
http_PeerID2Map = make(map[config.Vertex]string) http_PeerID2Map = make(map[config.Vertex]string)
http_PeerInfos = make(map[string]config.HTTP_Peerinfo) http_PeerInfos = make(map[string]config.HTTP_Peerinfo)
http_HashSalt = []byte(config.RandomStr(32, "Salt generate failed")) http_HashSalt = []byte(config.RandomStr(32, "Salt generate failed"))
http_StatePWD = sconfig.StatePassword
super_chains := path.SUPER_Events{ super_chains := path.SUPER_Events{
Event_server_pong: make(chan path.PongMsg, 1<<5), Event_server_pong: make(chan path.PongMsg, 1<<5),
@ -108,8 +109,8 @@ func Super(configPath string, useUAPI bool, printExample bool) (err error) {
thetap, _ := tap.CreateDummyTAP() thetap, _ := tap.CreateDummyTAP()
http_graph = path.NewGraph(3, true, sconfig.GraphRecalculateSetting) http_graph = path.NewGraph(3, true, sconfig.GraphRecalculateSetting)
http_device4 = device.NewDevice(thetap, path.SuperNodeMessage, conn.NewCustomBind(true, false), logger4, http_graph, true, configPath, nil, &sconfig, &super_chains) http_device4 = device.NewDevice(thetap, config.SuperNodeMessage, conn.NewCustomBind(true, false), logger4, http_graph, true, configPath, nil, &sconfig, &super_chains)
http_device6 = device.NewDevice(thetap, path.SuperNodeMessage, conn.NewCustomBind(false, true), logger6, http_graph, true, configPath, nil, &sconfig, &super_chains) http_device6 = device.NewDevice(thetap, config.SuperNodeMessage, conn.NewCustomBind(false, true), logger6, http_graph, true, configPath, nil, &sconfig, &super_chains)
defer http_device4.Close() defer http_device4.Close()
defer http_device6.Close() defer http_device6.Close()
var sk [32]byte var sk [32]byte
@ -142,7 +143,7 @@ func Super(configPath string, useUAPI bool, printExample bool) (err error) {
fmt.Println("Error decode base64 ", err) fmt.Println("Error decode base64 ", err)
} }
copy(pk[:], pk_slice) copy(pk[:], pk_slice)
if peerconf.NodeID >= path.SuperNodeMessage { if peerconf.NodeID >= config.SuperNodeMessage {
return errors.New(fmt.Sprintf("Invalid Node_id at peer %s\n", peerconf.PubKey)) return errors.New(fmt.Sprintf("Invalid Node_id at peer %s\n", peerconf.PubKey))
} }
http_PeerID2Map[peerconf.NodeID] = peerconf.PubKey http_PeerID2Map[peerconf.NodeID] = peerconf.PubKey
@ -280,9 +281,9 @@ func PushNhTable() {
} }
buf := make([]byte, path.EgHeaderLen+len(body)) buf := make([]byte, path.EgHeaderLen+len(body))
header, _ := path.NewEgHeader(buf[:path.EgHeaderLen]) header, _ := path.NewEgHeader(buf[:path.EgHeaderLen])
header.SetDst(path.SuperNodeMessage) header.SetDst(config.SuperNodeMessage)
header.SetPacketLength(uint16(len(body))) header.SetPacketLength(uint16(len(body)))
header.SetSrc(path.SuperNodeMessage) header.SetSrc(config.SuperNodeMessage)
header.SetTTL(0) header.SetTTL(0)
header.SetUsage(path.UpdateNhTable) header.SetUsage(path.UpdateNhTable)
copy(buf[path.EgHeaderLen:], body) copy(buf[path.EgHeaderLen:], body)
@ -308,9 +309,9 @@ func PushUpdate() {
} }
buf := make([]byte, path.EgHeaderLen+len(body)) buf := make([]byte, path.EgHeaderLen+len(body))
header, _ := path.NewEgHeader(buf[:path.EgHeaderLen]) header, _ := path.NewEgHeader(buf[:path.EgHeaderLen])
header.SetDst(path.SuperNodeMessage) header.SetDst(config.SuperNodeMessage)
header.SetPacketLength(uint16(len(body))) header.SetPacketLength(uint16(len(body)))
header.SetSrc(path.SuperNodeMessage) header.SetSrc(config.SuperNodeMessage)
header.SetTTL(0) header.SetTTL(0)
header.SetUsage(path.UpdatePeer) header.SetUsage(path.UpdatePeer)
copy(buf[path.EgHeaderLen:], body) copy(buf[path.EgHeaderLen:], body)

View File

@ -27,7 +27,7 @@ type RegisterMsg struct {
} }
func (c *RegisterMsg) ToString() string { func (c *RegisterMsg) ToString() string {
return "RegisterMsg Node_id:" + strconv.Itoa(int(c.Node_id)) return "RegisterMsg Node_id:" + c.Node_id.ToString()
} }
func ParseRegisterMsg(bin []byte) (StructPlace RegisterMsg, err error) { func ParseRegisterMsg(bin []byte) (StructPlace RegisterMsg, err error) {
@ -77,7 +77,7 @@ type PingMsg struct {
} }
func (c *PingMsg) ToString() string { func (c *PingMsg) ToString() string {
return "PingMsg SID:" + strconv.Itoa(int(c.Src_nodeID)) + " Time:" + c.Time.String() + " RequestID:" + strconv.Itoa(int(c.RequestID)) return "PingMsg SID:" + c.Src_nodeID.ToString() + " Time:" + c.Time.String() + " RequestID:" + strconv.Itoa(int(c.RequestID))
} }
func ParsePingMsg(bin []byte) (StructPlace PingMsg, err error) { func ParsePingMsg(bin []byte) (StructPlace PingMsg, err error) {
@ -96,7 +96,7 @@ type PongMsg struct {
} }
func (c *PongMsg) ToString() string { func (c *PongMsg) ToString() string {
return "PongMsg SID:" + strconv.Itoa(int(c.Src_nodeID)) + " DID:" + strconv.Itoa(int(c.Dst_nodeID)) + " Timediff:" + c.Timediff.String() + " RequestID:" + strconv.Itoa(int(c.RequestID)) return "PongMsg SID:" + c.Src_nodeID.ToString() + " DID:" + c.Dst_nodeID.ToString() + " Timediff:" + c.Timediff.String() + " RequestID:" + strconv.Itoa(int(c.RequestID))
} }
func ParsePongMsg(bin []byte) (StructPlace PongMsg, err error) { func ParsePongMsg(bin []byte) (StructPlace PongMsg, err error) {
@ -132,7 +132,7 @@ type BoardcastPeerMsg struct {
} }
func (c *BoardcastPeerMsg) ToString() string { func (c *BoardcastPeerMsg) ToString() string {
return "BoardcastPeerMsg Request_ID:" + strconv.Itoa(int(c.Request_ID)) + " NodeID:" + strconv.Itoa(int(c.NodeID)) + " ConnURL:" + c.ConnURL return "BoardcastPeerMsg Request_ID:" + strconv.Itoa(int(c.Request_ID)) + " NodeID:" + c.NodeID.ToString() + " ConnURL:" + c.ConnURL
} }
func ParseBoardcastPeerMsg(bin []byte) (StructPlace BoardcastPeerMsg, err error) { func ParseBoardcastPeerMsg(bin []byte) (StructPlace BoardcastPeerMsg, err error) {

View File

@ -12,14 +12,6 @@ import (
const Infinity = float64(99999) const Infinity = float64(99999)
const (
Boardcast config.Vertex = math.MaxUint32 - iota // Normal boardcast, boardcast with route table
ControlMessage config.Vertex = math.MaxUint32 - iota // p2p mode: boardcast to every know keer and prevent dup/ super mode: send to supernode
PingMessage config.Vertex = math.MaxUint32 - iota // boardsact to every know peer but don't transit
SuperNodeMessage config.Vertex = math.MaxUint32 - iota
Special_NodeID config.Vertex = SuperNodeMessage
)
func (g *IG) GetCurrentTime() time.Time { func (g *IG) GetCurrentTime() time.Time {
return time.Now().Round(0) return time.Now().Round(0)
} }
@ -268,9 +260,11 @@ func (g *IG) GetEdges() (edges map[config.Vertex]map[config.Vertex]float64) {
for src, _ := range vert { for src, _ := range vert {
edges[src] = make(map[config.Vertex]float64, len(vert)) edges[src] = make(map[config.Vertex]float64, len(vert))
for dst, _ := range vert { for dst, _ := range vert {
if src != dst {
edges[src][dst] = g.Weight(src, dst) edges[src][dst] = g.Weight(src, dst)
} }
} }
}
return return
} }

View File

@ -1,5 +1,7 @@
package tap package tap
import "errors"
type DummyTap struct { type DummyTap struct {
stopRead chan struct{} stopRead chan struct{}
events chan Event events chan Event
@ -21,7 +23,7 @@ func CreateDummyTAP() (tapdev Device, err error) {
func (tap *DummyTap) Read([]byte, int) (int, error) { func (tap *DummyTap) Read([]byte, int) (int, error) {
_ = <-tap.stopRead _ = <-tap.stopRead
return 0, nil return 0, errors.New("Device stopped")
} // read a packet from the device (without any additional headers) } // read a packet from the device (without any additional headers)
func (tap *DummyTap) Write(packet []byte, size int) (int, error) { func (tap *DummyTap) Write(packet []byte, size int) (int, error) {
return size, nil return size, nil
@ -40,6 +42,8 @@ func (tap *DummyTap) Events() chan Event {
} // returns a constant channel of events related to the device } // returns a constant channel of events related to the device
func (tap *DummyTap) Close() error { func (tap *DummyTap) Close() error {
tap.events <- EventDown tap.events <- EventDown
close(tap.events) tap.stopRead <- struct{}{}
//close(tap.stopRead)
//close(tap.events)
return nil return nil
} // stops the device and closes the event channel } // stops the device and closes the event channel