Skip to content

Commit

Permalink
add NOP netdev as default
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
scottfeldman authored and deadprogram committed Jul 20, 2024
1 parent 7f3a3c9 commit a237059
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions netdev.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package net

import (
"errors"
"net/netip"
"time"
)
Expand All @@ -24,8 +25,11 @@ const (
_F_SETFL = 0x4
)

// netdev is the current netdev, set by the application with useNetdev()
var netdev netdever
// netdev is the current netdev, set by the application with useNetdev().
//
// 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)
func useNetdev(dev netdever) {
Expand Down Expand Up @@ -139,3 +143,33 @@ type netdever interface {
// to pass driver-specific configurations.
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
}

0 comments on commit a237059

Please sign in to comment.