5
0
mirror of https://github.com/cwinfo/yggdrasil-go.git synced 2024-11-22 14:10:28 +00:00

Merge remote-tracking branch 'origin/develop' into link

Fix merge conflicts from flexible logging branch
This commit is contained in:
Neil Alexander 2019-01-27 20:54:21 +00:00
commit 1a3a67f205
No known key found for this signature in database
GPG Key ID: A02A2019A2BB0944
17 changed files with 98 additions and 78 deletions

View File

@ -6,7 +6,6 @@ import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"strings"
@ -14,6 +13,7 @@ import (
"golang.org/x/text/encoding/unicode"
"github.com/gologme/log"
"github.com/hjson/hjson-go"
"github.com/kardianos/minwinsvc"
"github.com/mitchellh/mapstructure"
@ -169,6 +169,7 @@ func main() {
confjson := flag.Bool("json", false, "print configuration from -genconf or -normaliseconf as JSON instead of HJSON")
autoconf := flag.Bool("autoconf", false, "automatic mode (dynamic IP, peer with IPv6 neighbors)")
version := flag.Bool("version", false, "prints the version of this build")
logging := flag.String("logging", "info,warn,error", "comma-separated list of logging levels to enable")
flag.Parse()
var cfg *nodeConfig
@ -217,6 +218,20 @@ func main() {
}
// Create a new logger that logs output to stdout.
logger := log.New(os.Stdout, "", log.Flags())
//logger.EnableLevel("error")
//logger.EnableLevel("warn")
//logger.EnableLevel("info")
if levels := strings.Split(*logging, ","); len(levels) > 0 {
for _, level := range levels {
l := strings.TrimSpace(level)
switch l {
case "error", "warn", "info", "trace", "debug":
logger.EnableLevel(l)
default:
continue
}
}
}
// Setup the Yggdrasil node itself. The node{} type includes a Core, so we
// don't need to create this manually.
n := node{}
@ -224,7 +239,7 @@ func main() {
// Yggdrasil. This will start the router, switch, DHT node, TCP and UDP
// sockets, TUN/TAP adapter and multicast discovery port.
if err := n.core.Start(cfg, logger); err != nil {
logger.Println("An error occurred during startup")
logger.Errorln("An error occurred during startup")
panic(err)
}
// The Stop function ensures that the TUN/TAP adapter is correctly shut down
@ -236,8 +251,8 @@ func main() {
// This is just logged to stdout for the user.
address := n.core.GetAddress()
subnet := n.core.GetSubnet()
logger.Printf("Your IPv6 address is %s", address.String())
logger.Printf("Your IPv6 subnet is %s", subnet.String())
logger.Infof("Your IPv6 address is %s", address.String())
logger.Infof("Your IPv6 subnet is %s", subnet.String())
// Catch interrupts from the operating system to exit gracefully.
c := make(chan os.Signal, 1)
r := make(chan os.Signal, 1)
@ -257,7 +272,7 @@ func main() {
cfg = readConfig(useconf, useconffile, normaliseconf)
n.core.UpdateConfig(cfg)
} else {
logger.Println("Reloading config at runtime is only possible with -useconffile")
logger.Errorln("Reloading config at runtime is only possible with -useconffile")
}
case _ = <-c:
goto exit

1
go.mod
View File

@ -5,6 +5,7 @@ require (
github.com/hjson/hjson-go v0.0.0-20181010104306-a25ecf6bd222
github.com/kardianos/minwinsvc v0.0.0-20151122163309-cad6b2b879b0
github.com/mitchellh/mapstructure v1.1.2
github.com/gologme/log v0.0.0-20181207131047-4e5d8ccb38e8
github.com/songgao/packets v0.0.0-20160404182456-549a10cd4091
github.com/yggdrasil-network/water v0.0.0-20180615095340-f732c88f34ae
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9

2
go.sum
View File

@ -18,3 +18,5 @@ golang.org/x/sys v0.0.0-20181206074257-70b957f3b65e h1:njOxP/wVblhCLIUhjHXf6X+dz
golang.org/x/sys v0.0.0-20181206074257-70b957f3b65e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
github.com/gologme/log v0.0.0-20181207131047-4e5d8ccb38e8 h1:WD8iJ37bRNwvETMfVTusVSAi0WdXTpfNVGY2aHycNKY=
github.com/gologme/log v0.0.0-20181207131047-4e5d8ccb38e8/go.mod h1:gq31gQ8wEHkR+WekdWsqDuf8pXTUZA9BnnzTuPz1Y9U=

View File

@ -398,7 +398,7 @@ func (a *admin) listen() {
switch strings.ToLower(u.Scheme) {
case "unix":
if _, err := os.Stat(a.listenaddr[7:]); err == nil {
a.core.log.Println("WARNING:", a.listenaddr[7:], "already exists and may be in use by another process")
a.core.log.Warnln("WARNING:", a.listenaddr[7:], "already exists and may be in use by another process")
}
a.listener, err = net.Listen("unix", a.listenaddr[7:])
if err == nil {
@ -406,7 +406,7 @@ func (a *admin) listen() {
case "@": // maybe abstract namespace
default:
if err := os.Chmod(a.listenaddr[7:], 0660); err != nil {
a.core.log.Println("WARNING:", a.listenaddr[:7], "may have unsafe permissions!")
a.core.log.Warnln("WARNING:", a.listenaddr[:7], "may have unsafe permissions!")
}
}
}
@ -420,10 +420,10 @@ func (a *admin) listen() {
a.listener, err = net.Listen("tcp", a.listenaddr)
}
if err != nil {
a.core.log.Printf("Admin socket failed to listen: %v", err)
a.core.log.Errorf("Admin socket failed to listen: %v", err)
os.Exit(1)
}
a.core.log.Printf("%s admin socket listening on %s",
a.core.log.Infof("%s admin socket listening on %s",
strings.ToUpper(a.listener.Addr().Network()),
a.listener.Addr().String())
defer a.listener.Close()
@ -450,9 +450,9 @@ func (a *admin) handleRequest(conn net.Conn) {
"status": "error",
"error": "Unrecoverable error, possibly as a result of invalid input types or malformed syntax",
}
fmt.Println("Admin socket error:", r)
a.core.log.Errorln("Admin socket error:", r)
if err := encoder.Encode(&send); err != nil {
fmt.Println("Admin socket JSON encode error:", err)
a.core.log.Errorln("Admin socket JSON encode error:", err)
}
conn.Close()
}

View File

@ -48,7 +48,7 @@ func (c *cryptokey) init(core *Core) {
}()
if err := c.configure(); err != nil {
c.core.log.Println("CKR configuration failed:", err)
c.core.log.Errorln("CKR configuration failed:", err)
}
}
@ -192,7 +192,7 @@ func (c *cryptokey) addSourceSubnet(cidr string) error {
// Add the source subnet
*routingsources = append(*routingsources, *ipnet)
c.core.log.Println("Added CKR source subnet", cidr)
c.core.log.Infoln("Added CKR source subnet", cidr)
return nil
}
@ -264,7 +264,7 @@ func (c *cryptokey) addRoute(cidr string, dest string) error {
delete(*routingcache, k)
}
c.core.log.Println("Added CKR destination subnet", cidr)
c.core.log.Infoln("Added CKR destination subnet", cidr)
return nil
}
}
@ -358,7 +358,7 @@ func (c *cryptokey) removeSourceSubnet(cidr string) error {
for idx, subnet := range *routingsources {
if subnet.String() == ipnet.String() {
*routingsources = append((*routingsources)[:idx], (*routingsources)[idx+1:]...)
c.core.log.Println("Removed CKR source subnet", cidr)
c.core.log.Infoln("Removed CKR source subnet", cidr)
return nil
}
}
@ -407,7 +407,7 @@ func (c *cryptokey) removeRoute(cidr string, dest string) error {
for k := range *routingcache {
delete(*routingcache, k)
}
c.core.log.Printf("Removed CKR destination subnet %s via %s\n", cidr, dest)
c.core.log.Infoln("Removed CKR destination subnet %s via %s\n", cidr, dest)
return nil
}
}

View File

@ -3,11 +3,12 @@ package yggdrasil
import (
"encoding/hex"
"io/ioutil"
"log"
"net"
"sync"
"time"
"github.com/gologme/log"
"github.com/yggdrasil-network/yggdrasil-go/src/address"
"github.com/yggdrasil-network/yggdrasil-go/src/config"
"github.com/yggdrasil-network/yggdrasil-go/src/crypto"
@ -178,13 +179,13 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
c.log = log
if name := GetBuildName(); name != "unknown" {
c.log.Println("Build name:", name)
c.log.Infoln("Build name:", name)
}
if version := GetBuildVersion(); version != "unknown" {
c.log.Println("Build version:", version)
c.log.Infoln("Build version:", version)
}
c.log.Println("Starting up...")
c.log.Infoln("Starting up...")
c.configMutex.Lock()
c.config = *nc
@ -194,12 +195,12 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
c.init()
if err := c.tcp.init(c); err != nil {
c.log.Println("Failed to start TCP interface")
c.log.Errorln("Failed to start TCP interface")
return err
}
if err := c.link.init(c); err != nil {
c.log.Println("Failed to start link interfaces")
c.log.Errorln("Failed to start link interfaces")
return err
}
@ -208,39 +209,39 @@ func (c *Core) Start(nc *config.NodeConfig, log *log.Logger) error {
}
if err := c.switchTable.start(); err != nil {
c.log.Println("Failed to start switch")
c.log.Errorln("Failed to start switch")
return err
}
if err := c.router.start(); err != nil {
c.log.Println("Failed to start router")
c.log.Errorln("Failed to start router")
return err
}
if err := c.admin.start(); err != nil {
c.log.Println("Failed to start admin socket")
c.log.Errorln("Failed to start admin socket")
return err
}
if err := c.multicast.start(); err != nil {
c.log.Println("Failed to start multicast interface")
c.log.Errorln("Failed to start multicast interface")
return err
}
if err := c.router.tun.start(); err != nil {
c.log.Println("Failed to start TUN/TAP")
c.log.Errorln("Failed to start TUN/TAP")
return err
}
go c.addPeerLoop()
c.log.Println("Startup complete")
c.log.Infoln("Startup complete")
return nil
}
// Stops the Yggdrasil node.
func (c *Core) Stop() {
c.log.Println("Stopping...")
c.log.Infoln("Stopping...")
c.router.tun.close()
c.admin.close()
}

View File

@ -14,7 +14,6 @@ import _ "golang.org/x/net/ipv6" // TODO put this somewhere better
import "fmt"
import "net"
import "log"
import "regexp"
import "encoding/hex"
@ -23,6 +22,8 @@ import "net/http"
import "runtime"
import "os"
import "github.com/gologme/log"
import "github.com/yggdrasil-network/yggdrasil-go/src/address"
import "github.com/yggdrasil-network/yggdrasil-go/src/config"
import "github.com/yggdrasil-network/yggdrasil-go/src/crypto"

View File

@ -35,15 +35,15 @@ func (m *multicast) init(core *Core) {
m.groupAddr = "[ff02::114]:9001"
// Check if we've been given any expressions
if count := len(m.interfaces()); count != 0 {
m.core.log.Println("Found", count, "multicast interface(s)")
m.core.log.Infoln("Found", count, "multicast interface(s)")
}
}
func (m *multicast) start() error {
if len(m.interfaces()) == 0 {
m.core.log.Println("Multicast discovery is disabled")
m.core.log.Infoln("Multicast discovery is disabled")
} else {
m.core.log.Println("Multicast discovery is enabled")
m.core.log.Infoln("Multicast discovery is enabled")
addr, err := net.ResolveUDPAddr("udp", m.groupAddr)
if err != nil {
return err

View File

@ -96,7 +96,7 @@ func (r *router) init(core *Core) {
// Starts the mainLoop goroutine.
func (r *router) start() error {
r.core.log.Println("Starting router")
r.core.log.Infoln("Starting router")
go r.mainLoop()
return nil
}

View File

@ -563,7 +563,7 @@ func (t *switchTable) getTable() lookupTable {
// Starts the switch worker
func (t *switchTable) start() error {
t.core.log.Println("Starting switch")
t.core.log.Infoln("Starting switch")
go t.doWorker()
return nil
}

View File

@ -133,16 +133,16 @@ func (iface *tcpInterface) listen() error {
// Runs the listener, which spawns off goroutines for incoming connections.
func (iface *tcpInterface) listener() {
defer iface.serv.Close()
iface.core.log.Println("Listening for TCP on:", iface.serv.Addr().String())
iface.core.log.Infoln("Listening for TCP on:", iface.serv.Addr().String())
for {
sock, err := iface.serv.Accept()
if err != nil {
iface.core.log.Println("Failed to accept connection:", err)
iface.core.log.Errorln("Failed to accept connection:", err)
return
}
select {
case <-iface.stop:
iface.core.log.Println("Stopping listener")
iface.core.log.Errorln("Stopping listener")
return
default:
if err != nil {
@ -290,7 +290,7 @@ func (iface *tcpInterface) handler(sock net.Conn, incoming bool) {
iface.core.log.Println(err)
panic(err)
}
iface.core.log.Println("DEBUG: starting handler for", name)
iface.core.log.Debugln("DEBUG: starting handler for", name)
err = link.handler()
iface.core.log.Println("DEBUG: stopped handler for", name, err)
iface.core.log.Debugln("DEBUG: stopped handler for", name, err)
}

View File

@ -53,7 +53,7 @@ func (tun *tunAdapter) init(core *Core, send chan<- []byte, recv <-chan []byte)
tun.core.config.IfMTU != tun.core.configOld.IfMTU
tun.core.configMutex.RUnlock()
if updated {
tun.core.log.Println("Reconfiguring TUN/TAP is not supported yet")
tun.core.log.Warnln("Reconfiguring TUN/TAP is not supported yet")
e <- nil
} else {
e <- nil
@ -82,8 +82,8 @@ func (tun *tunAdapter) start() error {
tun.mutex.Lock()
tun.isOpen = true
tun.mutex.Unlock()
go func() { tun.core.log.Println("WARNING: tun.read() exited with error:", tun.read()) }()
go func() { tun.core.log.Println("WARNING: tun.write() exited with error:", tun.write()) }()
go func() { tun.core.log.Errorln("WARNING: tun.read() exited with error:", tun.read()) }()
go func() { tun.core.log.Errorln("WARNING: tun.write() exited with error:", tun.write()) }()
if iftapmode {
go func() {
for {

View File

@ -114,9 +114,9 @@ func (tun *tunAdapter) setupAddress(addr string) error {
}
// Friendly output
tun.core.log.Printf("Interface name: %s", tun.iface.Name())
tun.core.log.Printf("Interface IPv6: %s", addr)
tun.core.log.Printf("Interface MTU: %d", tun.mtu)
tun.core.log.Infof("Interface name: %s", tun.iface.Name())
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", tun.mtu)
// Create the MTU request
var ir in6_ifreq_mtu
@ -126,15 +126,15 @@ func (tun *tunAdapter) setupAddress(addr string) error {
// Set the MTU
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(sfd), uintptr(syscall.SIOCSIFMTU), uintptr(unsafe.Pointer(&ir))); errno != 0 {
err = errno
tun.core.log.Printf("Error in SIOCSIFMTU: %v", errno)
tun.core.log.Errorf("Error in SIOCSIFMTU: %v", errno)
// Fall back to ifconfig to set the MTU
cmd := exec.Command("ifconfig", tun.iface.Name(), "mtu", string(tun.mtu))
tun.core.log.Printf("Using ifconfig as fallback: %v", strings.Join(cmd.Args, " "))
tun.core.log.Warnf("Using ifconfig as fallback: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Printf("SIOCSIFMTU fallback failed: %v.", err)
tun.core.log.Println(string(output))
tun.core.log.Errorf("SIOCSIFMTU fallback failed: %v.", err)
tun.core.log.Traceln(string(output))
}
}
@ -155,15 +155,15 @@ func (tun *tunAdapter) setupAddress(addr string) error {
// Set the interface address
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(sfd), uintptr(SIOCSIFADDR_IN6), uintptr(unsafe.Pointer(&ar))); errno != 0 {
err = errno
tun.core.log.Printf("Error in SIOCSIFADDR_IN6: %v", errno)
tun.core.log.Errorf("Error in SIOCSIFADDR_IN6: %v", errno)
// Fall back to ifconfig to set the address
cmd := exec.Command("ifconfig", tun.iface.Name(), "inet6", addr)
tun.core.log.Printf("Using ifconfig as fallback: %v", strings.Join(cmd.Args, " "))
tun.core.log.Warnf("Using ifconfig as fallback: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Printf("SIOCSIFADDR_IN6 fallback failed: %v.", err)
tun.core.log.Println(string(output))
tun.core.log.Errorf("SIOCSIFADDR_IN6 fallback failed: %v.", err)
tun.core.log.Traceln(string(output))
}
}

View File

@ -18,7 +18,7 @@ import (
// Configures the "utun" adapter with the correct IPv6 address and MTU.
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
if iftapmode {
tun.core.log.Printf("TAP mode is not supported on this platform, defaulting to TUN")
tun.core.log.Warnln("TAP mode is not supported on this platform, defaulting to TUN")
}
config := water.Config{DeviceType: water.TUN}
iface, err := water.New(config)
@ -98,19 +98,19 @@ func (tun *tunAdapter) setupAddress(addr string) error {
copy(ir.ifr_name[:], tun.iface.Name())
ir.ifru_mtu = uint32(tun.mtu)
tun.core.log.Printf("Interface name: %s", ar.ifra_name)
tun.core.log.Printf("Interface IPv6: %s", addr)
tun.core.log.Printf("Interface MTU: %d", ir.ifru_mtu)
tun.core.log.Infof("Interface name: %s", ar.ifra_name)
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", ir.ifru_mtu)
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(darwin_SIOCAIFADDR_IN6), uintptr(unsafe.Pointer(&ar))); errno != 0 {
err = errno
tun.core.log.Printf("Error in darwin_SIOCAIFADDR_IN6: %v", errno)
tun.core.log.Errorf("Error in darwin_SIOCAIFADDR_IN6: %v", errno)
return err
}
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(unix.SIOCSIFMTU), uintptr(unsafe.Pointer(&ir))); errno != 0 {
err = errno
tun.core.log.Printf("Error in SIOCSIFMTU: %v", errno)
tun.core.log.Errorf("Error in SIOCSIFMTU: %v", errno)
return err
}

View File

@ -40,9 +40,9 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
}
}
// Friendly output
tun.core.log.Printf("Interface name: %s", tun.iface.Name())
tun.core.log.Printf("Interface IPv6: %s", addr)
tun.core.log.Printf("Interface MTU: %d", tun.mtu)
tun.core.log.Infof("Interface name: %s", tun.iface.Name())
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", tun.mtu)
return tun.setupAddress(addr)
}

View File

@ -28,6 +28,6 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
// We don't know how to set the IPv6 address on an unknown platform, therefore
// write about it to stdout and don't try to do anything further.
func (tun *tunAdapter) setupAddress(addr string) error {
tun.core.log.Println("Platform not supported, you must set the address of", tun.iface.Name(), "to", addr)
tun.core.log.Warnln("Platform not supported, you must set the address of", tun.iface.Name(), "to", addr)
return nil
}

View File

@ -15,7 +15,7 @@ import (
// delegate the hard work to "netsh".
func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int) error {
if !iftapmode {
tun.core.log.Printf("TUN mode is not supported on this platform, defaulting to TAP")
tun.core.log.Warnln("TUN mode is not supported on this platform, defaulting to TAP")
}
config := water.Config{DeviceType: water.TAP}
config.PlatformSpecificParams.ComponentID = "tap0901"
@ -34,16 +34,16 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
tun.core.log.Printf("netsh command: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Printf("Windows netsh failed: %v.", err)
tun.core.log.Println(string(output))
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
cmd = exec.Command("netsh", "interface", "set", "interface", iface.Name(), "admin=ENABLED")
tun.core.log.Printf("netsh command: %v", strings.Join(cmd.Args, " "))
output, err = cmd.CombinedOutput()
if err != nil {
tun.core.log.Printf("Windows netsh failed: %v.", err)
tun.core.log.Println(string(output))
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
// Get a new iface
@ -58,9 +58,9 @@ func (tun *tunAdapter) setup(ifname string, iftapmode bool, addr string, mtu int
panic(err)
}
// Friendly output
tun.core.log.Printf("Interface name: %s", tun.iface.Name())
tun.core.log.Printf("Interface IPv6: %s", addr)
tun.core.log.Printf("Interface MTU: %d", tun.mtu)
tun.core.log.Infof("Interface name: %s", tun.iface.Name())
tun.core.log.Infof("Interface IPv6: %s", addr)
tun.core.log.Infof("Interface MTU: %d", tun.mtu)
return tun.setupAddress(addr)
}
@ -71,11 +71,11 @@ func (tun *tunAdapter) setupMTU(mtu int) error {
fmt.Sprintf("interface=%s", tun.iface.Name()),
fmt.Sprintf("mtu=%d", mtu),
"store=active")
tun.core.log.Printf("netsh command: %v", strings.Join(cmd.Args, " "))
tun.core.log.Debugln("netsh command: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Printf("Windows netsh failed: %v.", err)
tun.core.log.Println(string(output))
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
return nil
@ -88,11 +88,11 @@ func (tun *tunAdapter) setupAddress(addr string) error {
fmt.Sprintf("interface=%s", tun.iface.Name()),
fmt.Sprintf("addr=%s", addr),
"store=active")
tun.core.log.Printf("netsh command: %v", strings.Join(cmd.Args, " "))
tun.core.log.Debugln("netsh command: %v", strings.Join(cmd.Args, " "))
output, err := cmd.CombinedOutput()
if err != nil {
tun.core.log.Printf("Windows netsh failed: %v.", err)
tun.core.log.Println(string(output))
tun.core.log.Errorf("Windows netsh failed: %v.", err)
tun.core.log.Traceln(string(output))
return err
}
return nil