add NOP netdev as default

Initialize netdev to dummy NOP netdev that gracefully errors out all netdev
interface calls.  This is to catch cases where useNetdev() was not
called by the app to set netdev.
This commit is contained in:
Scott Feldman
2024-05-22 08:44:30 -07:00
committed by Ron Evans
parent 7f3a3c9177
commit a237059610
+36 -2
View File
@@ -3,6 +3,7 @@
package net package net
import ( import (
"errors"
"net/netip" "net/netip"
"time" "time"
) )
@@ -24,8 +25,11 @@ const (
_F_SETFL = 0x4 _F_SETFL = 0x4
) )
// netdev is the current netdev, set by the application with useNetdev() // netdev is the current netdev, set by the application with useNetdev().
var netdev netdever //
// Initialized to a NOP netdev that errors out cleanly in case netdev was not
// explicitly set with useNetdev().
var netdev netdever = &nopNetdev{}
// (useNetdev is go:linkname'd from tinygo/drivers package) // (useNetdev is go:linkname'd from tinygo/drivers package)
func useNetdev(dev netdever) { func useNetdev(dev netdever) {
@@ -139,3 +143,33 @@ type netdever interface {
// to pass driver-specific configurations. // to pass driver-specific configurations.
SetSockOpt(sockfd int, level int, opt int, value interface{}) error SetSockOpt(sockfd int, level int, opt int, value interface{}) error
} }
var ErrNetdevNotSet = errors.New("Netdev not set")
// nopNetdev is a NOP netdev that errors out any interface calls
type nopNetdev struct {
}
func (n *nopNetdev) GetHostByName(name string) (netip.Addr, error) {
return netip.Addr{}, ErrNetdevNotSet
}
func (n *nopNetdev) Addr() (netip.Addr, error) { return netip.Addr{}, ErrNetdevNotSet }
func (n *nopNetdev) Socket(domain int, stype int, protocol int) (sockfd int, _ error) {
return -1, ErrNetdevNotSet
}
func (n *nopNetdev) Bind(sockfd int, ip netip.AddrPort) error { return ErrNetdevNotSet }
func (n *nopNetdev) Connect(sockfd int, host string, ip netip.AddrPort) error { return ErrNetdevNotSet }
func (n *nopNetdev) Listen(sockfd int, backlog int) error { return ErrNetdevNotSet }
func (n *nopNetdev) Accept(sockfd int) (int, netip.AddrPort, error) {
return -1, netip.AddrPort{}, ErrNetdevNotSet
}
func (n *nopNetdev) Send(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) {
return -1, ErrNetdevNotSet
}
func (n *nopNetdev) Recv(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) {
return -1, ErrNetdevNotSet
}
func (n *nopNetdev) Close(sockfd int) error { return ErrNetdevNotSet }
func (n *nopNetdev) SetSockOpt(sockfd int, level int, opt int, value interface{}) error {
return ErrNetdevNotSet
}