1
0
mirror of https://git.zx2c4.com/wireguard-go synced 2024-11-15 01:05:15 +01:00

device: combine debug and info log levels into 'verbose'

There are very few cases, if any, in which a user only wants one of
these levels, so combine it into a single level.

While we're at it, reduce indirection on the loggers by using an empty
function rather than a nil function pointer. It's not like we have
retpolines anyway, and we were always calling through a function with a
branch prior, so this seems like a net gain.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld 2021-01-26 23:05:48 +01:00
parent 7139279cd0
commit d669c78c43
13 changed files with 109 additions and 133 deletions

View File

@ -177,7 +177,7 @@ func deviceUpdateState(device *Device) {
switch newIsUp { switch newIsUp {
case true: case true:
if err := device.BindUpdate(); err != nil { if err := device.BindUpdate(); err != nil {
device.errorf("Unable to update bind: %v", err) device.log.Errorf("Unable to update bind: %v", err)
device.isUp.Set(false) device.isUp.Set(false)
break break
} }
@ -303,7 +303,7 @@ func NewDevice(tunDevice tun.Device, logger *Logger) *Device {
device.tun.device = tunDevice device.tun.device = tunDevice
mtu, err := device.tun.device.MTU() mtu, err := device.tun.device.MTU()
if err != nil { if err != nil {
device.errorf("Trouble determining MTU, assuming default: %v", err) device.log.Errorf("Trouble determining MTU, assuming default: %v", err)
mtu = DefaultMTU mtu = DefaultMTU
} }
device.tun.mtu = int32(mtu) device.tun.mtu = int32(mtu)
@ -397,7 +397,7 @@ func (device *Device) Close() {
return return
} }
device.infof("Device closing") device.log.Verbosef("Device closing")
device.state.changing.Set(true) device.state.changing.Set(true)
device.state.Lock() device.state.Lock()
defer device.state.Unlock() defer device.state.Unlock()
@ -422,7 +422,7 @@ func (device *Device) Close() {
device.rate.limiter.Close() device.rate.limiter.Close()
device.state.changing.Set(false) device.state.changing.Set(false)
device.infof("Interface closed") device.log.Verbosef("Interface closed")
} }
func (device *Device) Wait() chan struct{} { func (device *Device) Wait() chan struct{} {
@ -562,7 +562,7 @@ func (device *Device) BindUpdate() error {
go device.RoutineReceiveIncoming(ipv4.Version, netc.bind) go device.RoutineReceiveIncoming(ipv4.Version, netc.bind)
go device.RoutineReceiveIncoming(ipv6.Version, netc.bind) go device.RoutineReceiveIncoming(ipv6.Version, netc.bind)
device.debugf("UDP bind has been updated") device.log.Verbosef("UDP bind has been updated")
} }
return nil return nil

View File

@ -148,7 +148,7 @@ NextAttempt:
} else { } else {
p.ip = net.ParseIP("1.0.0.2") p.ip = net.ParseIP("1.0.0.2")
} }
level := LogLevelDebug level := LogLevelVerbose
if _, ok := tb.(*testing.B); ok && !testing.Verbose() { if _, ok := tb.(*testing.B); ok && !testing.Verbose() {
level = LogLevelError level = LogLevelError
} }

View File

@ -16,8 +16,7 @@ import (
// They do not require a trailing newline in the format. // They do not require a trailing newline in the format.
// If nil, that level of logging will be silent. // If nil, that level of logging will be silent.
type Logger struct { type Logger struct {
Debugf func(format string, args ...interface{}) Verbosef func(format string, args ...interface{})
Infof func(format string, args ...interface{})
Errorf func(format string, args ...interface{}) Errorf func(format string, args ...interface{})
} }
@ -25,44 +24,25 @@ type Logger struct {
const ( const (
LogLevelSilent = iota LogLevelSilent = iota
LogLevelError LogLevelError
LogLevelInfo LogLevelVerbose
LogLevelDebug
) )
// Function for use in Logger for discarding logged lines.
func DiscardLogf(format string, args ...interface{}) {}
// NewLogger constructs a Logger that writes to stdout. // NewLogger constructs a Logger that writes to stdout.
// It logs at the specified log level and above. // It logs at the specified log level and above.
// It decorates log lines with the log level, date, time, and prepend. // It decorates log lines with the log level, date, time, and prepend.
func NewLogger(level int, prepend string) *Logger { func NewLogger(level int, prepend string) *Logger {
logger := new(Logger) logger := &Logger{DiscardLogf, DiscardLogf}
logf := func(prefix string) func(string, ...interface{}) { logf := func(prefix string) func(string, ...interface{}) {
return log.New(os.Stdout, prefix+": "+prepend, log.Ldate|log.Ltime).Printf return log.New(os.Stdout, prefix+": "+prepend, log.Ldate|log.Ltime).Printf
} }
if level >= LogLevelDebug { if level >= LogLevelVerbose {
logger.Debugf = logf("DEBUG") logger.Verbosef = logf("DEBUG")
}
if level >= LogLevelInfo {
logger.Infof = logf("INFO")
} }
if level >= LogLevelError { if level >= LogLevelError {
logger.Errorf = logf("ERROR") logger.Errorf = logf("ERROR")
} }
return logger return logger
} }
func (device *Device) debugf(format string, args ...interface{}) {
if device.log.Debugf != nil {
device.log.Debugf(format, args...)
}
}
func (device *Device) infof(format string, args ...interface{}) {
if device.log.Infof != nil {
device.log.Infof(format, args...)
}
}
func (device *Device) errorf(format string, args ...interface{}) {
if device.log.Errorf != nil {
device.log.Errorf(format, args...)
}
}

View File

@ -319,11 +319,11 @@ func (device *Device) ConsumeMessageInitiation(msg *MessageInitiation) *Peer {
flood := time.Since(handshake.lastInitiationConsumption) <= HandshakeInitationRate flood := time.Since(handshake.lastInitiationConsumption) <= HandshakeInitationRate
handshake.mutex.RUnlock() handshake.mutex.RUnlock()
if replay { if replay {
device.debugf("%v - ConsumeMessageInitiation: handshake replay @ %v", peer, timestamp) device.log.Verbosef("%v - ConsumeMessageInitiation: handshake replay @ %v", peer, timestamp)
return nil return nil
} }
if flood { if flood {
device.debugf("%v - ConsumeMessageInitiation: handshake flood", peer) device.log.Verbosef("%v - ConsumeMessageInitiation: handshake flood", peer)
return nil return nil
} }

View File

@ -190,7 +190,7 @@ func (peer *Peer) Start() {
} }
device := peer.device device := peer.device
device.debugf("%v - Starting...", peer) device.log.Verbosef("%v - Starting...", peer)
// reset routine state // reset routine state
@ -278,7 +278,7 @@ func (peer *Peer) Stop() {
peer.routines.Lock() peer.routines.Lock()
defer peer.routines.Unlock() defer peer.routines.Unlock()
peer.device.debugf("%v - Stopping...", peer) peer.device.log.Verbosef("%v - Stopping...", peer)
peer.timersStop() peer.timersStop()

View File

@ -79,12 +79,12 @@ func (peer *Peer) keepKeyFreshReceiving() {
*/ */
func (device *Device) RoutineReceiveIncoming(IP int, bind conn.Bind) { func (device *Device) RoutineReceiveIncoming(IP int, bind conn.Bind) {
defer func() { defer func() {
device.debugf("Routine: receive incoming IPv%d - stopped", IP) device.log.Verbosef("Routine: receive incoming IPv%d - stopped", IP)
device.queue.decryption.wg.Done() device.queue.decryption.wg.Done()
device.net.stopping.Done() device.net.stopping.Done()
}() }()
device.debugf("Routine: receive incoming IPv%d - started", IP) device.log.Verbosef("Routine: receive incoming IPv%d - started", IP)
// receive datagrams until conn is closed // receive datagrams until conn is closed
@ -112,7 +112,7 @@ func (device *Device) RoutineReceiveIncoming(IP int, bind conn.Bind) {
if errors.Is(err, conn.NetErrClosed) { if errors.Is(err, conn.NetErrClosed) {
return return
} }
device.errorf("Failed to receive packet: %v", err) device.log.Errorf("Failed to receive packet: %v", err)
if deathSpiral < 10 { if deathSpiral < 10 {
deathSpiral++ deathSpiral++
time.Sleep(time.Second / 3) time.Sleep(time.Second / 3)
@ -199,7 +199,7 @@ func (device *Device) RoutineReceiveIncoming(IP int, bind conn.Bind) {
okay = len(packet) == MessageCookieReplySize okay = len(packet) == MessageCookieReplySize
default: default:
device.debugf("Received message with unknown type") device.log.Verbosef("Received message with unknown type")
} }
if okay { if okay {
@ -221,10 +221,10 @@ func (device *Device) RoutineReceiveIncoming(IP int, bind conn.Bind) {
func (device *Device) RoutineDecryption() { func (device *Device) RoutineDecryption() {
var nonce [chacha20poly1305.NonceSize]byte var nonce [chacha20poly1305.NonceSize]byte
defer func() { defer func() {
device.debugf("Routine: decryption worker - stopped") device.log.Verbosef("Routine: decryption worker - stopped")
device.state.stopping.Done() device.state.stopping.Done()
}() }()
device.debugf("Routine: decryption worker - started") device.log.Verbosef("Routine: decryption worker - started")
for elem := range device.queue.decryption.c { for elem := range device.queue.decryption.c {
// split message into fields // split message into fields
@ -256,14 +256,14 @@ func (device *Device) RoutineHandshake() {
var ok bool var ok bool
defer func() { defer func() {
device.debugf("Routine: handshake worker - stopped") device.log.Verbosef("Routine: handshake worker - stopped")
device.state.stopping.Done() device.state.stopping.Done()
if elem.buffer != nil { if elem.buffer != nil {
device.PutMessageBuffer(elem.buffer) device.PutMessageBuffer(elem.buffer)
} }
}() }()
device.debugf("Routine: handshake worker - started") device.log.Verbosef("Routine: handshake worker - started")
for { for {
if elem.buffer != nil { if elem.buffer != nil {
@ -293,7 +293,7 @@ func (device *Device) RoutineHandshake() {
reader := bytes.NewReader(elem.packet) reader := bytes.NewReader(elem.packet)
err := binary.Read(reader, binary.LittleEndian, &reply) err := binary.Read(reader, binary.LittleEndian, &reply)
if err != nil { if err != nil {
device.debugf("Failed to decode cookie reply") device.log.Verbosef("Failed to decode cookie reply")
return return
} }
@ -308,9 +308,9 @@ func (device *Device) RoutineHandshake() {
// consume reply // consume reply
if peer := entry.peer; peer.isRunning.Get() { if peer := entry.peer; peer.isRunning.Get() {
device.debugf("Receiving cookie response from %s", elem.endpoint.DstToString()) device.log.Verbosef("Receiving cookie response from %s", elem.endpoint.DstToString())
if !peer.cookieGenerator.ConsumeReply(&reply) { if !peer.cookieGenerator.ConsumeReply(&reply) {
device.debugf("Could not decrypt invalid cookie response") device.log.Verbosef("Could not decrypt invalid cookie response")
} }
} }
@ -321,7 +321,7 @@ func (device *Device) RoutineHandshake() {
// check mac fields and maybe ratelimit // check mac fields and maybe ratelimit
if !device.cookieChecker.CheckMAC1(elem.packet) { if !device.cookieChecker.CheckMAC1(elem.packet) {
device.debugf("Received packet with invalid mac1") device.log.Verbosef("Received packet with invalid mac1")
continue continue
} }
@ -344,7 +344,7 @@ func (device *Device) RoutineHandshake() {
} }
default: default:
device.errorf("Invalid packet ended up in the handshake queue") device.log.Errorf("Invalid packet ended up in the handshake queue")
continue continue
} }
@ -359,7 +359,7 @@ func (device *Device) RoutineHandshake() {
reader := bytes.NewReader(elem.packet) reader := bytes.NewReader(elem.packet)
err := binary.Read(reader, binary.LittleEndian, &msg) err := binary.Read(reader, binary.LittleEndian, &msg)
if err != nil { if err != nil {
device.errorf("Failed to decode initiation message") device.log.Errorf("Failed to decode initiation message")
continue continue
} }
@ -367,7 +367,7 @@ func (device *Device) RoutineHandshake() {
peer := device.ConsumeMessageInitiation(&msg) peer := device.ConsumeMessageInitiation(&msg)
if peer == nil { if peer == nil {
device.infof("Received invalid initiation message from %s", elem.endpoint.DstToString()) device.log.Verbosef("Received invalid initiation message from %s", elem.endpoint.DstToString())
continue continue
} }
@ -379,7 +379,7 @@ func (device *Device) RoutineHandshake() {
// update endpoint // update endpoint
peer.SetEndpointFromPacket(elem.endpoint) peer.SetEndpointFromPacket(elem.endpoint)
device.debugf("%v - Received handshake initiation", peer) device.log.Verbosef("%v - Received handshake initiation", peer)
atomic.AddUint64(&peer.stats.rxBytes, uint64(len(elem.packet))) atomic.AddUint64(&peer.stats.rxBytes, uint64(len(elem.packet)))
peer.SendHandshakeResponse() peer.SendHandshakeResponse()
@ -392,7 +392,7 @@ func (device *Device) RoutineHandshake() {
reader := bytes.NewReader(elem.packet) reader := bytes.NewReader(elem.packet)
err := binary.Read(reader, binary.LittleEndian, &msg) err := binary.Read(reader, binary.LittleEndian, &msg)
if err != nil { if err != nil {
device.errorf("Failed to decode response message") device.log.Errorf("Failed to decode response message")
continue continue
} }
@ -400,14 +400,14 @@ func (device *Device) RoutineHandshake() {
peer := device.ConsumeMessageResponse(&msg) peer := device.ConsumeMessageResponse(&msg)
if peer == nil { if peer == nil {
device.infof("Received invalid response message from %s", elem.endpoint.DstToString()) device.log.Verbosef("Received invalid response message from %s", elem.endpoint.DstToString())
continue continue
} }
// update endpoint // update endpoint
peer.SetEndpointFromPacket(elem.endpoint) peer.SetEndpointFromPacket(elem.endpoint)
device.debugf("%v - Received handshake response", peer) device.log.Verbosef("%v - Received handshake response", peer)
atomic.AddUint64(&peer.stats.rxBytes, uint64(len(elem.packet))) atomic.AddUint64(&peer.stats.rxBytes, uint64(len(elem.packet)))
// update timers // update timers
@ -420,7 +420,7 @@ func (device *Device) RoutineHandshake() {
err = peer.BeginSymmetricSession() err = peer.BeginSymmetricSession()
if err != nil { if err != nil {
device.errorf("%v - Failed to derive keypair: %v", peer, err) device.log.Errorf("%v - Failed to derive keypair: %v", peer, err)
continue continue
} }
@ -440,7 +440,7 @@ func (peer *Peer) RoutineSequentialReceiver() {
var elem *QueueInboundElement var elem *QueueInboundElement
defer func() { defer func() {
device.debugf("%v - Routine: sequential receiver - stopped", peer) device.log.Verbosef("%v - Routine: sequential receiver - stopped", peer)
peer.routines.stopping.Done() peer.routines.stopping.Done()
if elem != nil { if elem != nil {
device.PutMessageBuffer(elem.buffer) device.PutMessageBuffer(elem.buffer)
@ -448,7 +448,7 @@ func (peer *Peer) RoutineSequentialReceiver() {
} }
}() }()
device.debugf("%v - Routine: sequential receiver - started", peer) device.log.Verbosef("%v - Routine: sequential receiver - started", peer)
for { for {
if elem != nil { if elem != nil {
@ -499,7 +499,7 @@ func (peer *Peer) RoutineSequentialReceiver() {
// check for keepalive // check for keepalive
if len(elem.packet) == 0 { if len(elem.packet) == 0 {
device.debugf("%v - Receiving keepalive packet", peer) device.log.Verbosef("%v - Receiving keepalive packet", peer)
continue continue
} }
peer.timersDataReceived() peer.timersDataReceived()
@ -527,7 +527,7 @@ func (peer *Peer) RoutineSequentialReceiver() {
src := elem.packet[IPv4offsetSrc : IPv4offsetSrc+net.IPv4len] src := elem.packet[IPv4offsetSrc : IPv4offsetSrc+net.IPv4len]
if device.allowedips.LookupIPv4(src) != peer { if device.allowedips.LookupIPv4(src) != peer {
device.infof("IPv4 packet with disallowed source address from %v", peer) device.log.Verbosef("IPv4 packet with disallowed source address from %v", peer)
continue continue
} }
@ -552,12 +552,12 @@ func (peer *Peer) RoutineSequentialReceiver() {
src := elem.packet[IPv6offsetSrc : IPv6offsetSrc+net.IPv6len] src := elem.packet[IPv6offsetSrc : IPv6offsetSrc+net.IPv6len]
if device.allowedips.LookupIPv6(src) != peer { if device.allowedips.LookupIPv6(src) != peer {
device.infof("IPv6 packet with disallowed source address from %v", peer) device.log.Verbosef("IPv6 packet with disallowed source address from %v", peer)
continue continue
} }
default: default:
device.infof("Packet with invalid IP version from %v", peer) device.log.Verbosef("Packet with invalid IP version from %v", peer)
continue continue
} }
@ -566,12 +566,12 @@ func (peer *Peer) RoutineSequentialReceiver() {
offset := MessageTransportOffsetContent offset := MessageTransportOffsetContent
_, err := device.tun.device.Write(elem.buffer[:offset+len(elem.packet)], offset) _, err := device.tun.device.Write(elem.buffer[:offset+len(elem.packet)], offset)
if err != nil && !device.isClosed.Get() { if err != nil && !device.isClosed.Get() {
device.errorf("Failed to write packet to TUN device: %v", err) device.log.Errorf("Failed to write packet to TUN device: %v", err)
} }
if len(peer.queue.inbound) == 0 { if len(peer.queue.inbound) == 0 {
err := device.tun.device.Flush() err := device.tun.device.Flush()
if err != nil { if err != nil {
peer.device.errorf("Unable to flush packets: %v", err) peer.device.log.Errorf("Unable to flush packets: %v", err)
} }
} }
} }

View File

@ -99,7 +99,7 @@ func (peer *Peer) SendKeepalive() bool {
elem.packet = nil elem.packet = nil
select { select {
case peer.queue.nonce <- elem: case peer.queue.nonce <- elem:
peer.device.debugf("%v - Sending keepalive packet", peer) peer.device.log.Verbosef("%v - Sending keepalive packet", peer)
return true return true
default: default:
peer.device.PutMessageBuffer(elem.buffer) peer.device.PutMessageBuffer(elem.buffer)
@ -128,11 +128,11 @@ func (peer *Peer) SendHandshakeInitiation(isRetry bool) error {
peer.handshake.lastSentHandshake = time.Now() peer.handshake.lastSentHandshake = time.Now()
peer.handshake.mutex.Unlock() peer.handshake.mutex.Unlock()
peer.device.debugf("%v - Sending handshake initiation", peer) peer.device.log.Verbosef("%v - Sending handshake initiation", peer)
msg, err := peer.device.CreateMessageInitiation(peer) msg, err := peer.device.CreateMessageInitiation(peer)
if err != nil { if err != nil {
peer.device.errorf("%v - Failed to create initiation message: %v", peer, err) peer.device.log.Errorf("%v - Failed to create initiation message: %v", peer, err)
return err return err
} }
@ -147,7 +147,7 @@ func (peer *Peer) SendHandshakeInitiation(isRetry bool) error {
err = peer.SendBuffer(packet) err = peer.SendBuffer(packet)
if err != nil { if err != nil {
peer.device.errorf("%v - Failed to send handshake initiation: %v", peer, err) peer.device.log.Errorf("%v - Failed to send handshake initiation: %v", peer, err)
} }
peer.timersHandshakeInitiated() peer.timersHandshakeInitiated()
@ -159,11 +159,11 @@ func (peer *Peer) SendHandshakeResponse() error {
peer.handshake.lastSentHandshake = time.Now() peer.handshake.lastSentHandshake = time.Now()
peer.handshake.mutex.Unlock() peer.handshake.mutex.Unlock()
peer.device.debugf("%v - Sending handshake response", peer) peer.device.log.Verbosef("%v - Sending handshake response", peer)
response, err := peer.device.CreateMessageResponse(peer) response, err := peer.device.CreateMessageResponse(peer)
if err != nil { if err != nil {
peer.device.errorf("%v - Failed to create response message: %v", peer, err) peer.device.log.Errorf("%v - Failed to create response message: %v", peer, err)
return err return err
} }
@ -175,7 +175,7 @@ func (peer *Peer) SendHandshakeResponse() error {
err = peer.BeginSymmetricSession() err = peer.BeginSymmetricSession()
if err != nil { if err != nil {
peer.device.errorf("%v - Failed to derive keypair: %v", peer, err) peer.device.log.Errorf("%v - Failed to derive keypair: %v", peer, err)
return err return err
} }
@ -185,19 +185,19 @@ func (peer *Peer) SendHandshakeResponse() error {
err = peer.SendBuffer(packet) err = peer.SendBuffer(packet)
if err != nil { if err != nil {
peer.device.errorf("%v - Failed to send handshake response: %v", peer, err) peer.device.log.Errorf("%v - Failed to send handshake response: %v", peer, err)
} }
return err return err
} }
func (device *Device) SendHandshakeCookie(initiatingElem *QueueHandshakeElement) error { func (device *Device) SendHandshakeCookie(initiatingElem *QueueHandshakeElement) error {
device.debugf("Sending cookie response for denied handshake message for %v", initiatingElem.endpoint.DstToString()) device.log.Verbosef("Sending cookie response for denied handshake message for %v", initiatingElem.endpoint.DstToString())
sender := binary.LittleEndian.Uint32(initiatingElem.packet[4:8]) sender := binary.LittleEndian.Uint32(initiatingElem.packet[4:8])
reply, err := device.cookieChecker.CreateReply(initiatingElem.packet, sender, initiatingElem.endpoint.DstToBytes()) reply, err := device.cookieChecker.CreateReply(initiatingElem.packet, sender, initiatingElem.endpoint.DstToBytes())
if err != nil { if err != nil {
device.errorf("Failed to create cookie reply: %v", err) device.log.Errorf("Failed to create cookie reply: %v", err)
return err return err
} }
@ -226,11 +226,11 @@ func (peer *Peer) keepKeyFreshSending() {
*/ */
func (device *Device) RoutineReadFromTUN() { func (device *Device) RoutineReadFromTUN() {
defer func() { defer func() {
device.debugf("Routine: TUN reader - stopped") device.log.Verbosef("Routine: TUN reader - stopped")
device.state.stopping.Done() device.state.stopping.Done()
}() }()
device.debugf("Routine: TUN reader - started") device.log.Verbosef("Routine: TUN reader - started")
var elem *QueueOutboundElement var elem *QueueOutboundElement
@ -248,7 +248,7 @@ func (device *Device) RoutineReadFromTUN() {
if err != nil { if err != nil {
if !device.isClosed.Get() { if !device.isClosed.Get() {
device.errorf("Failed to read packet from TUN device: %v", err) device.log.Errorf("Failed to read packet from TUN device: %v", err)
device.Close() device.Close()
} }
device.PutMessageBuffer(elem.buffer) device.PutMessageBuffer(elem.buffer)
@ -281,7 +281,7 @@ func (device *Device) RoutineReadFromTUN() {
peer = device.allowedips.LookupIPv6(dst) peer = device.allowedips.LookupIPv6(dst)
default: default:
device.debugf("Received packet with unknown IP version") device.log.Verbosef("Received packet with unknown IP version")
} }
if peer == nil { if peer == nil {
@ -333,14 +333,14 @@ func (peer *Peer) RoutineNonce() {
defer func() { defer func() {
flush() flush()
device.debugf("%v - Routine: nonce worker - stopped", peer) device.log.Verbosef("%v - Routine: nonce worker - stopped", peer)
peer.queue.packetInNonceQueueIsAwaitingKey.Set(false) peer.queue.packetInNonceQueueIsAwaitingKey.Set(false)
device.queue.encryption.wg.Done() // no more writes from us device.queue.encryption.wg.Done() // no more writes from us
close(peer.queue.outbound) // no more writes to this channel close(peer.queue.outbound) // no more writes to this channel
peer.routines.stopping.Done() peer.routines.stopping.Done()
}() }()
device.debugf("%v - Routine: nonce worker - started", peer) device.log.Verbosef("%v - Routine: nonce worker - started", peer)
NextPacket: NextPacket:
for { for {
@ -385,11 +385,11 @@ NextPacket:
// wait for key to be established // wait for key to be established
device.debugf("%v - Awaiting keypair", peer) device.log.Verbosef("%v - Awaiting keypair", peer)
select { select {
case <-peer.signals.newKeypairArrived: case <-peer.signals.newKeypairArrived:
device.debugf("%v - Obtained awaited keypair", peer) device.log.Verbosef("%v - Obtained awaited keypair", peer)
case <-peer.signals.flushNonceQueue: case <-peer.signals.flushNonceQueue:
device.PutMessageBuffer(elem.buffer) device.PutMessageBuffer(elem.buffer)
@ -453,8 +453,8 @@ func (device *Device) RoutineEncryption() {
var nonce [chacha20poly1305.NonceSize]byte var nonce [chacha20poly1305.NonceSize]byte
defer device.debugf("Routine: encryption worker - stopped") defer device.log.Verbosef("Routine: encryption worker - stopped")
device.debugf("Routine: encryption worker - started") device.log.Verbosef("Routine: encryption worker - started")
for elem := range device.queue.encryption.c { for elem := range device.queue.encryption.c {
// populate header fields // populate header fields
@ -497,8 +497,8 @@ func (peer *Peer) RoutineSequentialSender() {
device := peer.device device := peer.device
defer device.debugf("%v - Routine: sequential sender - stopped", peer) defer device.log.Verbosef("%v - Routine: sequential sender - stopped", peer)
device.debugf("%v - Routine: sequential sender - started", peer) device.log.Verbosef("%v - Routine: sequential sender - started", peer)
for elem := range peer.queue.outbound { for elem := range peer.queue.outbound {
elem.Lock() elem.Lock()
@ -526,7 +526,7 @@ func (peer *Peer) RoutineSequentialSender() {
device.PutMessageBuffer(elem.buffer) device.PutMessageBuffer(elem.buffer)
device.PutOutboundElement(elem) device.PutOutboundElement(elem)
if err != nil { if err != nil {
device.errorf("%v - Failed to send data packet: %v", peer, err) device.log.Errorf("%v - Failed to send data packet: %v", peer, err)
continue continue
} }

View File

@ -78,7 +78,7 @@ func (peer *Peer) timersActive() bool {
func expiredRetransmitHandshake(peer *Peer) { func expiredRetransmitHandshake(peer *Peer) {
if atomic.LoadUint32(&peer.timers.handshakeAttempts) > MaxTimerHandshakes { if atomic.LoadUint32(&peer.timers.handshakeAttempts) > MaxTimerHandshakes {
peer.device.debugf("%s - Handshake did not complete after %d attempts, giving up", peer, MaxTimerHandshakes+2) peer.device.log.Verbosef("%s - Handshake did not complete after %d attempts, giving up", peer, MaxTimerHandshakes+2)
if peer.timersActive() { if peer.timersActive() {
peer.timers.sendKeepalive.Del() peer.timers.sendKeepalive.Del()
@ -97,7 +97,7 @@ func expiredRetransmitHandshake(peer *Peer) {
} }
} else { } else {
atomic.AddUint32(&peer.timers.handshakeAttempts, 1) atomic.AddUint32(&peer.timers.handshakeAttempts, 1)
peer.device.debugf("%s - Handshake did not complete after %d seconds, retrying (try %d)", peer, int(RekeyTimeout.Seconds()), atomic.LoadUint32(&peer.timers.handshakeAttempts)+1) peer.device.log.Verbosef("%s - Handshake did not complete after %d seconds, retrying (try %d)", peer, int(RekeyTimeout.Seconds()), atomic.LoadUint32(&peer.timers.handshakeAttempts)+1)
/* We clear the endpoint address src address, in case this is the cause of trouble. */ /* We clear the endpoint address src address, in case this is the cause of trouble. */
peer.Lock() peer.Lock()
@ -121,7 +121,7 @@ func expiredSendKeepalive(peer *Peer) {
} }
func expiredNewHandshake(peer *Peer) { func expiredNewHandshake(peer *Peer) {
peer.device.debugf("%s - Retrying handshake because we stopped hearing back after %d seconds", peer, int((KeepaliveTimeout + RekeyTimeout).Seconds())) peer.device.log.Verbosef("%s - Retrying handshake because we stopped hearing back after %d seconds", peer, int((KeepaliveTimeout + RekeyTimeout).Seconds()))
/* We clear the endpoint address src address, in case this is the cause of trouble. */ /* We clear the endpoint address src address, in case this is the cause of trouble. */
peer.Lock() peer.Lock()
if peer.endpoint != nil { if peer.endpoint != nil {
@ -133,7 +133,7 @@ func expiredNewHandshake(peer *Peer) {
} }
func expiredZeroKeyMaterial(peer *Peer) { func expiredZeroKeyMaterial(peer *Peer) {
peer.device.debugf("%s - Removing all keys, since we haven't received a new one in %d seconds", peer, int((RejectAfterTime * 3).Seconds())) peer.device.log.Verbosef("%s - Removing all keys, since we haven't received a new one in %d seconds", peer, int((RejectAfterTime * 3).Seconds()))
peer.ZeroAndFlushAll() peer.ZeroAndFlushAll()
} }

View File

@ -15,37 +15,37 @@ const DefaultMTU = 1420
func (device *Device) RoutineTUNEventReader() { func (device *Device) RoutineTUNEventReader() {
setUp := false setUp := false
device.debugf("Routine: event worker - started") device.log.Verbosef("Routine: event worker - started")
for event := range device.tun.device.Events() { for event := range device.tun.device.Events() {
if event&tun.EventMTUUpdate != 0 { if event&tun.EventMTUUpdate != 0 {
mtu, err := device.tun.device.MTU() mtu, err := device.tun.device.MTU()
old := atomic.LoadInt32(&device.tun.mtu) old := atomic.LoadInt32(&device.tun.mtu)
if err != nil { if err != nil {
device.errorf("Failed to load updated MTU of device: %v", err) device.log.Errorf("Failed to load updated MTU of device: %v", err)
} else if int(old) != mtu { } else if int(old) != mtu {
if mtu+MessageTransportSize > MaxMessageSize { if mtu+MessageTransportSize > MaxMessageSize {
device.infof("MTU updated: %v (too large)", mtu) device.log.Verbosef("MTU updated: %v (too large)", mtu)
} else { } else {
device.infof("MTU updated: %v", mtu) device.log.Verbosef("MTU updated: %v", mtu)
} }
atomic.StoreInt32(&device.tun.mtu, int32(mtu)) atomic.StoreInt32(&device.tun.mtu, int32(mtu))
} }
} }
if event&tun.EventUp != 0 && !setUp { if event&tun.EventUp != 0 && !setUp {
device.infof("Interface set up") device.log.Verbosef("Interface set up")
setUp = true setUp = true
device.Up() device.Up()
} }
if event&tun.EventDown != 0 && setUp { if event&tun.EventDown != 0 && setUp {
device.infof("Interface set down") device.log.Verbosef("Interface set down")
setUp = false setUp = false
device.Down() device.Down()
} }
} }
device.debugf("Routine: event worker - stopped") device.log.Verbosef("Routine: event worker - stopped")
device.state.stopping.Done() device.state.stopping.Done()
} }

View File

@ -130,7 +130,7 @@ func (device *Device) IpcSetOperation(r io.Reader) (err error) {
defer func() { defer func() {
if err != nil { if err != nil {
device.errorf("%v", err) device.log.Errorf("%v", err)
} }
}() }()
@ -188,7 +188,7 @@ func (device *Device) handleDeviceLine(key, value string) error {
if err != nil { if err != nil {
return ipcErrorf(ipc.IpcErrorInvalid, "failed to set private_key: %w", err) return ipcErrorf(ipc.IpcErrorInvalid, "failed to set private_key: %w", err)
} }
device.debugf("UAPI: Updating private key") device.log.Verbosef("UAPI: Updating private key")
device.SetPrivateKey(sk) device.SetPrivateKey(sk)
case "listen_port": case "listen_port":
@ -198,7 +198,7 @@ func (device *Device) handleDeviceLine(key, value string) error {
} }
// update port and rebind // update port and rebind
device.debugf("UAPI: Updating listen port") device.log.Verbosef("UAPI: Updating listen port")
device.net.Lock() device.net.Lock()
device.net.port = uint16(port) device.net.port = uint16(port)
@ -214,7 +214,7 @@ func (device *Device) handleDeviceLine(key, value string) error {
return ipcErrorf(ipc.IpcErrorInvalid, "invalid fwmark: %w", err) return ipcErrorf(ipc.IpcErrorInvalid, "invalid fwmark: %w", err)
} }
device.debugf("UAPI: Updating fwmark") device.log.Verbosef("UAPI: Updating fwmark")
if err := device.BindSetMark(uint32(mark)); err != nil { if err := device.BindSetMark(uint32(mark)); err != nil {
return ipcErrorf(ipc.IpcErrorPortInUse, "failed to update fwmark: %w", err) return ipcErrorf(ipc.IpcErrorPortInUse, "failed to update fwmark: %w", err)
} }
@ -223,7 +223,7 @@ func (device *Device) handleDeviceLine(key, value string) error {
if value != "true" { if value != "true" {
return ipcErrorf(ipc.IpcErrorInvalid, "failed to set replace_peers, invalid value: %v", value) return ipcErrorf(ipc.IpcErrorInvalid, "failed to set replace_peers, invalid value: %v", value)
} }
device.debugf("UAPI: Removing all peers") device.log.Verbosef("UAPI: Removing all peers")
device.RemoveAllPeers() device.RemoveAllPeers()
default: default:
@ -265,7 +265,7 @@ func (device *Device) handlePublicKeyLine(peer *ipcSetPeer, value string) error
if err != nil { if err != nil {
return ipcErrorf(ipc.IpcErrorInvalid, "failed to create new peer: %w", err) return ipcErrorf(ipc.IpcErrorInvalid, "failed to create new peer: %w", err)
} }
device.debugf("%v - UAPI: Created", peer.Peer) device.log.Verbosef("%v - UAPI: Created", peer.Peer)
} }
return nil return nil
} }
@ -289,14 +289,14 @@ func (device *Device) handlePeerLine(peer *ipcSetPeer, key, value string) error
return ipcErrorf(ipc.IpcErrorInvalid, "failed to set remove, invalid value: %v", value) return ipcErrorf(ipc.IpcErrorInvalid, "failed to set remove, invalid value: %v", value)
} }
if !peer.dummy { if !peer.dummy {
device.debugf("%v - UAPI: Removing", peer.Peer) device.log.Verbosef("%v - UAPI: Removing", peer.Peer)
device.RemovePeer(peer.handshake.remoteStatic) device.RemovePeer(peer.handshake.remoteStatic)
} }
peer.Peer = &Peer{} peer.Peer = &Peer{}
peer.dummy = true peer.dummy = true
case "preshared_key": case "preshared_key":
device.debugf("%v - UAPI: Updating preshared key", peer.Peer) device.log.Verbosef("%v - UAPI: Updating preshared key", peer.Peer)
peer.handshake.mutex.Lock() peer.handshake.mutex.Lock()
err := peer.handshake.presharedKey.FromHex(value) err := peer.handshake.presharedKey.FromHex(value)
@ -307,7 +307,7 @@ func (device *Device) handlePeerLine(peer *ipcSetPeer, key, value string) error
} }
case "endpoint": case "endpoint":
device.debugf("%v - UAPI: Updating endpoint", peer.Peer) device.log.Verbosef("%v - UAPI: Updating endpoint", peer.Peer)
endpoint, err := conn.CreateEndpoint(value) endpoint, err := conn.CreateEndpoint(value)
if err != nil { if err != nil {
return ipcErrorf(ipc.IpcErrorInvalid, "failed to set endpoint %v: %w", value, err) return ipcErrorf(ipc.IpcErrorInvalid, "failed to set endpoint %v: %w", value, err)
@ -317,7 +317,7 @@ func (device *Device) handlePeerLine(peer *ipcSetPeer, key, value string) error
peer.endpoint = endpoint peer.endpoint = endpoint
case "persistent_keepalive_interval": case "persistent_keepalive_interval":
device.debugf("%v - UAPI: Updating persistent keepalive interval", peer.Peer) device.log.Verbosef("%v - UAPI: Updating persistent keepalive interval", peer.Peer)
secs, err := strconv.ParseUint(value, 10, 16) secs, err := strconv.ParseUint(value, 10, 16)
if err != nil { if err != nil {
@ -337,7 +337,7 @@ func (device *Device) handlePeerLine(peer *ipcSetPeer, key, value string) error
} }
case "replace_allowed_ips": case "replace_allowed_ips":
device.debugf("%v - UAPI: Removing all allowedips", peer.Peer) device.log.Verbosef("%v - UAPI: Removing all allowedips", peer.Peer)
if value != "true" { if value != "true" {
return ipcErrorf(ipc.IpcErrorInvalid, "failed to replace allowedips, invalid value: %v", value) return ipcErrorf(ipc.IpcErrorInvalid, "failed to replace allowedips, invalid value: %v", value)
} }
@ -347,7 +347,7 @@ func (device *Device) handlePeerLine(peer *ipcSetPeer, key, value string) error
device.allowedips.RemoveByPeer(peer.Peer) device.allowedips.RemoveByPeer(peer.Peer)
case "allowed_ip": case "allowed_ip":
device.debugf("%v - UAPI: Adding allowedip", peer.Peer) device.log.Verbosef("%v - UAPI: Adding allowedip", peer.Peer)
_, network, err := net.ParseCIDR(value) _, network, err := net.ParseCIDR(value)
if err != nil { if err != nil {
@ -409,12 +409,12 @@ func (device *Device) IpcHandle(socket net.Conn) {
return return
} }
if nextByte != '\n' { if nextByte != '\n' {
err = ipcErrorf(ipc.IpcErrorInvalid, "trailing character in UAPI get: %c", nextByte) err = ipcErrorf(ipc.IpcErrorInvalid, "trailing character in UAPI get: %q", nextByte)
break break
} }
err = device.IpcGetOperation(buffered.Writer) err = device.IpcGetOperation(buffered.Writer)
default: default:
device.errorf("invalid UAPI operation: %v", op) device.log.Errorf("invalid UAPI operation: %v", op)
return return
} }
@ -425,7 +425,7 @@ func (device *Device) IpcHandle(socket net.Conn) {
status = ipcErrorf(ipc.IpcErrorUnknown, "other UAPI error: %w", err) status = ipcErrorf(ipc.IpcErrorUnknown, "other UAPI error: %w", err)
} }
if status != nil { if status != nil {
device.errorf("%v", status) device.log.Errorf("%v", status)
fmt.Fprintf(buffered, "errno=%d\n\n", status.ErrorCode()) fmt.Fprintf(buffered, "errno=%d\n\n", status.ErrorCode())
} else { } else {
fmt.Fprintf(buffered, "errno=0\n\n") fmt.Fprintf(buffered, "errno=0\n\n")

17
main.go
View File

@ -95,16 +95,14 @@ func main() {
logLevel := func() int { logLevel := func() int {
switch os.Getenv("LOG_LEVEL") { switch os.Getenv("LOG_LEVEL") {
case "debug": case "verbose", "debug":
return device.LogLevelDebug return device.LogLevelVerbose
case "info":
return device.LogLevelInfo
case "error": case "error":
return device.LogLevelError return device.LogLevelError
case "silent": case "silent":
return device.LogLevelSilent return device.LogLevelSilent
} }
return device.LogLevelInfo return device.LogLevelError
}() }()
// open TUN device (or use supplied fd) // open TUN device (or use supplied fd)
@ -143,8 +141,7 @@ func main() {
fmt.Sprintf("(%s) ", interfaceName), fmt.Sprintf("(%s) ", interfaceName),
) )
logger.Infof("Starting wireguard-go version %v", device.WireGuardGoVersion) logger.Verbosef("Starting wireguard-go version %s", device.WireGuardGoVersion)
logger.Debugf("Debug log enabled")
if err != nil { if err != nil {
logger.Errorf("Failed to create TUN device: %v", err) logger.Errorf("Failed to create TUN device: %v", err)
@ -224,7 +221,7 @@ func main() {
device := device.NewDevice(tun, logger) device := device.NewDevice(tun, logger)
logger.Infof("Device started") logger.Verbosef("Device started")
errs := make(chan error) errs := make(chan error)
term := make(chan os.Signal, 1) term := make(chan os.Signal, 1)
@ -246,7 +243,7 @@ func main() {
} }
}() }()
logger.Infof("UAPI listener started") logger.Verbosef("UAPI listener started")
// wait for program to terminate // wait for program to terminate
@ -264,5 +261,5 @@ func main() {
uapi.Close() uapi.Close()
device.Close() device.Close()
logger.Infof("Shutting down") logger.Verbosef("Shutting down")
} }

View File

@ -31,11 +31,10 @@ func main() {
fmt.Fprintln(os.Stderr, "Warning: this is a test program for Windows, mainly used for debugging this Go package. For a real WireGuard for Windows client, the repo you want is <https://git.zx2c4.com/wireguard-windows/>, which includes this code as a module.") fmt.Fprintln(os.Stderr, "Warning: this is a test program for Windows, mainly used for debugging this Go package. For a real WireGuard for Windows client, the repo you want is <https://git.zx2c4.com/wireguard-windows/>, which includes this code as a module.")
logger := device.NewLogger( logger := device.NewLogger(
device.LogLevelDebug, device.LogLevelVerbose,
fmt.Sprintf("(%s) ", interfaceName), fmt.Sprintf("(%s) ", interfaceName),
) )
logger.Infof("Starting wireguard-go version %v", device.WireGuardGoVersion) logger.Verbosef("Starting wireguard-go version %s", device.WireGuardGoVersion)
logger.Debugf("Debug log enabled")
tun, err := tun.CreateTUN(interfaceName, 0) tun, err := tun.CreateTUN(interfaceName, 0)
if err == nil { if err == nil {
@ -50,7 +49,7 @@ func main() {
device := device.NewDevice(tun, logger) device := device.NewDevice(tun, logger)
device.Up() device.Up()
logger.Infof("Device started") logger.Verbosef("Device started")
uapi, err := ipc.UAPIListen(interfaceName) uapi, err := ipc.UAPIListen(interfaceName)
if err != nil { if err != nil {
@ -71,7 +70,7 @@ func main() {
go device.IpcHandle(conn) go device.IpcHandle(conn)
} }
}() }()
logger.Infof("UAPI listener started") logger.Verbosef("UAPI listener started")
// wait for program to terminate // wait for program to terminate
@ -90,5 +89,5 @@ func main() {
uapi.Close() uapi.Close()
device.Close() device.Close()
logger.Infof("Shutting down") logger.Verbosef("Shutting down")
} }

View File

@ -36,7 +36,7 @@ netns0="wg-test-$$-0"
netns1="wg-test-$$-1" netns1="wg-test-$$-1"
netns2="wg-test-$$-2" netns2="wg-test-$$-2"
program=$1 program=$1
export LOG_LEVEL="info" export LOG_LEVEL="verbose"
pretty() { echo -e "\x1b[32m\x1b[1m[+] ${1:+NS$1: }${2}\x1b[0m" >&3; } pretty() { echo -e "\x1b[32m\x1b[1m[+] ${1:+NS$1: }${2}\x1b[0m" >&3; }
pp() { pretty "" "$*"; "$@"; } pp() { pretty "" "$*"; "$@"; }