Skip to content

Commit a237059

Browse files
scottfeldmandeadprogram
authored andcommitted
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.
1 parent 7f3a3c9 commit a237059

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

netdev.go

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
package net
44

55
import (
6+
"errors"
67
"net/netip"
78
"time"
89
)
@@ -24,8 +25,11 @@ const (
2425
_F_SETFL = 0x4
2526
)
2627

27-
// netdev is the current netdev, set by the application with useNetdev()
28-
var netdev netdever
28+
// netdev is the current netdev, set by the application with useNetdev().
29+
//
30+
// Initialized to a NOP netdev that errors out cleanly in case netdev was not
31+
// explicitly set with useNetdev().
32+
var netdev netdever = &nopNetdev{}
2933

3034
// (useNetdev is go:linkname'd from tinygo/drivers package)
3135
func useNetdev(dev netdever) {
@@ -139,3 +143,33 @@ type netdever interface {
139143
// to pass driver-specific configurations.
140144
SetSockOpt(sockfd int, level int, opt int, value interface{}) error
141145
}
146+
147+
var ErrNetdevNotSet = errors.New("Netdev not set")
148+
149+
// nopNetdev is a NOP netdev that errors out any interface calls
150+
type nopNetdev struct {
151+
}
152+
153+
func (n *nopNetdev) GetHostByName(name string) (netip.Addr, error) {
154+
return netip.Addr{}, ErrNetdevNotSet
155+
}
156+
func (n *nopNetdev) Addr() (netip.Addr, error) { return netip.Addr{}, ErrNetdevNotSet }
157+
func (n *nopNetdev) Socket(domain int, stype int, protocol int) (sockfd int, _ error) {
158+
return -1, ErrNetdevNotSet
159+
}
160+
func (n *nopNetdev) Bind(sockfd int, ip netip.AddrPort) error { return ErrNetdevNotSet }
161+
func (n *nopNetdev) Connect(sockfd int, host string, ip netip.AddrPort) error { return ErrNetdevNotSet }
162+
func (n *nopNetdev) Listen(sockfd int, backlog int) error { return ErrNetdevNotSet }
163+
func (n *nopNetdev) Accept(sockfd int) (int, netip.AddrPort, error) {
164+
return -1, netip.AddrPort{}, ErrNetdevNotSet
165+
}
166+
func (n *nopNetdev) Send(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) {
167+
return -1, ErrNetdevNotSet
168+
}
169+
func (n *nopNetdev) Recv(sockfd int, buf []byte, flags int, deadline time.Time) (int, error) {
170+
return -1, ErrNetdevNotSet
171+
}
172+
func (n *nopNetdev) Close(sockfd int) error { return ErrNetdevNotSet }
173+
func (n *nopNetdev) SetSockOpt(sockfd int, level int, opt int, value interface{}) error {
174+
return ErrNetdevNotSet
175+
}

0 commit comments

Comments
 (0)