Make whisper tolerant to local time skews (#864)
This change adds adds an ability to use different source of time for whisper: when envelope is created it is used to set expiry to track when envelope needs to be expired This time is then used to check validity of the envelope when it is received. Currently If we receive an envelope that is sent from future - peer will get disconnected. If envelope that was received has an expiry less then now it will be simply dropped, if expiry is less than now + 10*2 seconds peer will get dropped. So, it is clear that whisper depends on time. And any time we get a skew with peers that is > 20s reliability will be grealy reduced. In this change another source of time for whisper will be used. This time source will use ntp servers from pool.ntp.org to compute offset. When whisper queries time - this offset will be added/substracted from current time. Query is executed every 2 mins, queries 5 different servers, cut offs min and max and the computes mean value. pool.ntp.org is resolved to different servers and according to documentation you will rarely hit the same. Closes: #687
This commit is contained in:
parent
357786eeca
commit
707221954f
|
@ -18,6 +18,12 @@
|
|||
packages = ["monotime"]
|
||||
revision = "ea17b1a17847fb6e4c0a91de0b674704693469b0"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/beevik/ntp"
|
||||
packages = ["."]
|
||||
revision = "62c80a04de2086884d8296004b6d74ee1846c582"
|
||||
version = "v0.2.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/beorn7/perks"
|
||||
|
@ -376,10 +382,14 @@
|
|||
branch = "master"
|
||||
name = "golang.org/x/net"
|
||||
packages = [
|
||||
"bpf",
|
||||
"context",
|
||||
"html",
|
||||
"html/atom",
|
||||
"html/charset",
|
||||
"internal/iana",
|
||||
"internal/socket",
|
||||
"ipv4",
|
||||
"websocket"
|
||||
]
|
||||
revision = "5ccada7d0a7ba9aeb5d3aca8d3501b4c2a509fec"
|
||||
|
@ -483,6 +493,6 @@
|
|||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "760ef0bfdecf48e51bf8a9e4409c04d46d1c74c8c42a8ca75447d5fd197f5095"
|
||||
inputs-digest = "c82f110ad74f6540b5ba89202a3e4e6cca24a7ec9eedd35248a3aa1e6d626275"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
|
|
|
@ -143,3 +143,7 @@ ignored = [ "github.com/ethereum/go-ethereum/ethapi" ]
|
|||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/vishvananda/netlink"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/beevik/ntp"
|
||||
version = "0.2.0"
|
||||
|
|
|
@ -0,0 +1,115 @@
|
|||
diff --git c/whisper/whisperv6/api.go w/whisper/whisperv6/api.go
|
||||
index 2de99f293..e0c3284b6 100644
|
||||
--- c/whisper/whisperv6/api.go
|
||||
+++ w/whisper/whisperv6/api.go
|
||||
@@ -285,7 +285,7 @@ func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (hexutil.
|
||||
}
|
||||
|
||||
var result []byte
|
||||
- env, err := whisperMsg.Wrap(params)
|
||||
+ env, err := whisperMsg.Wrap(params, api.w.GetCurrentTime())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
diff --git c/whisper/whisperv6/envelope.go w/whisper/whisperv6/envelope.go
|
||||
index c42d1fa8a..3b65fdba0 100644
|
||||
--- c/whisper/whisperv6/envelope.go
|
||||
+++ w/whisper/whisperv6/envelope.go
|
||||
@@ -62,9 +62,9 @@ func (e *Envelope) rlpWithoutNonce() []byte {
|
||||
|
||||
// NewEnvelope wraps a Whisper message with expiration and destination data
|
||||
// included into an envelope for network forwarding.
|
||||
-func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage) *Envelope {
|
||||
+func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage, now time.Time) *Envelope {
|
||||
env := Envelope{
|
||||
- Expiry: uint32(time.Now().Add(time.Second * time.Duration(ttl)).Unix()),
|
||||
+ Expiry: uint32(now.Add(time.Second * time.Duration(ttl)).Unix()),
|
||||
TTL: ttl,
|
||||
Topic: topic,
|
||||
Data: msg.Raw,
|
||||
diff --git c/whisper/whisperv6/message.go w/whisper/whisperv6/message.go
|
||||
index 2d4e86244..a12b445e2 100644
|
||||
--- c/whisper/whisperv6/message.go
|
||||
+++ w/whisper/whisperv6/message.go
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"errors"
|
||||
mrand "math/rand"
|
||||
"strconv"
|
||||
+ "time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
@@ -234,7 +235,7 @@ func generateSecureRandomData(length int) ([]byte, error) {
|
||||
}
|
||||
|
||||
// Wrap bundles the message into an Envelope to transmit over the network.
|
||||
-func (msg *sentMessage) Wrap(options *MessageParams) (envelope *Envelope, err error) {
|
||||
+func (msg *sentMessage) Wrap(options *MessageParams, now time.Time) (envelope *Envelope, err error) {
|
||||
if options.TTL == 0 {
|
||||
options.TTL = DefaultTTL
|
||||
}
|
||||
@@ -254,7 +255,7 @@ func (msg *sentMessage) Wrap(options *MessageParams) (envelope *Envelope, err er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
- envelope = NewEnvelope(options.TTL, options.Topic, msg)
|
||||
+ envelope = NewEnvelope(options.TTL, options.Topic, msg, now)
|
||||
if err = envelope.Seal(options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
diff --git c/whisper/whisperv6/whisper.go w/whisper/whisperv6/whisper.go
|
||||
index 8d56ece64..2bccfec33 100644
|
||||
--- c/whisper/whisperv6/whisper.go
|
||||
+++ w/whisper/whisperv6/whisper.go
|
||||
@@ -92,6 +92,8 @@ type Whisper struct {
|
||||
envelopeTracer EnvelopeTracer // Service collecting envelopes metadata
|
||||
|
||||
envelopeFeed event.Feed
|
||||
+
|
||||
+ timeSource func() time.Time // source of time for whisper
|
||||
}
|
||||
|
||||
// New creates a Whisper client ready to communicate through the Ethereum P2P network.
|
||||
@@ -110,6 +112,7 @@ func New(cfg *Config) *Whisper {
|
||||
p2pMsgQueue: make(chan *Envelope, messageQueueLimit),
|
||||
quit: make(chan struct{}),
|
||||
syncAllowance: DefaultSyncAllowance,
|
||||
+ timeSource: time.Now,
|
||||
}
|
||||
|
||||
whisper.filters = NewFilters(whisper)
|
||||
@@ -215,6 +218,16 @@ func (whisper *Whisper) APIs() []rpc.API {
|
||||
}
|
||||
}
|
||||
|
||||
+// SetTimeSource sets time source used by whisper for envelopes time and expiration logic.
|
||||
+func (whisper *Whisper) SetTimeSource(timeSource func() time.Time) {
|
||||
+ whisper.timeSource = timeSource
|
||||
+}
|
||||
+
|
||||
+// GetCurrentTime returns current time.
|
||||
+func (whisper *Whisper) GetCurrentTime() time.Time {
|
||||
+ return whisper.timeSource()
|
||||
+}
|
||||
+
|
||||
// RegisterServer registers MailServer interface.
|
||||
// MailServer will process all the incoming messages with p2pRequestCode.
|
||||
func (whisper *Whisper) RegisterServer(server MailServer) {
|
||||
@@ -829,7 +842,7 @@ func (whisper *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
|
||||
// appropriate time-stamp. In case of error, connection should be dropped.
|
||||
// param isP2P indicates whether the message is peer-to-peer (should not be forwarded).
|
||||
func (whisper *Whisper) add(envelope *Envelope, isP2P bool) (bool, error) {
|
||||
- now := uint32(time.Now().Unix())
|
||||
+ now := uint32(whisper.timeSource().Unix())
|
||||
sent := envelope.Expiry - envelope.TTL
|
||||
|
||||
if sent > now {
|
||||
@@ -988,7 +1001,7 @@ func (whisper *Whisper) expire() {
|
||||
whisper.statsMu.Lock()
|
||||
defer whisper.statsMu.Unlock()
|
||||
whisper.stats.reset()
|
||||
- now := uint32(time.Now().Unix())
|
||||
+ now := uint32(whisper.timeSource().Unix())
|
||||
for expiry, hashSet := range whisper.expirations {
|
||||
if expiry < now {
|
||||
// Dump all expired messages and remove timestamp
|
|
@ -24,6 +24,7 @@ import (
|
|||
"github.com/status-im/status-go/geth/rpc"
|
||||
"github.com/status-im/status-go/services/shhext"
|
||||
"github.com/status-im/status-go/services/status"
|
||||
"github.com/status-im/status-go/timesource"
|
||||
)
|
||||
|
||||
// tickerResolution is the delta to check blockchain sync progress.
|
||||
|
@ -52,6 +53,8 @@ type StatusNode struct {
|
|||
peerPool *peers.PeerPool
|
||||
db *leveldb.DB // used as a cache for PeerPool
|
||||
|
||||
timeManager *timesource.NTPTimeSource
|
||||
|
||||
log log.Logger
|
||||
}
|
||||
|
||||
|
@ -114,7 +117,9 @@ func (n *StatusNode) Start(config *params.NodeConfig, services ...node.ServiceCo
|
|||
if n.config.Discovery {
|
||||
return n.startPeerPool()
|
||||
}
|
||||
|
||||
if n.config.WhisperConfig != nil && n.config.WhisperConfig.Enabled {
|
||||
return n.setupWhisperTimeSource()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -148,6 +153,19 @@ func (n *StatusNode) start(services []node.ServiceConstructor) error {
|
|||
return n.gethNode.Start()
|
||||
}
|
||||
|
||||
func (n *StatusNode) setupWhisperTimeSource() error {
|
||||
var w *whisper.Whisper
|
||||
err := n.gethService(&w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Debug("Using ntp time source manager as a source of time in whisper.")
|
||||
n.timeManager = timesource.Default()
|
||||
n.timeManager.Start()
|
||||
w.SetTimeSource(n.timeManager.Now)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *StatusNode) setupRPCClient() (err error) {
|
||||
// setup public RPC client
|
||||
gethNodeClient, err := n.gethNode.AttachPublic()
|
||||
|
@ -205,6 +223,11 @@ func (n *StatusNode) stop() error {
|
|||
n.register = nil
|
||||
n.peerPool = nil
|
||||
|
||||
if n.timeManager != nil {
|
||||
log.Debug("Stopping time source manager")
|
||||
n.timeManager.Stop()
|
||||
n.timeManager = nil
|
||||
}
|
||||
if err := n.gethNode.Stop(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
@ -52,11 +52,11 @@ type MessagesRequest struct {
|
|||
SymKeyID string `json:"symKeyID"`
|
||||
}
|
||||
|
||||
func (r *MessagesRequest) setDefaults() {
|
||||
func (r *MessagesRequest) setDefaults(now time.Time) {
|
||||
// set From and To defaults
|
||||
if r.From == 0 && r.To == 0 {
|
||||
r.From = uint32(time.Now().UTC().Add(-24 * time.Hour).Unix())
|
||||
r.To = uint32(time.Now().UTC().Unix())
|
||||
r.From = uint32(now.UTC().Add(-24 * time.Hour).Unix())
|
||||
r.To = uint32(now.UTC().Unix())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -94,11 +94,9 @@ func (api *PublicAPI) Post(ctx context.Context, req whisper.NewMessage) (hash he
|
|||
// RequestMessages sends a request for historic messages to a MailServer.
|
||||
func (api *PublicAPI) RequestMessages(_ context.Context, r MessagesRequest) (bool, error) {
|
||||
api.log.Info("RequestMessages", "request", r)
|
||||
|
||||
r.setDefaults()
|
||||
|
||||
shh := api.service.w
|
||||
|
||||
now := api.service.w.GetCurrentTime()
|
||||
r.setDefaults(now)
|
||||
mailServerNode, err := discover.ParseNode(r.MailServerPeer)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%v: %v", ErrInvalidMailServerPeer, err)
|
||||
|
@ -109,11 +107,10 @@ func (api *PublicAPI) RequestMessages(_ context.Context, r MessagesRequest) (boo
|
|||
return false, fmt.Errorf("%v: %v", ErrInvalidSymKeyID, err)
|
||||
}
|
||||
|
||||
envelope, err := makeEnvelop(makePayload(r), symKey, api.service.nodeID, shh.MinPow())
|
||||
envelope, err := makeEnvelop(makePayload(r), symKey, api.service.nodeID, shh.MinPow(), now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if err := shh.RequestHistoricMessages(mailServerNode.ID[:], envelope); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
@ -137,7 +134,7 @@ func (api *PublicAPI) GetNewFilterMessages(filterID string) ([]*whisper.Message,
|
|||
// makeEnvelop makes an envelop for a historic messages request.
|
||||
// Symmetric key is used to authenticate to MailServer.
|
||||
// PK is the current node ID.
|
||||
func makeEnvelop(payload []byte, symKey []byte, nodeID *ecdsa.PrivateKey, pow float64) (*whisper.Envelope, error) {
|
||||
func makeEnvelop(payload []byte, symKey []byte, nodeID *ecdsa.PrivateKey, pow float64, now time.Time) (*whisper.Envelope, error) {
|
||||
params := whisper.MessageParams{
|
||||
PoW: pow,
|
||||
Payload: payload,
|
||||
|
@ -149,7 +146,7 @@ func makeEnvelop(payload []byte, symKey []byte, nodeID *ecdsa.PrivateKey, pow fl
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return message.Wrap(¶ms)
|
||||
return message.Wrap(¶ms, now)
|
||||
}
|
||||
|
||||
// makePayload makes a specific payload for MailServer to request historic messages.
|
||||
|
|
|
@ -130,7 +130,7 @@ func (s *ShhExtSuite) TestWaitMessageExpired() {
|
|||
|
||||
func (s *ShhExtSuite) TestRequestMessagesDefaults() {
|
||||
r := MessagesRequest{}
|
||||
r.setDefaults()
|
||||
r.setDefaults(time.Now())
|
||||
s.NotZero(r.From)
|
||||
s.InEpsilon(uint32(time.Now().UTC().Unix()), r.To, 1.0)
|
||||
}
|
||||
|
|
|
@ -104,7 +104,7 @@ func (s *WhisperMailboxSuite) TestRequestMessageFromMailboxAsync() {
|
|||
"topic":"` + topic.String() + `",
|
||||
"symKeyID":"` + MailServerKeyID + `",
|
||||
"from":0,
|
||||
"to":` + strconv.FormatInt(time.Now().Unix(), 10) + `
|
||||
"to":` + strconv.FormatInt(senderWhisperService.GetCurrentTime().Unix(), 10) + `
|
||||
}]
|
||||
}`
|
||||
resp := rpcClient.CallRaw(reqMessagesBody)
|
||||
|
@ -273,8 +273,8 @@ func (s *WhisperMailboxSuite) TestRequestMessagesInGroupChat() {
|
|||
s.Require().Equal(0, len(messages))
|
||||
|
||||
// Request each one messages from mailbox using enode.
|
||||
s.requestHistoricMessages(bobRPCClient, mailboxEnode, bobMailServerKeyID, groupChatTopic.String())
|
||||
s.requestHistoricMessages(charlieRPCClient, mailboxEnode, charlieMailServerKeyID, groupChatTopic.String())
|
||||
s.requestHistoricMessages(bobWhisperService, bobRPCClient, mailboxEnode, bobMailServerKeyID, groupChatTopic.String())
|
||||
s.requestHistoricMessages(charlieWhisperService, charlieRPCClient, mailboxEnode, charlieMailServerKeyID, groupChatTopic.String())
|
||||
// Wait to receive p2p messages.
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
|
@ -481,7 +481,7 @@ func (s *WhisperMailboxSuite) addSymKey(rpcCli *rpc.Client, symkey string) strin
|
|||
}
|
||||
|
||||
// requestHistoricMessages asks a mailnode to resend messages.
|
||||
func (s *WhisperMailboxSuite) requestHistoricMessages(rpcCli *rpc.Client, mailboxEnode, mailServerKeyID, topic string) {
|
||||
func (s *WhisperMailboxSuite) requestHistoricMessages(w *whisper.Whisper, rpcCli *rpc.Client, mailboxEnode, mailServerKeyID, topic string) {
|
||||
resp := rpcCli.CallRaw(`{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 2,
|
||||
|
@ -491,7 +491,7 @@ func (s *WhisperMailboxSuite) requestHistoricMessages(rpcCli *rpc.Client, mailbo
|
|||
"topic":"` + topic + `",
|
||||
"symKeyID":"` + mailServerKeyID + `",
|
||||
"from":0,
|
||||
"to":` + strconv.FormatInt(time.Now().Unix(), 10) + `
|
||||
"to":` + strconv.FormatInt(w.GetCurrentTime().Unix(), 10) + `
|
||||
}]
|
||||
}`)
|
||||
reqMessagesResp := baseRPCResponse{}
|
||||
|
|
|
@ -0,0 +1,165 @@
|
|||
package timesource
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/beevik/ntp"
|
||||
"github.com/ethereum/go-ethereum/log"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultServer will be internally resolved to the closest available.
|
||||
// also it rarely queries same server more than once.
|
||||
DefaultServer = "pool.ntp.org"
|
||||
|
||||
// DefaultAttempts defines how many servers we will query
|
||||
DefaultAttempts = 3
|
||||
|
||||
// DefaultUpdatePeriod defines how often time will be queried from ntp.
|
||||
DefaultUpdatePeriod = 2 * time.Minute
|
||||
)
|
||||
|
||||
type ntpQuery func(string) (*ntp.Response, error)
|
||||
|
||||
type queryResponse struct {
|
||||
Offset time.Duration
|
||||
Error error
|
||||
}
|
||||
|
||||
type multiRPCError []error
|
||||
|
||||
func (e multiRPCError) Error() string {
|
||||
var b bytes.Buffer
|
||||
b.WriteString("RPC failed: ")
|
||||
more := false
|
||||
for _, err := range e {
|
||||
if more {
|
||||
b.WriteString("; ")
|
||||
}
|
||||
b.WriteString(err.Error())
|
||||
more = true
|
||||
}
|
||||
b.WriteString(".")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func computeOffset(timeQuery ntpQuery, server string, attempts int) (time.Duration, error) {
|
||||
if attempts == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
responses := make(chan queryResponse, attempts)
|
||||
for i := 0; i < attempts; i++ {
|
||||
go func() {
|
||||
// ntp.Query default timeout is 5s
|
||||
response, err := timeQuery(server)
|
||||
if err != nil {
|
||||
responses <- queryResponse{Error: err}
|
||||
return
|
||||
}
|
||||
responses <- queryResponse{Offset: response.ClockOffset}
|
||||
}()
|
||||
}
|
||||
var (
|
||||
rpcErrors multiRPCError
|
||||
offsets []time.Duration
|
||||
collected int
|
||||
)
|
||||
for response := range responses {
|
||||
if response.Error != nil {
|
||||
rpcErrors = append(rpcErrors, response.Error)
|
||||
} else {
|
||||
offsets = append(offsets, response.Offset)
|
||||
}
|
||||
collected++
|
||||
if collected == attempts {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(rpcErrors) != 0 {
|
||||
return 0, rpcErrors
|
||||
}
|
||||
sort.SliceStable(offsets, func(i, j int) bool {
|
||||
return offsets[i] > offsets[j]
|
||||
})
|
||||
mid := attempts / 2
|
||||
if len(offsets)%2 == 0 {
|
||||
return (offsets[mid-1] + offsets[mid]) / 2, nil
|
||||
}
|
||||
return offsets[mid], nil
|
||||
}
|
||||
|
||||
// Default initializes time source with default config values.
|
||||
func Default() *NTPTimeSource {
|
||||
return &NTPTimeSource{
|
||||
server: DefaultServer,
|
||||
attempts: DefaultAttempts,
|
||||
updatePeriod: DefaultUpdatePeriod,
|
||||
timeQuery: ntp.Query,
|
||||
}
|
||||
}
|
||||
|
||||
// NTPTimeSource provides source of time that tries to be resistant to time skews.
|
||||
// It does so by periodically querying time offset from ntp servers.
|
||||
type NTPTimeSource struct {
|
||||
server string
|
||||
attempts int
|
||||
updatePeriod time.Duration
|
||||
timeQuery ntpQuery // for ease of testing
|
||||
|
||||
quit chan struct{}
|
||||
wg sync.WaitGroup
|
||||
|
||||
mu sync.RWMutex
|
||||
latestOffset time.Duration
|
||||
}
|
||||
|
||||
// Now returns time adjusted by latest known offset
|
||||
func (s *NTPTimeSource) Now() time.Time {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return time.Now().Add(s.latestOffset)
|
||||
}
|
||||
|
||||
func (s *NTPTimeSource) updateOffset() {
|
||||
offset, err := computeOffset(s.timeQuery, s.server, s.attempts)
|
||||
if err != nil {
|
||||
log.Error("failed to compute offset", "error", err)
|
||||
return
|
||||
}
|
||||
log.Info("Difference with ntp servers", "offset", offset)
|
||||
s.mu.Lock()
|
||||
s.latestOffset = offset
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// Start runs a goroutine that updates local offset every updatePeriod.
|
||||
func (s *NTPTimeSource) Start() {
|
||||
s.quit = make(chan struct{})
|
||||
ticker := time.NewTicker(s.updatePeriod)
|
||||
// we try to do it synchronously so that user can have reliable messages right away
|
||||
s.updateOffset()
|
||||
s.wg.Add(1)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.updateOffset()
|
||||
case <-s.quit:
|
||||
s.wg.Done()
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop goroutine that updates time source.
|
||||
func (s *NTPTimeSource) Stop() {
|
||||
if s.quit == nil {
|
||||
return
|
||||
}
|
||||
close(s.quit)
|
||||
s.wg.Wait()
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
package timesource
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/beevik/ntp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const (
|
||||
// clockCompareDelta declares time required between multiple calls to time.Now
|
||||
clockCompareDelta = 30 * time.Microsecond
|
||||
)
|
||||
|
||||
type testCase struct {
|
||||
description string
|
||||
attempts int
|
||||
responses []queryResponse
|
||||
expected time.Duration
|
||||
expectError bool
|
||||
|
||||
// actual attempts are mutable
|
||||
mu sync.Mutex
|
||||
actualAttempts int
|
||||
}
|
||||
|
||||
func (tc *testCase) query(string) (*ntp.Response, error) {
|
||||
tc.mu.Lock()
|
||||
defer func() {
|
||||
tc.actualAttempts++
|
||||
tc.mu.Unlock()
|
||||
}()
|
||||
response := &ntp.Response{ClockOffset: tc.responses[tc.actualAttempts].Offset}
|
||||
return response, tc.responses[tc.actualAttempts].Error
|
||||
}
|
||||
|
||||
func newTestCases() []*testCase {
|
||||
return []*testCase{
|
||||
{
|
||||
description: "SameResponse",
|
||||
attempts: 3,
|
||||
responses: []queryResponse{
|
||||
{Offset: 10 * time.Second},
|
||||
{Offset: 10 * time.Second},
|
||||
{Offset: 10 * time.Second},
|
||||
},
|
||||
expected: 10 * time.Second,
|
||||
},
|
||||
{
|
||||
description: "Median",
|
||||
attempts: 3,
|
||||
responses: []queryResponse{
|
||||
{Offset: 10 * time.Second},
|
||||
{Offset: 20 * time.Second},
|
||||
{Offset: 30 * time.Second},
|
||||
},
|
||||
expected: 20 * time.Second,
|
||||
},
|
||||
{
|
||||
description: "EvenMedian",
|
||||
attempts: 2,
|
||||
responses: []queryResponse{
|
||||
{Offset: 10 * time.Second},
|
||||
{Offset: 20 * time.Second},
|
||||
},
|
||||
expected: 15 * time.Second,
|
||||
},
|
||||
{
|
||||
description: "Error",
|
||||
attempts: 3,
|
||||
responses: []queryResponse{
|
||||
{Offset: 10 * time.Second},
|
||||
{Error: errors.New("test")},
|
||||
{Offset: 30 * time.Second},
|
||||
},
|
||||
expected: time.Duration(0),
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
description: "MultiError",
|
||||
attempts: 3,
|
||||
responses: []queryResponse{
|
||||
{Error: errors.New("test 1")},
|
||||
{Error: errors.New("test 2")},
|
||||
{Error: errors.New("test 3")},
|
||||
},
|
||||
expected: time.Duration(0),
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeOffset(t *testing.T) {
|
||||
for _, tc := range newTestCases() {
|
||||
t.Run(tc.description, func(t *testing.T) {
|
||||
offset, err := computeOffset(tc.query, "", tc.attempts)
|
||||
if tc.expectError {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
assert.Equal(t, tc.expected, offset)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNTPTimeSource(t *testing.T) {
|
||||
for _, tc := range newTestCases() {
|
||||
t.Run(tc.description, func(t *testing.T) {
|
||||
source := &NTPTimeSource{
|
||||
attempts: tc.attempts,
|
||||
timeQuery: tc.query,
|
||||
}
|
||||
assert.WithinDuration(t, time.Now(), source.Now(), clockCompareDelta)
|
||||
source.updateOffset()
|
||||
assert.WithinDuration(t, time.Now().Add(tc.expected), source.Now(), clockCompareDelta)
|
||||
})
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
Brett Vickers (beevik)
|
||||
Mikhail Salosin (AlphaB)
|
||||
Anton Tolchanov (knyar)
|
||||
Christopher Batey (chbatey)
|
||||
Meng Zhuo (mengzhuo)
|
||||
Leonid Evdokimov (darkk)
|
||||
Ask Bjørn Hansen (abh)
|
|
@ -0,0 +1,24 @@
|
|||
Copyright 2015-2017 Brett Vickers. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDER ``AS IS'' AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -0,0 +1,565 @@
|
|||
// Copyright 2015-2017 Brett Vickers.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package ntp provides an implementation of a Simple NTP (SNTP) client
|
||||
// capable of querying the current time from a remote NTP server. See
|
||||
// RFC5905 (https://tools.ietf.org/html/rfc5905) for more details.
|
||||
//
|
||||
// This approach grew out of a go-nuts post by Michael Hofmann:
|
||||
// https://groups.google.com/forum/?fromgroups#!topic/golang-nuts/FlcdMU5fkLQ
|
||||
package ntp
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/ipv4"
|
||||
)
|
||||
|
||||
// The LeapIndicator is used to warn if a leap second should be inserted
|
||||
// or deleted in the last minute of the current month.
|
||||
type LeapIndicator uint8
|
||||
|
||||
const (
|
||||
// LeapNoWarning indicates no impending leap second.
|
||||
LeapNoWarning LeapIndicator = 0
|
||||
|
||||
// LeapAddSecond indicates the last minute of the day has 61 seconds.
|
||||
LeapAddSecond = 1
|
||||
|
||||
// LeapDelSecond indicates the last minute of the day has 59 seconds.
|
||||
LeapDelSecond = 2
|
||||
|
||||
// LeapNotInSync indicates an unsynchronized leap second.
|
||||
LeapNotInSync = 3
|
||||
)
|
||||
|
||||
// Internal constants
|
||||
const (
|
||||
defaultNtpVersion = 4
|
||||
nanoPerSec = 1000000000
|
||||
maxStratum = 16
|
||||
defaultTimeout = 5 * time.Second
|
||||
maxPollInterval = (1 << 17) * time.Second
|
||||
maxDispersion = 16 * time.Second
|
||||
)
|
||||
|
||||
// Internal variables
|
||||
var (
|
||||
ntpEpoch = time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
)
|
||||
|
||||
type mode uint8
|
||||
|
||||
// NTP modes. This package uses only client mode.
|
||||
const (
|
||||
reserved mode = 0 + iota
|
||||
symmetricActive
|
||||
symmetricPassive
|
||||
client
|
||||
server
|
||||
broadcast
|
||||
controlMessage
|
||||
reservedPrivate
|
||||
)
|
||||
|
||||
// An ntpTime is a 64-bit fixed-point (Q32.32) representation of the number of
|
||||
// seconds elapsed.
|
||||
type ntpTime uint64
|
||||
|
||||
// Duration interprets the fixed-point ntpTime as a number of elapsed seconds
|
||||
// and returns the corresponding time.Duration value.
|
||||
func (t ntpTime) Duration() time.Duration {
|
||||
sec := (t >> 32) * nanoPerSec
|
||||
frac := (t & 0xffffffff) * nanoPerSec >> 32
|
||||
return time.Duration(sec + frac)
|
||||
}
|
||||
|
||||
// Time interprets the fixed-point ntpTime as an absolute time and returns
|
||||
// the corresponding time.Time value.
|
||||
func (t ntpTime) Time() time.Time {
|
||||
return ntpEpoch.Add(t.Duration())
|
||||
}
|
||||
|
||||
// toNtpTime converts the time.Time value t into its 64-bit fixed-point
|
||||
// ntpTime representation.
|
||||
func toNtpTime(t time.Time) ntpTime {
|
||||
nsec := uint64(t.Sub(ntpEpoch))
|
||||
sec := nsec / nanoPerSec
|
||||
// Round up the fractional component so that repeated conversions
|
||||
// between time.Time and ntpTime do not yield continually decreasing
|
||||
// results.
|
||||
frac := (((nsec - sec*nanoPerSec) << 32) + nanoPerSec - 1) / nanoPerSec
|
||||
return ntpTime(sec<<32 | frac)
|
||||
}
|
||||
|
||||
// An ntpTimeShort is a 32-bit fixed-point (Q16.16) representation of the
|
||||
// number of seconds elapsed.
|
||||
type ntpTimeShort uint32
|
||||
|
||||
// Duration interprets the fixed-point ntpTimeShort as a number of elapsed
|
||||
// seconds and returns the corresponding time.Duration value.
|
||||
func (t ntpTimeShort) Duration() time.Duration {
|
||||
t64 := uint64(t)
|
||||
sec := (t64 >> 16) * nanoPerSec
|
||||
frac := (t64 & 0xffff) * nanoPerSec >> 16
|
||||
return time.Duration(sec + frac)
|
||||
}
|
||||
|
||||
// msg is an internal representation of an NTP packet.
|
||||
type msg struct {
|
||||
LiVnMode uint8 // Leap Indicator (2) + Version (3) + Mode (3)
|
||||
Stratum uint8
|
||||
Poll int8
|
||||
Precision int8
|
||||
RootDelay ntpTimeShort
|
||||
RootDispersion ntpTimeShort
|
||||
ReferenceID uint32
|
||||
ReferenceTime ntpTime
|
||||
OriginTime ntpTime
|
||||
ReceiveTime ntpTime
|
||||
TransmitTime ntpTime
|
||||
}
|
||||
|
||||
// setVersion sets the NTP protocol version on the message.
|
||||
func (m *msg) setVersion(v int) {
|
||||
m.LiVnMode = (m.LiVnMode & 0xc7) | uint8(v)<<3
|
||||
}
|
||||
|
||||
// setMode sets the NTP protocol mode on the message.
|
||||
func (m *msg) setMode(md mode) {
|
||||
m.LiVnMode = (m.LiVnMode & 0xf8) | uint8(md)
|
||||
}
|
||||
|
||||
// setLeap modifies the leap indicator on the message.
|
||||
func (m *msg) setLeap(li LeapIndicator) {
|
||||
m.LiVnMode = (m.LiVnMode & 0x3f) | uint8(li)<<6
|
||||
}
|
||||
|
||||
// getVersion returns the version value in the message.
|
||||
func (m *msg) getVersion() int {
|
||||
return int((m.LiVnMode >> 3) & 0x07)
|
||||
}
|
||||
|
||||
// getMode returns the mode value in the message.
|
||||
func (m *msg) getMode() mode {
|
||||
return mode(m.LiVnMode & 0x07)
|
||||
}
|
||||
|
||||
// getLeap returns the leap indicator on the message.
|
||||
func (m *msg) getLeap() LeapIndicator {
|
||||
return LeapIndicator((m.LiVnMode >> 6) & 0x03)
|
||||
}
|
||||
|
||||
// QueryOptions contains the list of configurable options that may be used
|
||||
// with the QueryWithOptions function.
|
||||
type QueryOptions struct {
|
||||
Timeout time.Duration // defaults to 5 seconds
|
||||
Version int // NTP protocol version, defaults to 4
|
||||
LocalAddress string // IP address to use for the client address
|
||||
Port int // Server port, defaults to 123
|
||||
TTL int // IP TTL to use, defaults to system default
|
||||
}
|
||||
|
||||
// A Response contains time data, some of which is returned by the NTP server
|
||||
// and some of which is calculated by the client.
|
||||
type Response struct {
|
||||
// Time is the transmit time reported by the server just before it
|
||||
// responded to the client's NTP query.
|
||||
Time time.Time
|
||||
|
||||
// ClockOffset is the estimated offset of the client clock relative to
|
||||
// the server. Add this to the client's system clock time to obtain a
|
||||
// more accurate time.
|
||||
ClockOffset time.Duration
|
||||
|
||||
// RTT is the measured round-trip-time delay estimate between the client
|
||||
// and the server.
|
||||
RTT time.Duration
|
||||
|
||||
// Precision is the reported precision of the server's clock.
|
||||
Precision time.Duration
|
||||
|
||||
// Stratum is the "stratum level" of the server. The smaller the number,
|
||||
// the closer the server is to the reference clock. Stratum 1 servers are
|
||||
// attached directly to the reference clock. A stratum value of 0
|
||||
// indicates the "kiss of death," which typically occurs when the client
|
||||
// issues too many requests to the server in a short period of time.
|
||||
Stratum uint8
|
||||
|
||||
// ReferenceID is a 32-bit identifier identifying the server or
|
||||
// reference clock.
|
||||
ReferenceID uint32
|
||||
|
||||
// ReferenceTime is the time when the server's system clock was last
|
||||
// set or corrected.
|
||||
ReferenceTime time.Time
|
||||
|
||||
// RootDelay is the server's estimated aggregate round-trip-time delay to
|
||||
// the stratum 1 server.
|
||||
RootDelay time.Duration
|
||||
|
||||
// RootDispersion is the server's estimated maximum measurement error
|
||||
// relative to the stratum 1 server.
|
||||
RootDispersion time.Duration
|
||||
|
||||
// RootDistance is an estimate of the total synchronization distance
|
||||
// between the client and the stratum 1 server.
|
||||
RootDistance time.Duration
|
||||
|
||||
// Leap indicates whether a leap second should be added or removed from
|
||||
// the current month's last minute.
|
||||
Leap LeapIndicator
|
||||
|
||||
// MinError is a lower bound on the error between the client and server
|
||||
// clocks. When the client and server are not synchronized to the same
|
||||
// clock, the reported timestamps may appear to violate the principle of
|
||||
// causality. In other words, the NTP server's response may indicate
|
||||
// that a message was received before it was sent. In such cases, the
|
||||
// minimum error may be useful.
|
||||
MinError time.Duration
|
||||
|
||||
// KissCode is a 4-character string describing the reason for a
|
||||
// "kiss of death" response (stratum = 0). For a list of standard kiss
|
||||
// codes, see https://tools.ietf.org/html/rfc5905#section-7.4.
|
||||
KissCode string
|
||||
|
||||
// Poll is the maximum interval between successive NTP polling messages.
|
||||
// It is not relevant for simple NTP clients like this one.
|
||||
Poll time.Duration
|
||||
}
|
||||
|
||||
// Validate checks if the response is valid for the purposes of time
|
||||
// synchronization.
|
||||
func (r *Response) Validate() error {
|
||||
// Handle invalid stratum values.
|
||||
if r.Stratum == 0 {
|
||||
return fmt.Errorf("kiss of death received: %s", r.KissCode)
|
||||
}
|
||||
if r.Stratum >= maxStratum {
|
||||
return errors.New("invalid stratum in response")
|
||||
}
|
||||
|
||||
// Handle invalid leap second indicator.
|
||||
if r.Leap == LeapNotInSync {
|
||||
return errors.New("invalid leap second")
|
||||
}
|
||||
|
||||
// Estimate the "freshness" of the time. If it exceeds the maximum
|
||||
// polling interval (~36 hours), then it cannot be considered "fresh".
|
||||
freshness := r.Time.Sub(r.ReferenceTime)
|
||||
if freshness > maxPollInterval {
|
||||
return errors.New("server clock not fresh")
|
||||
}
|
||||
|
||||
// Calculate the peer synchronization distance, lambda:
|
||||
// lambda := RootDelay/2 + RootDispersion
|
||||
// If this value exceeds MAXDISP (16s), then the time is not suitable
|
||||
// for synchronization purposes.
|
||||
// https://tools.ietf.org/html/rfc5905#appendix-A.5.1.1.
|
||||
lambda := r.RootDelay/2 + r.RootDispersion
|
||||
if lambda > maxDispersion {
|
||||
return errors.New("invalid dispersion")
|
||||
}
|
||||
|
||||
// If the server's transmit time is before its reference time, the
|
||||
// response is invalid.
|
||||
if r.Time.Before(r.ReferenceTime) {
|
||||
return errors.New("invalid time reported")
|
||||
}
|
||||
|
||||
// nil means the response is valid.
|
||||
return nil
|
||||
}
|
||||
|
||||
// Query returns a response from the remote NTP server host. It contains
|
||||
// the time at which the server transmitted the response as well as other
|
||||
// useful information about the time and the remote server.
|
||||
func Query(host string) (*Response, error) {
|
||||
return QueryWithOptions(host, QueryOptions{})
|
||||
}
|
||||
|
||||
// QueryWithOptions performs the same function as Query but allows for the
|
||||
// customization of several query options.
|
||||
func QueryWithOptions(host string, opt QueryOptions) (*Response, error) {
|
||||
m, now, err := getTime(host, opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parseTime(m, now), nil
|
||||
}
|
||||
|
||||
// TimeV returns the current time using information from a remote NTP server.
|
||||
// On error, it returns the local system time. The version may be 2, 3, or 4.
|
||||
//
|
||||
// Deprecated: TimeV is deprecated. Use QueryWithOptions instead.
|
||||
func TimeV(host string, version int) (time.Time, error) {
|
||||
m, recvTime, err := getTime(host, QueryOptions{Version: version})
|
||||
if err != nil {
|
||||
return time.Now(), err
|
||||
}
|
||||
|
||||
r := parseTime(m, recvTime)
|
||||
err = r.Validate()
|
||||
if err != nil {
|
||||
return time.Now(), err
|
||||
}
|
||||
|
||||
// Use the clock offset to calculate the time.
|
||||
return time.Now().Add(r.ClockOffset), nil
|
||||
}
|
||||
|
||||
// Time returns the current time using information from a remote NTP server.
|
||||
// It uses version 4 of the NTP protocol. On error, it returns the local
|
||||
// system time.
|
||||
func Time(host string) (time.Time, error) {
|
||||
return TimeV(host, defaultNtpVersion)
|
||||
}
|
||||
|
||||
// getTime performs the NTP server query and returns the response message
|
||||
// along with the local system time it was received.
|
||||
func getTime(host string, opt QueryOptions) (*msg, ntpTime, error) {
|
||||
if opt.Version == 0 {
|
||||
opt.Version = defaultNtpVersion
|
||||
}
|
||||
if opt.Version < 2 || opt.Version > 4 {
|
||||
return nil, 0, errors.New("invalid protocol version requested")
|
||||
}
|
||||
|
||||
// Resolve the remote NTP server address.
|
||||
raddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(host, "123"))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Resolve the local address if specified as an option.
|
||||
var laddr *net.UDPAddr
|
||||
if opt.LocalAddress != "" {
|
||||
laddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(opt.LocalAddress, "0"))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
}
|
||||
|
||||
// Override the port if requested.
|
||||
if opt.Port != 0 {
|
||||
raddr.Port = opt.Port
|
||||
}
|
||||
|
||||
// Prepare a "connection" to the remote server.
|
||||
con, err := net.DialUDP("udp", laddr, raddr)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer con.Close()
|
||||
|
||||
// Set a TTL for the packet if requested.
|
||||
if opt.TTL != 0 {
|
||||
ipcon := ipv4.NewConn(con)
|
||||
err = ipcon.SetTTL(opt.TTL)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
}
|
||||
|
||||
// Set a timeout on the connection.
|
||||
if opt.Timeout == 0 {
|
||||
opt.Timeout = defaultTimeout
|
||||
}
|
||||
con.SetDeadline(time.Now().Add(opt.Timeout))
|
||||
|
||||
// Allocate a message to hold the response.
|
||||
recvMsg := new(msg)
|
||||
|
||||
// Allocate a message to hold the query.
|
||||
xmitMsg := new(msg)
|
||||
xmitMsg.setMode(client)
|
||||
xmitMsg.setVersion(opt.Version)
|
||||
xmitMsg.setLeap(LeapNotInSync)
|
||||
|
||||
// To ensure privacy and prevent spoofing, try to use a random 64-bit
|
||||
// value for the TransmitTime. If crypto/rand couldn't generate a
|
||||
// random value, fall back to using the system clock. Keep track of
|
||||
// when the messsage was actually transmitted.
|
||||
bits := make([]byte, 8)
|
||||
_, err = rand.Read(bits)
|
||||
var xmitTime time.Time
|
||||
if err == nil {
|
||||
xmitMsg.TransmitTime = ntpTime(binary.BigEndian.Uint64(bits))
|
||||
xmitTime = time.Now()
|
||||
} else {
|
||||
xmitTime = time.Now()
|
||||
xmitMsg.TransmitTime = toNtpTime(xmitTime)
|
||||
}
|
||||
|
||||
// Transmit the query.
|
||||
err = binary.Write(con, binary.BigEndian, xmitMsg)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Receive the response.
|
||||
err = binary.Read(con, binary.BigEndian, recvMsg)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Keep track of the time the response was received.
|
||||
delta := time.Since(xmitTime)
|
||||
if delta < 0 {
|
||||
// The local system may have had its clock adjusted since it
|
||||
// sent the query. In go 1.9 and later, time.Since ensures
|
||||
// that a monotonic clock is used, so delta can never be less
|
||||
// than zero. In versions before 1.9, a monotonic clock is
|
||||
// not used, so we have to check.
|
||||
return nil, 0, errors.New("client clock ticked backwards")
|
||||
}
|
||||
recvTime := toNtpTime(xmitTime.Add(delta))
|
||||
|
||||
// Check for invalid fields.
|
||||
if recvMsg.getMode() != server {
|
||||
return nil, 0, errors.New("invalid mode in response")
|
||||
}
|
||||
if recvMsg.TransmitTime == ntpTime(0) {
|
||||
return nil, 0, errors.New("invalid transmit time in response")
|
||||
}
|
||||
if recvMsg.OriginTime != xmitMsg.TransmitTime {
|
||||
return nil, 0, errors.New("server response mismatch")
|
||||
}
|
||||
if recvMsg.ReceiveTime > recvMsg.TransmitTime {
|
||||
return nil, 0, errors.New("server clock ticked backwards")
|
||||
}
|
||||
|
||||
// Correct the received message's origin time using the actual
|
||||
// transmit time.
|
||||
recvMsg.OriginTime = toNtpTime(xmitTime)
|
||||
|
||||
return recvMsg, recvTime, nil
|
||||
}
|
||||
|
||||
// parseTime parses the NTP packet along with the packet receive time to
|
||||
// generate a Response record.
|
||||
func parseTime(m *msg, recvTime ntpTime) *Response {
|
||||
r := &Response{
|
||||
Time: m.TransmitTime.Time(),
|
||||
ClockOffset: offset(m.OriginTime, m.ReceiveTime, m.TransmitTime, recvTime),
|
||||
RTT: rtt(m.OriginTime, m.ReceiveTime, m.TransmitTime, recvTime),
|
||||
Precision: toInterval(m.Precision),
|
||||
Stratum: m.Stratum,
|
||||
ReferenceID: m.ReferenceID,
|
||||
ReferenceTime: m.ReferenceTime.Time(),
|
||||
RootDelay: m.RootDelay.Duration(),
|
||||
RootDispersion: m.RootDispersion.Duration(),
|
||||
Leap: m.getLeap(),
|
||||
MinError: minError(m.OriginTime, m.ReceiveTime, m.TransmitTime, recvTime),
|
||||
Poll: toInterval(m.Poll),
|
||||
}
|
||||
|
||||
// Calculate values depending on other calculated values
|
||||
r.RootDistance = rootDistance(r.RTT, r.RootDelay, r.RootDispersion)
|
||||
|
||||
// If a kiss of death was received, interpret the reference ID as
|
||||
// a kiss code.
|
||||
if r.Stratum == 0 {
|
||||
r.KissCode = kissCode(r.ReferenceID)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// The following helper functions calculate additional metadata about the
|
||||
// timestamps received from an NTP server. The timestamps returned by
|
||||
// the server are given the following variable names:
|
||||
//
|
||||
// org = Origin Timestamp (client send time)
|
||||
// rec = Receive Timestamp (server receive time)
|
||||
// xmt = Transmit Timestamp (server reply time)
|
||||
// dst = Destination Timestamp (client receive time)
|
||||
|
||||
func rtt(org, rec, xmt, dst ntpTime) time.Duration {
|
||||
// round trip delay time
|
||||
// rtt = (dst-org) - (xmt-rec)
|
||||
a := dst.Time().Sub(org.Time())
|
||||
b := xmt.Time().Sub(rec.Time())
|
||||
rtt := a - b
|
||||
if rtt < 0 {
|
||||
rtt = 0
|
||||
}
|
||||
return rtt
|
||||
}
|
||||
|
||||
func offset(org, rec, xmt, dst ntpTime) time.Duration {
|
||||
// local clock offset
|
||||
// offset = ((rec-org) + (xmt-dst)) / 2
|
||||
a := rec.Time().Sub(org.Time())
|
||||
b := xmt.Time().Sub(dst.Time())
|
||||
return (a + b) / time.Duration(2)
|
||||
}
|
||||
|
||||
func minError(org, rec, xmt, dst ntpTime) time.Duration {
|
||||
// Each NTP response contains two pairs of send/receive timestamps.
|
||||
// When either pair indicates a "causality violation", we calculate the
|
||||
// error as the difference in time between them. The minimum error is
|
||||
// the greater of the two causality violations.
|
||||
var error0, error1 ntpTime
|
||||
if org >= rec {
|
||||
error0 = org - rec
|
||||
}
|
||||
if xmt >= dst {
|
||||
error1 = xmt - dst
|
||||
}
|
||||
if error0 > error1 {
|
||||
return error0.Duration()
|
||||
}
|
||||
return error1.Duration()
|
||||
}
|
||||
|
||||
func rootDistance(rtt, rootDelay, rootDisp time.Duration) time.Duration {
|
||||
// The root distance is:
|
||||
// the maximum error due to all causes of the local clock
|
||||
// relative to the primary server. It is defined as half the
|
||||
// total delay plus total dispersion plus peer jitter.
|
||||
// (https://tools.ietf.org/html/rfc5905#appendix-A.5.5.2)
|
||||
//
|
||||
// In the reference implementation, it is calculated as follows:
|
||||
// rootDist = max(MINDISP, rootDelay + rtt)/2 + rootDisp
|
||||
// + peerDisp + PHI * (uptime - peerUptime)
|
||||
// + peerJitter
|
||||
// For an SNTP client which sends only a single packet, most of these
|
||||
// terms are irrelevant and become 0.
|
||||
totalDelay := rtt + rootDelay
|
||||
return totalDelay/2 + rootDisp
|
||||
}
|
||||
|
||||
func toInterval(t int8) time.Duration {
|
||||
switch {
|
||||
case t > 0:
|
||||
return time.Duration(uint64(time.Second) << uint(t))
|
||||
case t < 0:
|
||||
return time.Duration(uint64(time.Second) >> uint(-t))
|
||||
default:
|
||||
return time.Second
|
||||
}
|
||||
}
|
||||
|
||||
func kissCode(id uint32) string {
|
||||
isPrintable := func(ch byte) bool { return ch >= 32 && ch <= 126 }
|
||||
|
||||
b := []byte{
|
||||
byte(id >> 24),
|
||||
byte(id >> 16),
|
||||
byte(id >> 8),
|
||||
byte(id),
|
||||
}
|
||||
for _, ch := range b {
|
||||
if !isPrintable(ch) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
|
@ -285,7 +285,7 @@ func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (hexutil.
|
|||
}
|
||||
|
||||
var result []byte
|
||||
env, err := whisperMsg.Wrap(params)
|
||||
env, err := whisperMsg.Wrap(params, api.w.GetCurrentTime())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
@ -62,9 +62,9 @@ func (e *Envelope) rlpWithoutNonce() []byte {
|
|||
|
||||
// NewEnvelope wraps a Whisper message with expiration and destination data
|
||||
// included into an envelope for network forwarding.
|
||||
func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage) *Envelope {
|
||||
func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage, now time.Time) *Envelope {
|
||||
env := Envelope{
|
||||
Expiry: uint32(time.Now().Add(time.Second * time.Duration(ttl)).Unix()),
|
||||
Expiry: uint32(now.Add(time.Second * time.Duration(ttl)).Unix()),
|
||||
TTL: ttl,
|
||||
Topic: topic,
|
||||
Data: msg.Raw,
|
||||
|
|
|
@ -27,6 +27,7 @@ import (
|
|||
"errors"
|
||||
mrand "math/rand"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
|
@ -234,7 +235,7 @@ func generateSecureRandomData(length int) ([]byte, error) {
|
|||
}
|
||||
|
||||
// Wrap bundles the message into an Envelope to transmit over the network.
|
||||
func (msg *sentMessage) Wrap(options *MessageParams) (envelope *Envelope, err error) {
|
||||
func (msg *sentMessage) Wrap(options *MessageParams, now time.Time) (envelope *Envelope, err error) {
|
||||
if options.TTL == 0 {
|
||||
options.TTL = DefaultTTL
|
||||
}
|
||||
|
@ -254,7 +255,7 @@ func (msg *sentMessage) Wrap(options *MessageParams) (envelope *Envelope, err er
|
|||
return nil, err
|
||||
}
|
||||
|
||||
envelope = NewEnvelope(options.TTL, options.Topic, msg)
|
||||
envelope = NewEnvelope(options.TTL, options.Topic, msg, now)
|
||||
if err = envelope.Seal(options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
@ -92,6 +92,8 @@ type Whisper struct {
|
|||
envelopeTracer EnvelopeTracer // Service collecting envelopes metadata
|
||||
|
||||
envelopeFeed event.Feed
|
||||
|
||||
timeSource func() time.Time // source of time for whisper
|
||||
}
|
||||
|
||||
// New creates a Whisper client ready to communicate through the Ethereum P2P network.
|
||||
|
@ -110,6 +112,7 @@ func New(cfg *Config) *Whisper {
|
|||
p2pMsgQueue: make(chan *Envelope, messageQueueLimit),
|
||||
quit: make(chan struct{}),
|
||||
syncAllowance: DefaultSyncAllowance,
|
||||
timeSource: time.Now,
|
||||
}
|
||||
|
||||
whisper.filters = NewFilters(whisper)
|
||||
|
@ -215,6 +218,16 @@ func (whisper *Whisper) APIs() []rpc.API {
|
|||
}
|
||||
}
|
||||
|
||||
// SetTimeSource sets time source used by whisper for envelopes time and expiration logic.
|
||||
func (whisper *Whisper) SetTimeSource(timeSource func() time.Time) {
|
||||
whisper.timeSource = timeSource
|
||||
}
|
||||
|
||||
// GetCurrentTime returns current time.
|
||||
func (whisper *Whisper) GetCurrentTime() time.Time {
|
||||
return whisper.timeSource()
|
||||
}
|
||||
|
||||
// RegisterServer registers MailServer interface.
|
||||
// MailServer will process all the incoming messages with p2pRequestCode.
|
||||
func (whisper *Whisper) RegisterServer(server MailServer) {
|
||||
|
@ -829,7 +842,7 @@ func (whisper *Whisper) runMessageLoop(p *Peer, rw p2p.MsgReadWriter) error {
|
|||
// appropriate time-stamp. In case of error, connection should be dropped.
|
||||
// param isP2P indicates whether the message is peer-to-peer (should not be forwarded).
|
||||
func (whisper *Whisper) add(envelope *Envelope, isP2P bool) (bool, error) {
|
||||
now := uint32(time.Now().Unix())
|
||||
now := uint32(whisper.timeSource().Unix())
|
||||
sent := envelope.Expiry - envelope.TTL
|
||||
|
||||
if sent > now {
|
||||
|
@ -988,7 +1001,7 @@ func (whisper *Whisper) expire() {
|
|||
whisper.statsMu.Lock()
|
||||
defer whisper.statsMu.Unlock()
|
||||
whisper.stats.reset()
|
||||
now := uint32(time.Now().Unix())
|
||||
now := uint32(whisper.timeSource().Unix())
|
||||
for expiry, hashSet := range whisper.expirations {
|
||||
if expiry < now {
|
||||
// Dump all expired messages and remove timestamp
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package bpf
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Assemble converts insts into raw instructions suitable for loading
|
||||
// into a BPF virtual machine.
|
||||
//
|
||||
// Currently, no optimization is attempted, the assembled program flow
|
||||
// is exactly as provided.
|
||||
func Assemble(insts []Instruction) ([]RawInstruction, error) {
|
||||
ret := make([]RawInstruction, len(insts))
|
||||
var err error
|
||||
for i, inst := range insts {
|
||||
ret[i], err = inst.Assemble()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("assembling instruction %d: %s", i+1, err)
|
||||
}
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
// Disassemble attempts to parse raw back into
|
||||
// Instructions. Unrecognized RawInstructions are assumed to be an
|
||||
// extension not implemented by this package, and are passed through
|
||||
// unchanged to the output. The allDecoded value reports whether insts
|
||||
// contains no RawInstructions.
|
||||
func Disassemble(raw []RawInstruction) (insts []Instruction, allDecoded bool) {
|
||||
insts = make([]Instruction, len(raw))
|
||||
allDecoded = true
|
||||
for i, r := range raw {
|
||||
insts[i] = r.Disassemble()
|
||||
if _, ok := insts[i].(RawInstruction); ok {
|
||||
allDecoded = false
|
||||
}
|
||||
}
|
||||
return insts, allDecoded
|
||||
}
|
|
@ -0,0 +1,218 @@
|
|||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package bpf
|
||||
|
||||
// A Register is a register of the BPF virtual machine.
|
||||
type Register uint16
|
||||
|
||||
const (
|
||||
// RegA is the accumulator register. RegA is always the
|
||||
// destination register of ALU operations.
|
||||
RegA Register = iota
|
||||
// RegX is the indirection register, used by LoadIndirect
|
||||
// operations.
|
||||
RegX
|
||||
)
|
||||
|
||||
// An ALUOp is an arithmetic or logic operation.
|
||||
type ALUOp uint16
|
||||
|
||||
// ALU binary operation types.
|
||||
const (
|
||||
ALUOpAdd ALUOp = iota << 4
|
||||
ALUOpSub
|
||||
ALUOpMul
|
||||
ALUOpDiv
|
||||
ALUOpOr
|
||||
ALUOpAnd
|
||||
ALUOpShiftLeft
|
||||
ALUOpShiftRight
|
||||
aluOpNeg // Not exported because it's the only unary ALU operation, and gets its own instruction type.
|
||||
ALUOpMod
|
||||
ALUOpXor
|
||||
)
|
||||
|
||||
// A JumpTest is a comparison operator used in conditional jumps.
|
||||
type JumpTest uint16
|
||||
|
||||
// Supported operators for conditional jumps.
|
||||
const (
|
||||
// K == A
|
||||
JumpEqual JumpTest = iota
|
||||
// K != A
|
||||
JumpNotEqual
|
||||
// K > A
|
||||
JumpGreaterThan
|
||||
// K < A
|
||||
JumpLessThan
|
||||
// K >= A
|
||||
JumpGreaterOrEqual
|
||||
// K <= A
|
||||
JumpLessOrEqual
|
||||
// K & A != 0
|
||||
JumpBitsSet
|
||||
// K & A == 0
|
||||
JumpBitsNotSet
|
||||
)
|
||||
|
||||
// An Extension is a function call provided by the kernel that
|
||||
// performs advanced operations that are expensive or impossible
|
||||
// within the BPF virtual machine.
|
||||
//
|
||||
// Extensions are only implemented by the Linux kernel.
|
||||
//
|
||||
// TODO: should we prune this list? Some of these extensions seem
|
||||
// either broken or near-impossible to use correctly, whereas other
|
||||
// (len, random, ifindex) are quite useful.
|
||||
type Extension int
|
||||
|
||||
// Extension functions available in the Linux kernel.
|
||||
const (
|
||||
// extOffset is the negative maximum number of instructions used
|
||||
// to load instructions by overloading the K argument.
|
||||
extOffset = -0x1000
|
||||
// ExtLen returns the length of the packet.
|
||||
ExtLen Extension = 1
|
||||
// ExtProto returns the packet's L3 protocol type.
|
||||
ExtProto Extension = 0
|
||||
// ExtType returns the packet's type (skb->pkt_type in the kernel)
|
||||
//
|
||||
// TODO: better documentation. How nice an API do we want to
|
||||
// provide for these esoteric extensions?
|
||||
ExtType Extension = 4
|
||||
// ExtPayloadOffset returns the offset of the packet payload, or
|
||||
// the first protocol header that the kernel does not know how to
|
||||
// parse.
|
||||
ExtPayloadOffset Extension = 52
|
||||
// ExtInterfaceIndex returns the index of the interface on which
|
||||
// the packet was received.
|
||||
ExtInterfaceIndex Extension = 8
|
||||
// ExtNetlinkAttr returns the netlink attribute of type X at
|
||||
// offset A.
|
||||
ExtNetlinkAttr Extension = 12
|
||||
// ExtNetlinkAttrNested returns the nested netlink attribute of
|
||||
// type X at offset A.
|
||||
ExtNetlinkAttrNested Extension = 16
|
||||
// ExtMark returns the packet's mark value.
|
||||
ExtMark Extension = 20
|
||||
// ExtQueue returns the packet's assigned hardware queue.
|
||||
ExtQueue Extension = 24
|
||||
// ExtLinkLayerType returns the packet's hardware address type
|
||||
// (e.g. Ethernet, Infiniband).
|
||||
ExtLinkLayerType Extension = 28
|
||||
// ExtRXHash returns the packets receive hash.
|
||||
//
|
||||
// TODO: figure out what this rxhash actually is.
|
||||
ExtRXHash Extension = 32
|
||||
// ExtCPUID returns the ID of the CPU processing the current
|
||||
// packet.
|
||||
ExtCPUID Extension = 36
|
||||
// ExtVLANTag returns the packet's VLAN tag.
|
||||
ExtVLANTag Extension = 44
|
||||
// ExtVLANTagPresent returns non-zero if the packet has a VLAN
|
||||
// tag.
|
||||
//
|
||||
// TODO: I think this might be a lie: it reads bit 0x1000 of the
|
||||
// VLAN header, which changed meaning in recent revisions of the
|
||||
// spec - this extension may now return meaningless information.
|
||||
ExtVLANTagPresent Extension = 48
|
||||
// ExtVLANProto returns 0x8100 if the frame has a VLAN header,
|
||||
// 0x88a8 if the frame has a "Q-in-Q" double VLAN header, or some
|
||||
// other value if no VLAN information is present.
|
||||
ExtVLANProto Extension = 60
|
||||
// ExtRand returns a uniformly random uint32.
|
||||
ExtRand Extension = 56
|
||||
)
|
||||
|
||||
// The following gives names to various bit patterns used in opcode construction.
|
||||
|
||||
const (
|
||||
opMaskCls uint16 = 0x7
|
||||
// opClsLoad masks
|
||||
opMaskLoadDest = 0x01
|
||||
opMaskLoadWidth = 0x18
|
||||
opMaskLoadMode = 0xe0
|
||||
// opClsALU
|
||||
opMaskOperandSrc = 0x08
|
||||
opMaskOperator = 0xf0
|
||||
// opClsJump
|
||||
opMaskJumpConst = 0x0f
|
||||
opMaskJumpCond = 0xf0
|
||||
)
|
||||
|
||||
const (
|
||||
// +---------------+-----------------+---+---+---+
|
||||
// | AddrMode (3b) | LoadWidth (2b) | 0 | 0 | 0 |
|
||||
// +---------------+-----------------+---+---+---+
|
||||
opClsLoadA uint16 = iota
|
||||
// +---------------+-----------------+---+---+---+
|
||||
// | AddrMode (3b) | LoadWidth (2b) | 0 | 0 | 1 |
|
||||
// +---------------+-----------------+---+---+---+
|
||||
opClsLoadX
|
||||
// +---+---+---+---+---+---+---+---+
|
||||
// | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
|
||||
// +---+---+---+---+---+---+---+---+
|
||||
opClsStoreA
|
||||
// +---+---+---+---+---+---+---+---+
|
||||
// | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
|
||||
// +---+---+---+---+---+---+---+---+
|
||||
opClsStoreX
|
||||
// +---------------+-----------------+---+---+---+
|
||||
// | Operator (4b) | OperandSrc (1b) | 1 | 0 | 0 |
|
||||
// +---------------+-----------------+---+---+---+
|
||||
opClsALU
|
||||
// +-----------------------------+---+---+---+---+
|
||||
// | TestOperator (4b) | 0 | 1 | 0 | 1 |
|
||||
// +-----------------------------+---+---+---+---+
|
||||
opClsJump
|
||||
// +---+-------------------------+---+---+---+---+
|
||||
// | 0 | 0 | 0 | RetSrc (1b) | 0 | 1 | 1 | 0 |
|
||||
// +---+-------------------------+---+---+---+---+
|
||||
opClsReturn
|
||||
// +---+-------------------------+---+---+---+---+
|
||||
// | 0 | 0 | 0 | TXAorTAX (1b) | 0 | 1 | 1 | 1 |
|
||||
// +---+-------------------------+---+---+---+---+
|
||||
opClsMisc
|
||||
)
|
||||
|
||||
const (
|
||||
opAddrModeImmediate uint16 = iota << 5
|
||||
opAddrModeAbsolute
|
||||
opAddrModeIndirect
|
||||
opAddrModeScratch
|
||||
opAddrModePacketLen // actually an extension, not an addressing mode.
|
||||
opAddrModeMemShift
|
||||
)
|
||||
|
||||
const (
|
||||
opLoadWidth4 uint16 = iota << 3
|
||||
opLoadWidth2
|
||||
opLoadWidth1
|
||||
)
|
||||
|
||||
// Operator defined by ALUOp*
|
||||
|
||||
const (
|
||||
opALUSrcConstant uint16 = iota << 3
|
||||
opALUSrcX
|
||||
)
|
||||
|
||||
const (
|
||||
opJumpAlways = iota << 4
|
||||
opJumpEqual
|
||||
opJumpGT
|
||||
opJumpGE
|
||||
opJumpSet
|
||||
)
|
||||
|
||||
const (
|
||||
opRetSrcConstant uint16 = iota << 4
|
||||
opRetSrcA
|
||||
)
|
||||
|
||||
const (
|
||||
opMiscTAX = 0x00
|
||||
opMiscTXA = 0x80
|
||||
)
|
|
@ -0,0 +1,82 @@
|
|||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
/*
|
||||
|
||||
Package bpf implements marshaling and unmarshaling of programs for the
|
||||
Berkeley Packet Filter virtual machine, and provides a Go implementation
|
||||
of the virtual machine.
|
||||
|
||||
BPF's main use is to specify a packet filter for network taps, so that
|
||||
the kernel doesn't have to expensively copy every packet it sees to
|
||||
userspace. However, it's been repurposed to other areas where running
|
||||
user code in-kernel is needed. For example, Linux's seccomp uses BPF
|
||||
to apply security policies to system calls. For simplicity, this
|
||||
documentation refers only to packets, but other uses of BPF have their
|
||||
own data payloads.
|
||||
|
||||
BPF programs run in a restricted virtual machine. It has almost no
|
||||
access to kernel functions, and while conditional branches are
|
||||
allowed, they can only jump forwards, to guarantee that there are no
|
||||
infinite loops.
|
||||
|
||||
The virtual machine
|
||||
|
||||
The BPF VM is an accumulator machine. Its main register, called
|
||||
register A, is an implicit source and destination in all arithmetic
|
||||
and logic operations. The machine also has 16 scratch registers for
|
||||
temporary storage, and an indirection register (register X) for
|
||||
indirect memory access. All registers are 32 bits wide.
|
||||
|
||||
Each run of a BPF program is given one packet, which is placed in the
|
||||
VM's read-only "main memory". LoadAbsolute and LoadIndirect
|
||||
instructions can fetch up to 32 bits at a time into register A for
|
||||
examination.
|
||||
|
||||
The goal of a BPF program is to produce and return a verdict (uint32),
|
||||
which tells the kernel what to do with the packet. In the context of
|
||||
packet filtering, the returned value is the number of bytes of the
|
||||
packet to forward to userspace, or 0 to ignore the packet. Other
|
||||
contexts like seccomp define their own return values.
|
||||
|
||||
In order to simplify programs, attempts to read past the end of the
|
||||
packet terminate the program execution with a verdict of 0 (ignore
|
||||
packet). This means that the vast majority of BPF programs don't need
|
||||
to do any explicit bounds checking.
|
||||
|
||||
In addition to the bytes of the packet, some BPF programs have access
|
||||
to extensions, which are essentially calls to kernel utility
|
||||
functions. Currently, the only extensions supported by this package
|
||||
are the Linux packet filter extensions.
|
||||
|
||||
Examples
|
||||
|
||||
This packet filter selects all ARP packets.
|
||||
|
||||
bpf.Assemble([]bpf.Instruction{
|
||||
// Load "EtherType" field from the ethernet header.
|
||||
bpf.LoadAbsolute{Off: 12, Size: 2},
|
||||
// Skip over the next instruction if EtherType is not ARP.
|
||||
bpf.JumpIf{Cond: bpf.JumpNotEqual, Val: 0x0806, SkipTrue: 1},
|
||||
// Verdict is "send up to 4k of the packet to userspace."
|
||||
bpf.RetConstant{Val: 4096},
|
||||
// Verdict is "ignore packet."
|
||||
bpf.RetConstant{Val: 0},
|
||||
})
|
||||
|
||||
This packet filter captures a random 1% sample of traffic.
|
||||
|
||||
bpf.Assemble([]bpf.Instruction{
|
||||
// Get a 32-bit random number from the Linux kernel.
|
||||
bpf.LoadExtension{Num: bpf.ExtRand},
|
||||
// 1% dice roll?
|
||||
bpf.JumpIf{Cond: bpf.JumpLessThan, Val: 2^32/100, SkipFalse: 1},
|
||||
// Capture.
|
||||
bpf.RetConstant{Val: 4096},
|
||||
// Ignore.
|
||||
bpf.RetConstant{Val: 0},
|
||||
})
|
||||
|
||||
*/
|
||||
package bpf // import "golang.org/x/net/bpf"
|
|
@ -0,0 +1,704 @@
|
|||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package bpf
|
||||
|
||||
import "fmt"
|
||||
|
||||
// An Instruction is one instruction executed by the BPF virtual
|
||||
// machine.
|
||||
type Instruction interface {
|
||||
// Assemble assembles the Instruction into a RawInstruction.
|
||||
Assemble() (RawInstruction, error)
|
||||
}
|
||||
|
||||
// A RawInstruction is a raw BPF virtual machine instruction.
|
||||
type RawInstruction struct {
|
||||
// Operation to execute.
|
||||
Op uint16
|
||||
// For conditional jump instructions, the number of instructions
|
||||
// to skip if the condition is true/false.
|
||||
Jt uint8
|
||||
Jf uint8
|
||||
// Constant parameter. The meaning depends on the Op.
|
||||
K uint32
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (ri RawInstruction) Assemble() (RawInstruction, error) { return ri, nil }
|
||||
|
||||
// Disassemble parses ri into an Instruction and returns it. If ri is
|
||||
// not recognized by this package, ri itself is returned.
|
||||
func (ri RawInstruction) Disassemble() Instruction {
|
||||
switch ri.Op & opMaskCls {
|
||||
case opClsLoadA, opClsLoadX:
|
||||
reg := Register(ri.Op & opMaskLoadDest)
|
||||
sz := 0
|
||||
switch ri.Op & opMaskLoadWidth {
|
||||
case opLoadWidth4:
|
||||
sz = 4
|
||||
case opLoadWidth2:
|
||||
sz = 2
|
||||
case opLoadWidth1:
|
||||
sz = 1
|
||||
default:
|
||||
return ri
|
||||
}
|
||||
switch ri.Op & opMaskLoadMode {
|
||||
case opAddrModeImmediate:
|
||||
if sz != 4 {
|
||||
return ri
|
||||
}
|
||||
return LoadConstant{Dst: reg, Val: ri.K}
|
||||
case opAddrModeScratch:
|
||||
if sz != 4 || ri.K > 15 {
|
||||
return ri
|
||||
}
|
||||
return LoadScratch{Dst: reg, N: int(ri.K)}
|
||||
case opAddrModeAbsolute:
|
||||
if ri.K > extOffset+0xffffffff {
|
||||
return LoadExtension{Num: Extension(-extOffset + ri.K)}
|
||||
}
|
||||
return LoadAbsolute{Size: sz, Off: ri.K}
|
||||
case opAddrModeIndirect:
|
||||
return LoadIndirect{Size: sz, Off: ri.K}
|
||||
case opAddrModePacketLen:
|
||||
if sz != 4 {
|
||||
return ri
|
||||
}
|
||||
return LoadExtension{Num: ExtLen}
|
||||
case opAddrModeMemShift:
|
||||
return LoadMemShift{Off: ri.K}
|
||||
default:
|
||||
return ri
|
||||
}
|
||||
|
||||
case opClsStoreA:
|
||||
if ri.Op != opClsStoreA || ri.K > 15 {
|
||||
return ri
|
||||
}
|
||||
return StoreScratch{Src: RegA, N: int(ri.K)}
|
||||
|
||||
case opClsStoreX:
|
||||
if ri.Op != opClsStoreX || ri.K > 15 {
|
||||
return ri
|
||||
}
|
||||
return StoreScratch{Src: RegX, N: int(ri.K)}
|
||||
|
||||
case opClsALU:
|
||||
switch op := ALUOp(ri.Op & opMaskOperator); op {
|
||||
case ALUOpAdd, ALUOpSub, ALUOpMul, ALUOpDiv, ALUOpOr, ALUOpAnd, ALUOpShiftLeft, ALUOpShiftRight, ALUOpMod, ALUOpXor:
|
||||
if ri.Op&opMaskOperandSrc != 0 {
|
||||
return ALUOpX{Op: op}
|
||||
}
|
||||
return ALUOpConstant{Op: op, Val: ri.K}
|
||||
case aluOpNeg:
|
||||
return NegateA{}
|
||||
default:
|
||||
return ri
|
||||
}
|
||||
|
||||
case opClsJump:
|
||||
if ri.Op&opMaskJumpConst != opClsJump {
|
||||
return ri
|
||||
}
|
||||
switch ri.Op & opMaskJumpCond {
|
||||
case opJumpAlways:
|
||||
return Jump{Skip: ri.K}
|
||||
case opJumpEqual:
|
||||
if ri.Jt == 0 {
|
||||
return JumpIf{
|
||||
Cond: JumpNotEqual,
|
||||
Val: ri.K,
|
||||
SkipTrue: ri.Jf,
|
||||
SkipFalse: 0,
|
||||
}
|
||||
}
|
||||
return JumpIf{
|
||||
Cond: JumpEqual,
|
||||
Val: ri.K,
|
||||
SkipTrue: ri.Jt,
|
||||
SkipFalse: ri.Jf,
|
||||
}
|
||||
case opJumpGT:
|
||||
if ri.Jt == 0 {
|
||||
return JumpIf{
|
||||
Cond: JumpLessOrEqual,
|
||||
Val: ri.K,
|
||||
SkipTrue: ri.Jf,
|
||||
SkipFalse: 0,
|
||||
}
|
||||
}
|
||||
return JumpIf{
|
||||
Cond: JumpGreaterThan,
|
||||
Val: ri.K,
|
||||
SkipTrue: ri.Jt,
|
||||
SkipFalse: ri.Jf,
|
||||
}
|
||||
case opJumpGE:
|
||||
if ri.Jt == 0 {
|
||||
return JumpIf{
|
||||
Cond: JumpLessThan,
|
||||
Val: ri.K,
|
||||
SkipTrue: ri.Jf,
|
||||
SkipFalse: 0,
|
||||
}
|
||||
}
|
||||
return JumpIf{
|
||||
Cond: JumpGreaterOrEqual,
|
||||
Val: ri.K,
|
||||
SkipTrue: ri.Jt,
|
||||
SkipFalse: ri.Jf,
|
||||
}
|
||||
case opJumpSet:
|
||||
return JumpIf{
|
||||
Cond: JumpBitsSet,
|
||||
Val: ri.K,
|
||||
SkipTrue: ri.Jt,
|
||||
SkipFalse: ri.Jf,
|
||||
}
|
||||
default:
|
||||
return ri
|
||||
}
|
||||
|
||||
case opClsReturn:
|
||||
switch ri.Op {
|
||||
case opClsReturn | opRetSrcA:
|
||||
return RetA{}
|
||||
case opClsReturn | opRetSrcConstant:
|
||||
return RetConstant{Val: ri.K}
|
||||
default:
|
||||
return ri
|
||||
}
|
||||
|
||||
case opClsMisc:
|
||||
switch ri.Op {
|
||||
case opClsMisc | opMiscTAX:
|
||||
return TAX{}
|
||||
case opClsMisc | opMiscTXA:
|
||||
return TXA{}
|
||||
default:
|
||||
return ri
|
||||
}
|
||||
|
||||
default:
|
||||
panic("unreachable") // switch is exhaustive on the bit pattern
|
||||
}
|
||||
}
|
||||
|
||||
// LoadConstant loads Val into register Dst.
|
||||
type LoadConstant struct {
|
||||
Dst Register
|
||||
Val uint32
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a LoadConstant) Assemble() (RawInstruction, error) {
|
||||
return assembleLoad(a.Dst, 4, opAddrModeImmediate, a.Val)
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a LoadConstant) String() string {
|
||||
switch a.Dst {
|
||||
case RegA:
|
||||
return fmt.Sprintf("ld #%d", a.Val)
|
||||
case RegX:
|
||||
return fmt.Sprintf("ldx #%d", a.Val)
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// LoadScratch loads scratch[N] into register Dst.
|
||||
type LoadScratch struct {
|
||||
Dst Register
|
||||
N int // 0-15
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a LoadScratch) Assemble() (RawInstruction, error) {
|
||||
if a.N < 0 || a.N > 15 {
|
||||
return RawInstruction{}, fmt.Errorf("invalid scratch slot %d", a.N)
|
||||
}
|
||||
return assembleLoad(a.Dst, 4, opAddrModeScratch, uint32(a.N))
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a LoadScratch) String() string {
|
||||
switch a.Dst {
|
||||
case RegA:
|
||||
return fmt.Sprintf("ld M[%d]", a.N)
|
||||
case RegX:
|
||||
return fmt.Sprintf("ldx M[%d]", a.N)
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// LoadAbsolute loads packet[Off:Off+Size] as an integer value into
|
||||
// register A.
|
||||
type LoadAbsolute struct {
|
||||
Off uint32
|
||||
Size int // 1, 2 or 4
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a LoadAbsolute) Assemble() (RawInstruction, error) {
|
||||
return assembleLoad(RegA, a.Size, opAddrModeAbsolute, a.Off)
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a LoadAbsolute) String() string {
|
||||
switch a.Size {
|
||||
case 1: // byte
|
||||
return fmt.Sprintf("ldb [%d]", a.Off)
|
||||
case 2: // half word
|
||||
return fmt.Sprintf("ldh [%d]", a.Off)
|
||||
case 4: // word
|
||||
if a.Off > extOffset+0xffffffff {
|
||||
return LoadExtension{Num: Extension(a.Off + 0x1000)}.String()
|
||||
}
|
||||
return fmt.Sprintf("ld [%d]", a.Off)
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// LoadIndirect loads packet[X+Off:X+Off+Size] as an integer value
|
||||
// into register A.
|
||||
type LoadIndirect struct {
|
||||
Off uint32
|
||||
Size int // 1, 2 or 4
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a LoadIndirect) Assemble() (RawInstruction, error) {
|
||||
return assembleLoad(RegA, a.Size, opAddrModeIndirect, a.Off)
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a LoadIndirect) String() string {
|
||||
switch a.Size {
|
||||
case 1: // byte
|
||||
return fmt.Sprintf("ldb [x + %d]", a.Off)
|
||||
case 2: // half word
|
||||
return fmt.Sprintf("ldh [x + %d]", a.Off)
|
||||
case 4: // word
|
||||
return fmt.Sprintf("ld [x + %d]", a.Off)
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// LoadMemShift multiplies the first 4 bits of the byte at packet[Off]
|
||||
// by 4 and stores the result in register X.
|
||||
//
|
||||
// This instruction is mainly useful to load into X the length of an
|
||||
// IPv4 packet header in a single instruction, rather than have to do
|
||||
// the arithmetic on the header's first byte by hand.
|
||||
type LoadMemShift struct {
|
||||
Off uint32
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a LoadMemShift) Assemble() (RawInstruction, error) {
|
||||
return assembleLoad(RegX, 1, opAddrModeMemShift, a.Off)
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a LoadMemShift) String() string {
|
||||
return fmt.Sprintf("ldx 4*([%d]&0xf)", a.Off)
|
||||
}
|
||||
|
||||
// LoadExtension invokes a linux-specific extension and stores the
|
||||
// result in register A.
|
||||
type LoadExtension struct {
|
||||
Num Extension
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a LoadExtension) Assemble() (RawInstruction, error) {
|
||||
if a.Num == ExtLen {
|
||||
return assembleLoad(RegA, 4, opAddrModePacketLen, 0)
|
||||
}
|
||||
return assembleLoad(RegA, 4, opAddrModeAbsolute, uint32(extOffset+a.Num))
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a LoadExtension) String() string {
|
||||
switch a.Num {
|
||||
case ExtLen:
|
||||
return "ld #len"
|
||||
case ExtProto:
|
||||
return "ld #proto"
|
||||
case ExtType:
|
||||
return "ld #type"
|
||||
case ExtPayloadOffset:
|
||||
return "ld #poff"
|
||||
case ExtInterfaceIndex:
|
||||
return "ld #ifidx"
|
||||
case ExtNetlinkAttr:
|
||||
return "ld #nla"
|
||||
case ExtNetlinkAttrNested:
|
||||
return "ld #nlan"
|
||||
case ExtMark:
|
||||
return "ld #mark"
|
||||
case ExtQueue:
|
||||
return "ld #queue"
|
||||
case ExtLinkLayerType:
|
||||
return "ld #hatype"
|
||||
case ExtRXHash:
|
||||
return "ld #rxhash"
|
||||
case ExtCPUID:
|
||||
return "ld #cpu"
|
||||
case ExtVLANTag:
|
||||
return "ld #vlan_tci"
|
||||
case ExtVLANTagPresent:
|
||||
return "ld #vlan_avail"
|
||||
case ExtVLANProto:
|
||||
return "ld #vlan_tpid"
|
||||
case ExtRand:
|
||||
return "ld #rand"
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// StoreScratch stores register Src into scratch[N].
|
||||
type StoreScratch struct {
|
||||
Src Register
|
||||
N int // 0-15
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a StoreScratch) Assemble() (RawInstruction, error) {
|
||||
if a.N < 0 || a.N > 15 {
|
||||
return RawInstruction{}, fmt.Errorf("invalid scratch slot %d", a.N)
|
||||
}
|
||||
var op uint16
|
||||
switch a.Src {
|
||||
case RegA:
|
||||
op = opClsStoreA
|
||||
case RegX:
|
||||
op = opClsStoreX
|
||||
default:
|
||||
return RawInstruction{}, fmt.Errorf("invalid source register %v", a.Src)
|
||||
}
|
||||
|
||||
return RawInstruction{
|
||||
Op: op,
|
||||
K: uint32(a.N),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a StoreScratch) String() string {
|
||||
switch a.Src {
|
||||
case RegA:
|
||||
return fmt.Sprintf("st M[%d]", a.N)
|
||||
case RegX:
|
||||
return fmt.Sprintf("stx M[%d]", a.N)
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// ALUOpConstant executes A = A <Op> Val.
|
||||
type ALUOpConstant struct {
|
||||
Op ALUOp
|
||||
Val uint32
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a ALUOpConstant) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsALU | opALUSrcConstant | uint16(a.Op),
|
||||
K: a.Val,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a ALUOpConstant) String() string {
|
||||
switch a.Op {
|
||||
case ALUOpAdd:
|
||||
return fmt.Sprintf("add #%d", a.Val)
|
||||
case ALUOpSub:
|
||||
return fmt.Sprintf("sub #%d", a.Val)
|
||||
case ALUOpMul:
|
||||
return fmt.Sprintf("mul #%d", a.Val)
|
||||
case ALUOpDiv:
|
||||
return fmt.Sprintf("div #%d", a.Val)
|
||||
case ALUOpMod:
|
||||
return fmt.Sprintf("mod #%d", a.Val)
|
||||
case ALUOpAnd:
|
||||
return fmt.Sprintf("and #%d", a.Val)
|
||||
case ALUOpOr:
|
||||
return fmt.Sprintf("or #%d", a.Val)
|
||||
case ALUOpXor:
|
||||
return fmt.Sprintf("xor #%d", a.Val)
|
||||
case ALUOpShiftLeft:
|
||||
return fmt.Sprintf("lsh #%d", a.Val)
|
||||
case ALUOpShiftRight:
|
||||
return fmt.Sprintf("rsh #%d", a.Val)
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// ALUOpX executes A = A <Op> X
|
||||
type ALUOpX struct {
|
||||
Op ALUOp
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a ALUOpX) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsALU | opALUSrcX | uint16(a.Op),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a ALUOpX) String() string {
|
||||
switch a.Op {
|
||||
case ALUOpAdd:
|
||||
return "add x"
|
||||
case ALUOpSub:
|
||||
return "sub x"
|
||||
case ALUOpMul:
|
||||
return "mul x"
|
||||
case ALUOpDiv:
|
||||
return "div x"
|
||||
case ALUOpMod:
|
||||
return "mod x"
|
||||
case ALUOpAnd:
|
||||
return "and x"
|
||||
case ALUOpOr:
|
||||
return "or x"
|
||||
case ALUOpXor:
|
||||
return "xor x"
|
||||
case ALUOpShiftLeft:
|
||||
return "lsh x"
|
||||
case ALUOpShiftRight:
|
||||
return "rsh x"
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// NegateA executes A = -A.
|
||||
type NegateA struct{}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a NegateA) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsALU | uint16(aluOpNeg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a NegateA) String() string {
|
||||
return fmt.Sprintf("neg")
|
||||
}
|
||||
|
||||
// Jump skips the following Skip instructions in the program.
|
||||
type Jump struct {
|
||||
Skip uint32
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a Jump) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsJump | opJumpAlways,
|
||||
K: a.Skip,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a Jump) String() string {
|
||||
return fmt.Sprintf("ja %d", a.Skip)
|
||||
}
|
||||
|
||||
// JumpIf skips the following Skip instructions in the program if A
|
||||
// <Cond> Val is true.
|
||||
type JumpIf struct {
|
||||
Cond JumpTest
|
||||
Val uint32
|
||||
SkipTrue uint8
|
||||
SkipFalse uint8
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a JumpIf) Assemble() (RawInstruction, error) {
|
||||
var (
|
||||
cond uint16
|
||||
flip bool
|
||||
)
|
||||
switch a.Cond {
|
||||
case JumpEqual:
|
||||
cond = opJumpEqual
|
||||
case JumpNotEqual:
|
||||
cond, flip = opJumpEqual, true
|
||||
case JumpGreaterThan:
|
||||
cond = opJumpGT
|
||||
case JumpLessThan:
|
||||
cond, flip = opJumpGE, true
|
||||
case JumpGreaterOrEqual:
|
||||
cond = opJumpGE
|
||||
case JumpLessOrEqual:
|
||||
cond, flip = opJumpGT, true
|
||||
case JumpBitsSet:
|
||||
cond = opJumpSet
|
||||
case JumpBitsNotSet:
|
||||
cond, flip = opJumpSet, true
|
||||
default:
|
||||
return RawInstruction{}, fmt.Errorf("unknown JumpTest %v", a.Cond)
|
||||
}
|
||||
jt, jf := a.SkipTrue, a.SkipFalse
|
||||
if flip {
|
||||
jt, jf = jf, jt
|
||||
}
|
||||
return RawInstruction{
|
||||
Op: opClsJump | cond,
|
||||
Jt: jt,
|
||||
Jf: jf,
|
||||
K: a.Val,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a JumpIf) String() string {
|
||||
switch a.Cond {
|
||||
// K == A
|
||||
case JumpEqual:
|
||||
return conditionalJump(a, "jeq", "jneq")
|
||||
// K != A
|
||||
case JumpNotEqual:
|
||||
return fmt.Sprintf("jneq #%d,%d", a.Val, a.SkipTrue)
|
||||
// K > A
|
||||
case JumpGreaterThan:
|
||||
return conditionalJump(a, "jgt", "jle")
|
||||
// K < A
|
||||
case JumpLessThan:
|
||||
return fmt.Sprintf("jlt #%d,%d", a.Val, a.SkipTrue)
|
||||
// K >= A
|
||||
case JumpGreaterOrEqual:
|
||||
return conditionalJump(a, "jge", "jlt")
|
||||
// K <= A
|
||||
case JumpLessOrEqual:
|
||||
return fmt.Sprintf("jle #%d,%d", a.Val, a.SkipTrue)
|
||||
// K & A != 0
|
||||
case JumpBitsSet:
|
||||
if a.SkipFalse > 0 {
|
||||
return fmt.Sprintf("jset #%d,%d,%d", a.Val, a.SkipTrue, a.SkipFalse)
|
||||
}
|
||||
return fmt.Sprintf("jset #%d,%d", a.Val, a.SkipTrue)
|
||||
// K & A == 0, there is no assembler instruction for JumpBitNotSet, use JumpBitSet and invert skips
|
||||
case JumpBitsNotSet:
|
||||
return JumpIf{Cond: JumpBitsSet, SkipTrue: a.SkipFalse, SkipFalse: a.SkipTrue, Val: a.Val}.String()
|
||||
default:
|
||||
return fmt.Sprintf("unknown instruction: %#v", a)
|
||||
}
|
||||
}
|
||||
|
||||
func conditionalJump(inst JumpIf, positiveJump, negativeJump string) string {
|
||||
if inst.SkipTrue > 0 {
|
||||
if inst.SkipFalse > 0 {
|
||||
return fmt.Sprintf("%s #%d,%d,%d", positiveJump, inst.Val, inst.SkipTrue, inst.SkipFalse)
|
||||
}
|
||||
return fmt.Sprintf("%s #%d,%d", positiveJump, inst.Val, inst.SkipTrue)
|
||||
}
|
||||
return fmt.Sprintf("%s #%d,%d", negativeJump, inst.Val, inst.SkipFalse)
|
||||
}
|
||||
|
||||
// RetA exits the BPF program, returning the value of register A.
|
||||
type RetA struct{}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a RetA) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsReturn | opRetSrcA,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a RetA) String() string {
|
||||
return fmt.Sprintf("ret a")
|
||||
}
|
||||
|
||||
// RetConstant exits the BPF program, returning a constant value.
|
||||
type RetConstant struct {
|
||||
Val uint32
|
||||
}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a RetConstant) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsReturn | opRetSrcConstant,
|
||||
K: a.Val,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a RetConstant) String() string {
|
||||
return fmt.Sprintf("ret #%d", a.Val)
|
||||
}
|
||||
|
||||
// TXA copies the value of register X to register A.
|
||||
type TXA struct{}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a TXA) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsMisc | opMiscTXA,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a TXA) String() string {
|
||||
return fmt.Sprintf("txa")
|
||||
}
|
||||
|
||||
// TAX copies the value of register A to register X.
|
||||
type TAX struct{}
|
||||
|
||||
// Assemble implements the Instruction Assemble method.
|
||||
func (a TAX) Assemble() (RawInstruction, error) {
|
||||
return RawInstruction{
|
||||
Op: opClsMisc | opMiscTAX,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns the the instruction in assembler notation.
|
||||
func (a TAX) String() string {
|
||||
return fmt.Sprintf("tax")
|
||||
}
|
||||
|
||||
func assembleLoad(dst Register, loadSize int, mode uint16, k uint32) (RawInstruction, error) {
|
||||
var (
|
||||
cls uint16
|
||||
sz uint16
|
||||
)
|
||||
switch dst {
|
||||
case RegA:
|
||||
cls = opClsLoadA
|
||||
case RegX:
|
||||
cls = opClsLoadX
|
||||
default:
|
||||
return RawInstruction{}, fmt.Errorf("invalid target register %v", dst)
|
||||
}
|
||||
switch loadSize {
|
||||
case 1:
|
||||
sz = opLoadWidth1
|
||||
case 2:
|
||||
sz = opLoadWidth2
|
||||
case 4:
|
||||
sz = opLoadWidth4
|
||||
default:
|
||||
return RawInstruction{}, fmt.Errorf("invalid load byte length %d", sz)
|
||||
}
|
||||
return RawInstruction{
|
||||
Op: cls | sz | mode,
|
||||
K: k,
|
||||
}, nil
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package bpf
|
||||
|
||||
// A Setter is a type which can attach a compiled BPF filter to itself.
|
||||
type Setter interface {
|
||||
SetBPF(filter []RawInstruction) error
|
||||
}
|
|
@ -0,0 +1,140 @@
|
|||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package bpf
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// A VM is an emulated BPF virtual machine.
|
||||
type VM struct {
|
||||
filter []Instruction
|
||||
}
|
||||
|
||||
// NewVM returns a new VM using the input BPF program.
|
||||
func NewVM(filter []Instruction) (*VM, error) {
|
||||
if len(filter) == 0 {
|
||||
return nil, errors.New("one or more Instructions must be specified")
|
||||
}
|
||||
|
||||
for i, ins := range filter {
|
||||
check := len(filter) - (i + 1)
|
||||
switch ins := ins.(type) {
|
||||
// Check for out-of-bounds jumps in instructions
|
||||
case Jump:
|
||||
if check <= int(ins.Skip) {
|
||||
return nil, fmt.Errorf("cannot jump %d instructions; jumping past program bounds", ins.Skip)
|
||||
}
|
||||
case JumpIf:
|
||||
if check <= int(ins.SkipTrue) {
|
||||
return nil, fmt.Errorf("cannot jump %d instructions in true case; jumping past program bounds", ins.SkipTrue)
|
||||
}
|
||||
if check <= int(ins.SkipFalse) {
|
||||
return nil, fmt.Errorf("cannot jump %d instructions in false case; jumping past program bounds", ins.SkipFalse)
|
||||
}
|
||||
// Check for division or modulus by zero
|
||||
case ALUOpConstant:
|
||||
if ins.Val != 0 {
|
||||
break
|
||||
}
|
||||
|
||||
switch ins.Op {
|
||||
case ALUOpDiv, ALUOpMod:
|
||||
return nil, errors.New("cannot divide by zero using ALUOpConstant")
|
||||
}
|
||||
// Check for unknown extensions
|
||||
case LoadExtension:
|
||||
switch ins.Num {
|
||||
case ExtLen:
|
||||
default:
|
||||
return nil, fmt.Errorf("extension %d not implemented", ins.Num)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure last instruction is a return instruction
|
||||
switch filter[len(filter)-1].(type) {
|
||||
case RetA, RetConstant:
|
||||
default:
|
||||
return nil, errors.New("BPF program must end with RetA or RetConstant")
|
||||
}
|
||||
|
||||
// Though our VM works using disassembled instructions, we
|
||||
// attempt to assemble the input filter anyway to ensure it is compatible
|
||||
// with an operating system VM.
|
||||
_, err := Assemble(filter)
|
||||
|
||||
return &VM{
|
||||
filter: filter,
|
||||
}, err
|
||||
}
|
||||
|
||||
// Run runs the VM's BPF program against the input bytes.
|
||||
// Run returns the number of bytes accepted by the BPF program, and any errors
|
||||
// which occurred while processing the program.
|
||||
func (v *VM) Run(in []byte) (int, error) {
|
||||
var (
|
||||
// Registers of the virtual machine
|
||||
regA uint32
|
||||
regX uint32
|
||||
regScratch [16]uint32
|
||||
|
||||
// OK is true if the program should continue processing the next
|
||||
// instruction, or false if not, causing the loop to break
|
||||
ok = true
|
||||
)
|
||||
|
||||
// TODO(mdlayher): implement:
|
||||
// - NegateA:
|
||||
// - would require a change from uint32 registers to int32
|
||||
// registers
|
||||
|
||||
// TODO(mdlayher): add interop tests that check signedness of ALU
|
||||
// operations against kernel implementation, and make sure Go
|
||||
// implementation matches behavior
|
||||
|
||||
for i := 0; i < len(v.filter) && ok; i++ {
|
||||
ins := v.filter[i]
|
||||
|
||||
switch ins := ins.(type) {
|
||||
case ALUOpConstant:
|
||||
regA = aluOpConstant(ins, regA)
|
||||
case ALUOpX:
|
||||
regA, ok = aluOpX(ins, regA, regX)
|
||||
case Jump:
|
||||
i += int(ins.Skip)
|
||||
case JumpIf:
|
||||
jump := jumpIf(ins, regA)
|
||||
i += jump
|
||||
case LoadAbsolute:
|
||||
regA, ok = loadAbsolute(ins, in)
|
||||
case LoadConstant:
|
||||
regA, regX = loadConstant(ins, regA, regX)
|
||||
case LoadExtension:
|
||||
regA = loadExtension(ins, in)
|
||||
case LoadIndirect:
|
||||
regA, ok = loadIndirect(ins, in, regX)
|
||||
case LoadMemShift:
|
||||
regX, ok = loadMemShift(ins, in)
|
||||
case LoadScratch:
|
||||
regA, regX = loadScratch(ins, regScratch, regA, regX)
|
||||
case RetA:
|
||||
return int(regA), nil
|
||||
case RetConstant:
|
||||
return int(ins.Val), nil
|
||||
case StoreScratch:
|
||||
regScratch = storeScratch(ins, regScratch, regA, regX)
|
||||
case TAX:
|
||||
regX = regA
|
||||
case TXA:
|
||||
regA = regX
|
||||
default:
|
||||
return 0, fmt.Errorf("unknown Instruction at index %d: %T", i, ins)
|
||||
}
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
|
@ -0,0 +1,174 @@
|
|||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package bpf
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func aluOpConstant(ins ALUOpConstant, regA uint32) uint32 {
|
||||
return aluOpCommon(ins.Op, regA, ins.Val)
|
||||
}
|
||||
|
||||
func aluOpX(ins ALUOpX, regA uint32, regX uint32) (uint32, bool) {
|
||||
// Guard against division or modulus by zero by terminating
|
||||
// the program, as the OS BPF VM does
|
||||
if regX == 0 {
|
||||
switch ins.Op {
|
||||
case ALUOpDiv, ALUOpMod:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
return aluOpCommon(ins.Op, regA, regX), true
|
||||
}
|
||||
|
||||
func aluOpCommon(op ALUOp, regA uint32, value uint32) uint32 {
|
||||
switch op {
|
||||
case ALUOpAdd:
|
||||
return regA + value
|
||||
case ALUOpSub:
|
||||
return regA - value
|
||||
case ALUOpMul:
|
||||
return regA * value
|
||||
case ALUOpDiv:
|
||||
// Division by zero not permitted by NewVM and aluOpX checks
|
||||
return regA / value
|
||||
case ALUOpOr:
|
||||
return regA | value
|
||||
case ALUOpAnd:
|
||||
return regA & value
|
||||
case ALUOpShiftLeft:
|
||||
return regA << value
|
||||
case ALUOpShiftRight:
|
||||
return regA >> value
|
||||
case ALUOpMod:
|
||||
// Modulus by zero not permitted by NewVM and aluOpX checks
|
||||
return regA % value
|
||||
case ALUOpXor:
|
||||
return regA ^ value
|
||||
default:
|
||||
return regA
|
||||
}
|
||||
}
|
||||
|
||||
func jumpIf(ins JumpIf, value uint32) int {
|
||||
var ok bool
|
||||
inV := uint32(ins.Val)
|
||||
|
||||
switch ins.Cond {
|
||||
case JumpEqual:
|
||||
ok = value == inV
|
||||
case JumpNotEqual:
|
||||
ok = value != inV
|
||||
case JumpGreaterThan:
|
||||
ok = value > inV
|
||||
case JumpLessThan:
|
||||
ok = value < inV
|
||||
case JumpGreaterOrEqual:
|
||||
ok = value >= inV
|
||||
case JumpLessOrEqual:
|
||||
ok = value <= inV
|
||||
case JumpBitsSet:
|
||||
ok = (value & inV) != 0
|
||||
case JumpBitsNotSet:
|
||||
ok = (value & inV) == 0
|
||||
}
|
||||
|
||||
if ok {
|
||||
return int(ins.SkipTrue)
|
||||
}
|
||||
|
||||
return int(ins.SkipFalse)
|
||||
}
|
||||
|
||||
func loadAbsolute(ins LoadAbsolute, in []byte) (uint32, bool) {
|
||||
offset := int(ins.Off)
|
||||
size := int(ins.Size)
|
||||
|
||||
return loadCommon(in, offset, size)
|
||||
}
|
||||
|
||||
func loadConstant(ins LoadConstant, regA uint32, regX uint32) (uint32, uint32) {
|
||||
switch ins.Dst {
|
||||
case RegA:
|
||||
regA = ins.Val
|
||||
case RegX:
|
||||
regX = ins.Val
|
||||
}
|
||||
|
||||
return regA, regX
|
||||
}
|
||||
|
||||
func loadExtension(ins LoadExtension, in []byte) uint32 {
|
||||
switch ins.Num {
|
||||
case ExtLen:
|
||||
return uint32(len(in))
|
||||
default:
|
||||
panic(fmt.Sprintf("unimplemented extension: %d", ins.Num))
|
||||
}
|
||||
}
|
||||
|
||||
func loadIndirect(ins LoadIndirect, in []byte, regX uint32) (uint32, bool) {
|
||||
offset := int(ins.Off) + int(regX)
|
||||
size := int(ins.Size)
|
||||
|
||||
return loadCommon(in, offset, size)
|
||||
}
|
||||
|
||||
func loadMemShift(ins LoadMemShift, in []byte) (uint32, bool) {
|
||||
offset := int(ins.Off)
|
||||
|
||||
if !inBounds(len(in), offset, 0) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Mask off high 4 bits and multiply low 4 bits by 4
|
||||
return uint32(in[offset]&0x0f) * 4, true
|
||||
}
|
||||
|
||||
func inBounds(inLen int, offset int, size int) bool {
|
||||
return offset+size <= inLen
|
||||
}
|
||||
|
||||
func loadCommon(in []byte, offset int, size int) (uint32, bool) {
|
||||
if !inBounds(len(in), offset, size) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch size {
|
||||
case 1:
|
||||
return uint32(in[offset]), true
|
||||
case 2:
|
||||
return uint32(binary.BigEndian.Uint16(in[offset : offset+size])), true
|
||||
case 4:
|
||||
return uint32(binary.BigEndian.Uint32(in[offset : offset+size])), true
|
||||
default:
|
||||
panic(fmt.Sprintf("invalid load size: %d", size))
|
||||
}
|
||||
}
|
||||
|
||||
func loadScratch(ins LoadScratch, regScratch [16]uint32, regA uint32, regX uint32) (uint32, uint32) {
|
||||
switch ins.Dst {
|
||||
case RegA:
|
||||
regA = regScratch[ins.N]
|
||||
case RegX:
|
||||
regX = regScratch[ins.N]
|
||||
}
|
||||
|
||||
return regA, regX
|
||||
}
|
||||
|
||||
func storeScratch(ins StoreScratch, regScratch [16]uint32, regA uint32, regX uint32) [16]uint32 {
|
||||
switch ins.Src {
|
||||
case RegA:
|
||||
regScratch[ins.N] = regA
|
||||
case RegX:
|
||||
regScratch[ins.N] = regX
|
||||
}
|
||||
|
||||
return regScratch
|
||||
}
|
|
@ -0,0 +1,180 @@
|
|||
// go generate gen.go
|
||||
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
|
||||
// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).
|
||||
package iana // import "golang.org/x/net/internal/iana"
|
||||
|
||||
// Differentiated Services Field Codepoints (DSCP), Updated: 2017-05-12
|
||||
const (
|
||||
DiffServCS0 = 0x0 // CS0
|
||||
DiffServCS1 = 0x20 // CS1
|
||||
DiffServCS2 = 0x40 // CS2
|
||||
DiffServCS3 = 0x60 // CS3
|
||||
DiffServCS4 = 0x80 // CS4
|
||||
DiffServCS5 = 0xa0 // CS5
|
||||
DiffServCS6 = 0xc0 // CS6
|
||||
DiffServCS7 = 0xe0 // CS7
|
||||
DiffServAF11 = 0x28 // AF11
|
||||
DiffServAF12 = 0x30 // AF12
|
||||
DiffServAF13 = 0x38 // AF13
|
||||
DiffServAF21 = 0x48 // AF21
|
||||
DiffServAF22 = 0x50 // AF22
|
||||
DiffServAF23 = 0x58 // AF23
|
||||
DiffServAF31 = 0x68 // AF31
|
||||
DiffServAF32 = 0x70 // AF32
|
||||
DiffServAF33 = 0x78 // AF33
|
||||
DiffServAF41 = 0x88 // AF41
|
||||
DiffServAF42 = 0x90 // AF42
|
||||
DiffServAF43 = 0x98 // AF43
|
||||
DiffServEF = 0xb8 // EF
|
||||
DiffServVOICEADMIT = 0xb0 // VOICE-ADMIT
|
||||
)
|
||||
|
||||
// IPv4 TOS Byte and IPv6 Traffic Class Octet, Updated: 2001-09-06
|
||||
const (
|
||||
NotECNTransport = 0x0 // Not-ECT (Not ECN-Capable Transport)
|
||||
ECNTransport1 = 0x1 // ECT(1) (ECN-Capable Transport(1))
|
||||
ECNTransport0 = 0x2 // ECT(0) (ECN-Capable Transport(0))
|
||||
CongestionExperienced = 0x3 // CE (Congestion Experienced)
|
||||
)
|
||||
|
||||
// Protocol Numbers, Updated: 2016-06-22
|
||||
const (
|
||||
ProtocolIP = 0 // IPv4 encapsulation, pseudo protocol number
|
||||
ProtocolHOPOPT = 0 // IPv6 Hop-by-Hop Option
|
||||
ProtocolICMP = 1 // Internet Control Message
|
||||
ProtocolIGMP = 2 // Internet Group Management
|
||||
ProtocolGGP = 3 // Gateway-to-Gateway
|
||||
ProtocolIPv4 = 4 // IPv4 encapsulation
|
||||
ProtocolST = 5 // Stream
|
||||
ProtocolTCP = 6 // Transmission Control
|
||||
ProtocolCBT = 7 // CBT
|
||||
ProtocolEGP = 8 // Exterior Gateway Protocol
|
||||
ProtocolIGP = 9 // any private interior gateway (used by Cisco for their IGRP)
|
||||
ProtocolBBNRCCMON = 10 // BBN RCC Monitoring
|
||||
ProtocolNVPII = 11 // Network Voice Protocol
|
||||
ProtocolPUP = 12 // PUP
|
||||
ProtocolEMCON = 14 // EMCON
|
||||
ProtocolXNET = 15 // Cross Net Debugger
|
||||
ProtocolCHAOS = 16 // Chaos
|
||||
ProtocolUDP = 17 // User Datagram
|
||||
ProtocolMUX = 18 // Multiplexing
|
||||
ProtocolDCNMEAS = 19 // DCN Measurement Subsystems
|
||||
ProtocolHMP = 20 // Host Monitoring
|
||||
ProtocolPRM = 21 // Packet Radio Measurement
|
||||
ProtocolXNSIDP = 22 // XEROX NS IDP
|
||||
ProtocolTRUNK1 = 23 // Trunk-1
|
||||
ProtocolTRUNK2 = 24 // Trunk-2
|
||||
ProtocolLEAF1 = 25 // Leaf-1
|
||||
ProtocolLEAF2 = 26 // Leaf-2
|
||||
ProtocolRDP = 27 // Reliable Data Protocol
|
||||
ProtocolIRTP = 28 // Internet Reliable Transaction
|
||||
ProtocolISOTP4 = 29 // ISO Transport Protocol Class 4
|
||||
ProtocolNETBLT = 30 // Bulk Data Transfer Protocol
|
||||
ProtocolMFENSP = 31 // MFE Network Services Protocol
|
||||
ProtocolMERITINP = 32 // MERIT Internodal Protocol
|
||||
ProtocolDCCP = 33 // Datagram Congestion Control Protocol
|
||||
Protocol3PC = 34 // Third Party Connect Protocol
|
||||
ProtocolIDPR = 35 // Inter-Domain Policy Routing Protocol
|
||||
ProtocolXTP = 36 // XTP
|
||||
ProtocolDDP = 37 // Datagram Delivery Protocol
|
||||
ProtocolIDPRCMTP = 38 // IDPR Control Message Transport Proto
|
||||
ProtocolTPPP = 39 // TP++ Transport Protocol
|
||||
ProtocolIL = 40 // IL Transport Protocol
|
||||
ProtocolIPv6 = 41 // IPv6 encapsulation
|
||||
ProtocolSDRP = 42 // Source Demand Routing Protocol
|
||||
ProtocolIPv6Route = 43 // Routing Header for IPv6
|
||||
ProtocolIPv6Frag = 44 // Fragment Header for IPv6
|
||||
ProtocolIDRP = 45 // Inter-Domain Routing Protocol
|
||||
ProtocolRSVP = 46 // Reservation Protocol
|
||||
ProtocolGRE = 47 // Generic Routing Encapsulation
|
||||
ProtocolDSR = 48 // Dynamic Source Routing Protocol
|
||||
ProtocolBNA = 49 // BNA
|
||||
ProtocolESP = 50 // Encap Security Payload
|
||||
ProtocolAH = 51 // Authentication Header
|
||||
ProtocolINLSP = 52 // Integrated Net Layer Security TUBA
|
||||
ProtocolNARP = 54 // NBMA Address Resolution Protocol
|
||||
ProtocolMOBILE = 55 // IP Mobility
|
||||
ProtocolTLSP = 56 // Transport Layer Security Protocol using Kryptonet key management
|
||||
ProtocolSKIP = 57 // SKIP
|
||||
ProtocolIPv6ICMP = 58 // ICMP for IPv6
|
||||
ProtocolIPv6NoNxt = 59 // No Next Header for IPv6
|
||||
ProtocolIPv6Opts = 60 // Destination Options for IPv6
|
||||
ProtocolCFTP = 62 // CFTP
|
||||
ProtocolSATEXPAK = 64 // SATNET and Backroom EXPAK
|
||||
ProtocolKRYPTOLAN = 65 // Kryptolan
|
||||
ProtocolRVD = 66 // MIT Remote Virtual Disk Protocol
|
||||
ProtocolIPPC = 67 // Internet Pluribus Packet Core
|
||||
ProtocolSATMON = 69 // SATNET Monitoring
|
||||
ProtocolVISA = 70 // VISA Protocol
|
||||
ProtocolIPCV = 71 // Internet Packet Core Utility
|
||||
ProtocolCPNX = 72 // Computer Protocol Network Executive
|
||||
ProtocolCPHB = 73 // Computer Protocol Heart Beat
|
||||
ProtocolWSN = 74 // Wang Span Network
|
||||
ProtocolPVP = 75 // Packet Video Protocol
|
||||
ProtocolBRSATMON = 76 // Backroom SATNET Monitoring
|
||||
ProtocolSUNND = 77 // SUN ND PROTOCOL-Temporary
|
||||
ProtocolWBMON = 78 // WIDEBAND Monitoring
|
||||
ProtocolWBEXPAK = 79 // WIDEBAND EXPAK
|
||||
ProtocolISOIP = 80 // ISO Internet Protocol
|
||||
ProtocolVMTP = 81 // VMTP
|
||||
ProtocolSECUREVMTP = 82 // SECURE-VMTP
|
||||
ProtocolVINES = 83 // VINES
|
||||
ProtocolTTP = 84 // Transaction Transport Protocol
|
||||
ProtocolIPTM = 84 // Internet Protocol Traffic Manager
|
||||
ProtocolNSFNETIGP = 85 // NSFNET-IGP
|
||||
ProtocolDGP = 86 // Dissimilar Gateway Protocol
|
||||
ProtocolTCF = 87 // TCF
|
||||
ProtocolEIGRP = 88 // EIGRP
|
||||
ProtocolOSPFIGP = 89 // OSPFIGP
|
||||
ProtocolSpriteRPC = 90 // Sprite RPC Protocol
|
||||
ProtocolLARP = 91 // Locus Address Resolution Protocol
|
||||
ProtocolMTP = 92 // Multicast Transport Protocol
|
||||
ProtocolAX25 = 93 // AX.25 Frames
|
||||
ProtocolIPIP = 94 // IP-within-IP Encapsulation Protocol
|
||||
ProtocolSCCSP = 96 // Semaphore Communications Sec. Pro.
|
||||
ProtocolETHERIP = 97 // Ethernet-within-IP Encapsulation
|
||||
ProtocolENCAP = 98 // Encapsulation Header
|
||||
ProtocolGMTP = 100 // GMTP
|
||||
ProtocolIFMP = 101 // Ipsilon Flow Management Protocol
|
||||
ProtocolPNNI = 102 // PNNI over IP
|
||||
ProtocolPIM = 103 // Protocol Independent Multicast
|
||||
ProtocolARIS = 104 // ARIS
|
||||
ProtocolSCPS = 105 // SCPS
|
||||
ProtocolQNX = 106 // QNX
|
||||
ProtocolAN = 107 // Active Networks
|
||||
ProtocolIPComp = 108 // IP Payload Compression Protocol
|
||||
ProtocolSNP = 109 // Sitara Networks Protocol
|
||||
ProtocolCompaqPeer = 110 // Compaq Peer Protocol
|
||||
ProtocolIPXinIP = 111 // IPX in IP
|
||||
ProtocolVRRP = 112 // Virtual Router Redundancy Protocol
|
||||
ProtocolPGM = 113 // PGM Reliable Transport Protocol
|
||||
ProtocolL2TP = 115 // Layer Two Tunneling Protocol
|
||||
ProtocolDDX = 116 // D-II Data Exchange (DDX)
|
||||
ProtocolIATP = 117 // Interactive Agent Transfer Protocol
|
||||
ProtocolSTP = 118 // Schedule Transfer Protocol
|
||||
ProtocolSRP = 119 // SpectraLink Radio Protocol
|
||||
ProtocolUTI = 120 // UTI
|
||||
ProtocolSMP = 121 // Simple Message Protocol
|
||||
ProtocolPTP = 123 // Performance Transparency Protocol
|
||||
ProtocolISIS = 124 // ISIS over IPv4
|
||||
ProtocolFIRE = 125 // FIRE
|
||||
ProtocolCRTP = 126 // Combat Radio Transport Protocol
|
||||
ProtocolCRUDP = 127 // Combat Radio User Datagram
|
||||
ProtocolSSCOPMCE = 128 // SSCOPMCE
|
||||
ProtocolIPLT = 129 // IPLT
|
||||
ProtocolSPS = 130 // Secure Packet Shield
|
||||
ProtocolPIPE = 131 // Private IP Encapsulation within IP
|
||||
ProtocolSCTP = 132 // Stream Control Transmission Protocol
|
||||
ProtocolFC = 133 // Fibre Channel
|
||||
ProtocolRSVPE2EIGNORE = 134 // RSVP-E2E-IGNORE
|
||||
ProtocolMobilityHeader = 135 // Mobility Header
|
||||
ProtocolUDPLite = 136 // UDPLite
|
||||
ProtocolMPLSinIP = 137 // MPLS-in-IP
|
||||
ProtocolMANET = 138 // MANET Protocols
|
||||
ProtocolHIP = 139 // Host Identity Protocol
|
||||
ProtocolShim6 = 140 // Shim6 Protocol
|
||||
ProtocolWESP = 141 // Wrapped Encapsulating Security Payload
|
||||
ProtocolROHC = 142 // Robust Header Compression
|
||||
ProtocolReserved = 255 // Reserved
|
||||
)
|
|
@ -0,0 +1,293 @@
|
|||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
//go:generate go run gen.go
|
||||
|
||||
// This program generates internet protocol constants and tables by
|
||||
// reading IANA protocol registries.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var registries = []struct {
|
||||
url string
|
||||
parse func(io.Writer, io.Reader) error
|
||||
}{
|
||||
{
|
||||
"http://www.iana.org/assignments/dscp-registry/dscp-registry.xml",
|
||||
parseDSCPRegistry,
|
||||
},
|
||||
{
|
||||
"http://www.iana.org/assignments/ipv4-tos-byte/ipv4-tos-byte.xml",
|
||||
parseTOSTCByte,
|
||||
},
|
||||
{
|
||||
"http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml",
|
||||
parseProtocolNumbers,
|
||||
},
|
||||
}
|
||||
|
||||
func main() {
|
||||
var bb bytes.Buffer
|
||||
fmt.Fprintf(&bb, "// go generate gen.go\n")
|
||||
fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n")
|
||||
fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n")
|
||||
fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"`+"\n\n")
|
||||
for _, r := range registries {
|
||||
resp, err := http.Get(r.url)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := r.parse(&bb, resp.Body); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Fprintf(&bb, "\n")
|
||||
}
|
||||
b, err := format.Source(bb.Bytes())
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := ioutil.WriteFile("const.go", b, 0644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func parseDSCPRegistry(w io.Writer, r io.Reader) error {
|
||||
dec := xml.NewDecoder(r)
|
||||
var dr dscpRegistry
|
||||
if err := dec.Decode(&dr); err != nil {
|
||||
return err
|
||||
}
|
||||
drs := dr.escape()
|
||||
fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated)
|
||||
fmt.Fprintf(w, "const (\n")
|
||||
for _, dr := range drs {
|
||||
fmt.Fprintf(w, "DiffServ%s = %#x", dr.Name, dr.Value)
|
||||
fmt.Fprintf(w, "// %s\n", dr.OrigName)
|
||||
}
|
||||
fmt.Fprintf(w, ")\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
type dscpRegistry struct {
|
||||
XMLName xml.Name `xml:"registry"`
|
||||
Title string `xml:"title"`
|
||||
Updated string `xml:"updated"`
|
||||
Note string `xml:"note"`
|
||||
RegTitle string `xml:"registry>title"`
|
||||
PoolRecords []struct {
|
||||
Name string `xml:"name"`
|
||||
Space string `xml:"space"`
|
||||
} `xml:"registry>record"`
|
||||
Records []struct {
|
||||
Name string `xml:"name"`
|
||||
Space string `xml:"space"`
|
||||
} `xml:"registry>registry>record"`
|
||||
}
|
||||
|
||||
type canonDSCPRecord struct {
|
||||
OrigName string
|
||||
Name string
|
||||
Value int
|
||||
}
|
||||
|
||||
func (drr *dscpRegistry) escape() []canonDSCPRecord {
|
||||
drs := make([]canonDSCPRecord, len(drr.Records))
|
||||
sr := strings.NewReplacer(
|
||||
"+", "",
|
||||
"-", "",
|
||||
"/", "",
|
||||
".", "",
|
||||
" ", "",
|
||||
)
|
||||
for i, dr := range drr.Records {
|
||||
s := strings.TrimSpace(dr.Name)
|
||||
drs[i].OrigName = s
|
||||
drs[i].Name = sr.Replace(s)
|
||||
n, err := strconv.ParseUint(dr.Space, 2, 8)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
drs[i].Value = int(n) << 2
|
||||
}
|
||||
return drs
|
||||
}
|
||||
|
||||
func parseTOSTCByte(w io.Writer, r io.Reader) error {
|
||||
dec := xml.NewDecoder(r)
|
||||
var ttb tosTCByte
|
||||
if err := dec.Decode(&ttb); err != nil {
|
||||
return err
|
||||
}
|
||||
trs := ttb.escape()
|
||||
fmt.Fprintf(w, "// %s, Updated: %s\n", ttb.Title, ttb.Updated)
|
||||
fmt.Fprintf(w, "const (\n")
|
||||
for _, tr := range trs {
|
||||
fmt.Fprintf(w, "%s = %#x", tr.Keyword, tr.Value)
|
||||
fmt.Fprintf(w, "// %s\n", tr.OrigKeyword)
|
||||
}
|
||||
fmt.Fprintf(w, ")\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
type tosTCByte struct {
|
||||
XMLName xml.Name `xml:"registry"`
|
||||
Title string `xml:"title"`
|
||||
Updated string `xml:"updated"`
|
||||
Note string `xml:"note"`
|
||||
RegTitle string `xml:"registry>title"`
|
||||
Records []struct {
|
||||
Binary string `xml:"binary"`
|
||||
Keyword string `xml:"keyword"`
|
||||
} `xml:"registry>record"`
|
||||
}
|
||||
|
||||
type canonTOSTCByteRecord struct {
|
||||
OrigKeyword string
|
||||
Keyword string
|
||||
Value int
|
||||
}
|
||||
|
||||
func (ttb *tosTCByte) escape() []canonTOSTCByteRecord {
|
||||
trs := make([]canonTOSTCByteRecord, len(ttb.Records))
|
||||
sr := strings.NewReplacer(
|
||||
"Capable", "",
|
||||
"(", "",
|
||||
")", "",
|
||||
"+", "",
|
||||
"-", "",
|
||||
"/", "",
|
||||
".", "",
|
||||
" ", "",
|
||||
)
|
||||
for i, tr := range ttb.Records {
|
||||
s := strings.TrimSpace(tr.Keyword)
|
||||
trs[i].OrigKeyword = s
|
||||
ss := strings.Split(s, " ")
|
||||
if len(ss) > 1 {
|
||||
trs[i].Keyword = strings.Join(ss[1:], " ")
|
||||
} else {
|
||||
trs[i].Keyword = ss[0]
|
||||
}
|
||||
trs[i].Keyword = sr.Replace(trs[i].Keyword)
|
||||
n, err := strconv.ParseUint(tr.Binary, 2, 8)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
trs[i].Value = int(n)
|
||||
}
|
||||
return trs
|
||||
}
|
||||
|
||||
func parseProtocolNumbers(w io.Writer, r io.Reader) error {
|
||||
dec := xml.NewDecoder(r)
|
||||
var pn protocolNumbers
|
||||
if err := dec.Decode(&pn); err != nil {
|
||||
return err
|
||||
}
|
||||
prs := pn.escape()
|
||||
prs = append([]canonProtocolRecord{{
|
||||
Name: "IP",
|
||||
Descr: "IPv4 encapsulation, pseudo protocol number",
|
||||
Value: 0,
|
||||
}}, prs...)
|
||||
fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated)
|
||||
fmt.Fprintf(w, "const (\n")
|
||||
for _, pr := range prs {
|
||||
if pr.Name == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value)
|
||||
s := pr.Descr
|
||||
if s == "" {
|
||||
s = pr.OrigName
|
||||
}
|
||||
fmt.Fprintf(w, "// %s\n", s)
|
||||
}
|
||||
fmt.Fprintf(w, ")\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
type protocolNumbers struct {
|
||||
XMLName xml.Name `xml:"registry"`
|
||||
Title string `xml:"title"`
|
||||
Updated string `xml:"updated"`
|
||||
RegTitle string `xml:"registry>title"`
|
||||
Note string `xml:"registry>note"`
|
||||
Records []struct {
|
||||
Value string `xml:"value"`
|
||||
Name string `xml:"name"`
|
||||
Descr string `xml:"description"`
|
||||
} `xml:"registry>record"`
|
||||
}
|
||||
|
||||
type canonProtocolRecord struct {
|
||||
OrigName string
|
||||
Name string
|
||||
Descr string
|
||||
Value int
|
||||
}
|
||||
|
||||
func (pn *protocolNumbers) escape() []canonProtocolRecord {
|
||||
prs := make([]canonProtocolRecord, len(pn.Records))
|
||||
sr := strings.NewReplacer(
|
||||
"-in-", "in",
|
||||
"-within-", "within",
|
||||
"-over-", "over",
|
||||
"+", "P",
|
||||
"-", "",
|
||||
"/", "",
|
||||
".", "",
|
||||
" ", "",
|
||||
)
|
||||
for i, pr := range pn.Records {
|
||||
if strings.Contains(pr.Name, "Deprecated") ||
|
||||
strings.Contains(pr.Name, "deprecated") {
|
||||
continue
|
||||
}
|
||||
prs[i].OrigName = pr.Name
|
||||
s := strings.TrimSpace(pr.Name)
|
||||
switch pr.Name {
|
||||
case "ISIS over IPv4":
|
||||
prs[i].Name = "ISIS"
|
||||
case "manet":
|
||||
prs[i].Name = "MANET"
|
||||
default:
|
||||
prs[i].Name = sr.Replace(s)
|
||||
}
|
||||
ss := strings.Split(pr.Descr, "\n")
|
||||
for i := range ss {
|
||||
ss[i] = strings.TrimSpace(ss[i])
|
||||
}
|
||||
if len(ss) > 1 {
|
||||
prs[i].Descr = strings.Join(ss, " ")
|
||||
} else {
|
||||
prs[i].Descr = ss[0]
|
||||
}
|
||||
prs[i].Value, _ = strconv.Atoi(pr.Value)
|
||||
}
|
||||
return prs
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
|
||||
|
||||
package socket
|
||||
|
||||
func (h *cmsghdr) len() int { return int(h.Len) }
|
||||
func (h *cmsghdr) lvl() int { return int(h.Level) }
|
||||
func (h *cmsghdr) typ() int { return int(h.Type) }
|
|
@ -0,0 +1,13 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd netbsd openbsd
|
||||
|
||||
package socket
|
||||
|
||||
func (h *cmsghdr) set(l, lvl, typ int) {
|
||||
h.Len = uint32(l)
|
||||
h.Level = int32(lvl)
|
||||
h.Type = int32(typ)
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build arm mips mipsle 386
|
||||
// +build linux
|
||||
|
||||
package socket
|
||||
|
||||
func (h *cmsghdr) set(l, lvl, typ int) {
|
||||
h.Len = uint32(l)
|
||||
h.Level = int32(lvl)
|
||||
h.Type = int32(typ)
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x
|
||||
// +build linux
|
||||
|
||||
package socket
|
||||
|
||||
func (h *cmsghdr) set(l, lvl, typ int) {
|
||||
h.Len = uint64(l)
|
||||
h.Level = int32(lvl)
|
||||
h.Type = int32(typ)
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build amd64
|
||||
// +build solaris
|
||||
|
||||
package socket
|
||||
|
||||
func (h *cmsghdr) set(l, lvl, typ int) {
|
||||
h.Len = uint32(l)
|
||||
h.Level = int32(lvl)
|
||||
h.Type = int32(typ)
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris
|
||||
|
||||
package socket
|
||||
|
||||
type cmsghdr struct{}
|
||||
|
||||
const sizeofCmsghdr = 0
|
||||
|
||||
func (h *cmsghdr) len() int { return 0 }
|
||||
func (h *cmsghdr) lvl() int { return 0 }
|
||||
func (h *cmsghdr) typ() int { return 0 }
|
||||
|
||||
func (h *cmsghdr) set(l, lvl, typ int) {}
|
|
@ -0,0 +1,44 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// +godefs map struct_in_addr [4]byte /* in_addr */
|
||||
// +godefs map struct_in6_addr [16]byte /* in6_addr */
|
||||
|
||||
package socket
|
||||
|
||||
/*
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = C.AF_UNSPEC
|
||||
sysAF_INET = C.AF_INET
|
||||
sysAF_INET6 = C.AF_INET6
|
||||
|
||||
sysSOCK_RAW = C.SOCK_RAW
|
||||
)
|
||||
|
||||
type iovec C.struct_iovec
|
||||
|
||||
type msghdr C.struct_msghdr
|
||||
|
||||
type cmsghdr C.struct_cmsghdr
|
||||
|
||||
type sockaddrInet C.struct_sockaddr_in
|
||||
|
||||
type sockaddrInet6 C.struct_sockaddr_in6
|
||||
|
||||
const (
|
||||
sizeofIovec = C.sizeof_struct_iovec
|
||||
sizeofMsghdr = C.sizeof_struct_msghdr
|
||||
sizeofCmsghdr = C.sizeof_struct_cmsghdr
|
||||
|
||||
sizeofSockaddrInet = C.sizeof_struct_sockaddr_in
|
||||
sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
|
||||
)
|
|
@ -0,0 +1,44 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// +godefs map struct_in_addr [4]byte /* in_addr */
|
||||
// +godefs map struct_in6_addr [16]byte /* in6_addr */
|
||||
|
||||
package socket
|
||||
|
||||
/*
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = C.AF_UNSPEC
|
||||
sysAF_INET = C.AF_INET
|
||||
sysAF_INET6 = C.AF_INET6
|
||||
|
||||
sysSOCK_RAW = C.SOCK_RAW
|
||||
)
|
||||
|
||||
type iovec C.struct_iovec
|
||||
|
||||
type msghdr C.struct_msghdr
|
||||
|
||||
type cmsghdr C.struct_cmsghdr
|
||||
|
||||
type sockaddrInet C.struct_sockaddr_in
|
||||
|
||||
type sockaddrInet6 C.struct_sockaddr_in6
|
||||
|
||||
const (
|
||||
sizeofIovec = C.sizeof_struct_iovec
|
||||
sizeofMsghdr = C.sizeof_struct_msghdr
|
||||
sizeofCmsghdr = C.sizeof_struct_cmsghdr
|
||||
|
||||
sizeofSockaddrInet = C.sizeof_struct_sockaddr_in
|
||||
sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
|
||||
)
|
|
@ -0,0 +1,44 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// +godefs map struct_in_addr [4]byte /* in_addr */
|
||||
// +godefs map struct_in6_addr [16]byte /* in6_addr */
|
||||
|
||||
package socket
|
||||
|
||||
/*
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = C.AF_UNSPEC
|
||||
sysAF_INET = C.AF_INET
|
||||
sysAF_INET6 = C.AF_INET6
|
||||
|
||||
sysSOCK_RAW = C.SOCK_RAW
|
||||
)
|
||||
|
||||
type iovec C.struct_iovec
|
||||
|
||||
type msghdr C.struct_msghdr
|
||||
|
||||
type cmsghdr C.struct_cmsghdr
|
||||
|
||||
type sockaddrInet C.struct_sockaddr_in
|
||||
|
||||
type sockaddrInet6 C.struct_sockaddr_in6
|
||||
|
||||
const (
|
||||
sizeofIovec = C.sizeof_struct_iovec
|
||||
sizeofMsghdr = C.sizeof_struct_msghdr
|
||||
sizeofCmsghdr = C.sizeof_struct_cmsghdr
|
||||
|
||||
sizeofSockaddrInet = C.sizeof_struct_sockaddr_in
|
||||
sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
|
||||
)
|
|
@ -0,0 +1,49 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// +godefs map struct_in_addr [4]byte /* in_addr */
|
||||
// +godefs map struct_in6_addr [16]byte /* in6_addr */
|
||||
|
||||
package socket
|
||||
|
||||
/*
|
||||
#include <linux/in.h>
|
||||
#include <linux/in6.h>
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <sys/socket.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = C.AF_UNSPEC
|
||||
sysAF_INET = C.AF_INET
|
||||
sysAF_INET6 = C.AF_INET6
|
||||
|
||||
sysSOCK_RAW = C.SOCK_RAW
|
||||
)
|
||||
|
||||
type iovec C.struct_iovec
|
||||
|
||||
type msghdr C.struct_msghdr
|
||||
|
||||
type mmsghdr C.struct_mmsghdr
|
||||
|
||||
type cmsghdr C.struct_cmsghdr
|
||||
|
||||
type sockaddrInet C.struct_sockaddr_in
|
||||
|
||||
type sockaddrInet6 C.struct_sockaddr_in6
|
||||
|
||||
const (
|
||||
sizeofIovec = C.sizeof_struct_iovec
|
||||
sizeofMsghdr = C.sizeof_struct_msghdr
|
||||
sizeofMmsghdr = C.sizeof_struct_mmsghdr
|
||||
sizeofCmsghdr = C.sizeof_struct_cmsghdr
|
||||
|
||||
sizeofSockaddrInet = C.sizeof_struct_sockaddr_in
|
||||
sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
|
||||
)
|
|
@ -0,0 +1,47 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// +godefs map struct_in_addr [4]byte /* in_addr */
|
||||
// +godefs map struct_in6_addr [16]byte /* in6_addr */
|
||||
|
||||
package socket
|
||||
|
||||
/*
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = C.AF_UNSPEC
|
||||
sysAF_INET = C.AF_INET
|
||||
sysAF_INET6 = C.AF_INET6
|
||||
|
||||
sysSOCK_RAW = C.SOCK_RAW
|
||||
)
|
||||
|
||||
type iovec C.struct_iovec
|
||||
|
||||
type msghdr C.struct_msghdr
|
||||
|
||||
type mmsghdr C.struct_mmsghdr
|
||||
|
||||
type cmsghdr C.struct_cmsghdr
|
||||
|
||||
type sockaddrInet C.struct_sockaddr_in
|
||||
|
||||
type sockaddrInet6 C.struct_sockaddr_in6
|
||||
|
||||
const (
|
||||
sizeofIovec = C.sizeof_struct_iovec
|
||||
sizeofMsghdr = C.sizeof_struct_msghdr
|
||||
sizeofMmsghdr = C.sizeof_struct_mmsghdr
|
||||
sizeofCmsghdr = C.sizeof_struct_cmsghdr
|
||||
|
||||
sizeofSockaddrInet = C.sizeof_struct_sockaddr_in
|
||||
sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
|
||||
)
|
|
@ -0,0 +1,44 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// +godefs map struct_in_addr [4]byte /* in_addr */
|
||||
// +godefs map struct_in6_addr [16]byte /* in6_addr */
|
||||
|
||||
package socket
|
||||
|
||||
/*
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = C.AF_UNSPEC
|
||||
sysAF_INET = C.AF_INET
|
||||
sysAF_INET6 = C.AF_INET6
|
||||
|
||||
sysSOCK_RAW = C.SOCK_RAW
|
||||
)
|
||||
|
||||
type iovec C.struct_iovec
|
||||
|
||||
type msghdr C.struct_msghdr
|
||||
|
||||
type cmsghdr C.struct_cmsghdr
|
||||
|
||||
type sockaddrInet C.struct_sockaddr_in
|
||||
|
||||
type sockaddrInet6 C.struct_sockaddr_in6
|
||||
|
||||
const (
|
||||
sizeofIovec = C.sizeof_struct_iovec
|
||||
sizeofMsghdr = C.sizeof_struct_msghdr
|
||||
sizeofCmsghdr = C.sizeof_struct_cmsghdr
|
||||
|
||||
sizeofSockaddrInet = C.sizeof_struct_sockaddr_in
|
||||
sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
|
||||
)
|
|
@ -0,0 +1,44 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build ignore
|
||||
|
||||
// +godefs map struct_in_addr [4]byte /* in_addr */
|
||||
// +godefs map struct_in6_addr [16]byte /* in6_addr */
|
||||
|
||||
package socket
|
||||
|
||||
/*
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = C.AF_UNSPEC
|
||||
sysAF_INET = C.AF_INET
|
||||
sysAF_INET6 = C.AF_INET6
|
||||
|
||||
sysSOCK_RAW = C.SOCK_RAW
|
||||
)
|
||||
|
||||
type iovec C.struct_iovec
|
||||
|
||||
type msghdr C.struct_msghdr
|
||||
|
||||
type cmsghdr C.struct_cmsghdr
|
||||
|
||||
type sockaddrInet C.struct_sockaddr_in
|
||||
|
||||
type sockaddrInet6 C.struct_sockaddr_in6
|
||||
|
||||
const (
|
||||
sizeofIovec = C.sizeof_struct_iovec
|
||||
sizeofMsghdr = C.sizeof_struct_msghdr
|
||||
sizeofCmsghdr = C.sizeof_struct_cmsghdr
|
||||
|
||||
sizeofSockaddrInet = C.sizeof_struct_sockaddr_in
|
||||
sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
|
||||
)
|
|
@ -0,0 +1,31 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
|
||||
|
||||
package socket
|
||||
|
||||
import "syscall"
|
||||
|
||||
var (
|
||||
errEAGAIN error = syscall.EAGAIN
|
||||
errEINVAL error = syscall.EINVAL
|
||||
errENOENT error = syscall.ENOENT
|
||||
)
|
||||
|
||||
// errnoErr returns common boxed Errno values, to prevent allocations
|
||||
// at runtime.
|
||||
func errnoErr(errno syscall.Errno) error {
|
||||
switch errno {
|
||||
case 0:
|
||||
return nil
|
||||
case syscall.EAGAIN:
|
||||
return errEAGAIN
|
||||
case syscall.EINVAL:
|
||||
return errEINVAL
|
||||
case syscall.ENOENT:
|
||||
return errENOENT
|
||||
}
|
||||
return errno
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import "syscall"
|
||||
|
||||
var (
|
||||
errERROR_IO_PENDING error = syscall.ERROR_IO_PENDING
|
||||
errEINVAL error = syscall.EINVAL
|
||||
)
|
||||
|
||||
// errnoErr returns common boxed Errno values, to prevent allocations
|
||||
// at runtime.
|
||||
func errnoErr(errno syscall.Errno) error {
|
||||
switch errno {
|
||||
case 0:
|
||||
return nil
|
||||
case syscall.ERROR_IO_PENDING:
|
||||
return errERROR_IO_PENDING
|
||||
case syscall.EINVAL:
|
||||
return errEINVAL
|
||||
}
|
||||
return errno
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build arm mips mipsle 386
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (v *iovec) set(b []byte) {
|
||||
l := len(b)
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
v.Base = (*byte)(unsafe.Pointer(&b[0]))
|
||||
v.Len = uint32(l)
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (v *iovec) set(b []byte) {
|
||||
l := len(b)
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
v.Base = (*byte)(unsafe.Pointer(&b[0]))
|
||||
v.Len = uint64(l)
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build amd64
|
||||
// +build solaris
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (v *iovec) set(b []byte) {
|
||||
l := len(b)
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
v.Base = (*int8)(unsafe.Pointer(&b[0]))
|
||||
v.Len = uint64(l)
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris
|
||||
|
||||
package socket
|
||||
|
||||
type iovec struct{}
|
||||
|
||||
func (v *iovec) set(b []byte) {}
|
|
@ -0,0 +1,21 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !linux,!netbsd
|
||||
|
||||
package socket
|
||||
|
||||
import "net"
|
||||
|
||||
type mmsghdr struct{}
|
||||
|
||||
type mmsghdrs []mmsghdr
|
||||
|
||||
func (hs mmsghdrs) pack(ms []Message, parseFn func([]byte, string) (net.Addr, error), marshalFn func(net.Addr) []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs mmsghdrs) unpack(ms []Message, parseFn func([]byte, string) (net.Addr, error), hint string) error {
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build linux netbsd
|
||||
|
||||
package socket
|
||||
|
||||
import "net"
|
||||
|
||||
type mmsghdrs []mmsghdr
|
||||
|
||||
func (hs mmsghdrs) pack(ms []Message, parseFn func([]byte, string) (net.Addr, error), marshalFn func(net.Addr) []byte) error {
|
||||
for i := range hs {
|
||||
vs := make([]iovec, len(ms[i].Buffers))
|
||||
var sa []byte
|
||||
if parseFn != nil {
|
||||
sa = make([]byte, sizeofSockaddrInet6)
|
||||
}
|
||||
if marshalFn != nil {
|
||||
sa = marshalFn(ms[i].Addr)
|
||||
}
|
||||
hs[i].Hdr.pack(vs, ms[i].Buffers, ms[i].OOB, sa)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs mmsghdrs) unpack(ms []Message, parseFn func([]byte, string) (net.Addr, error), hint string) error {
|
||||
for i := range hs {
|
||||
ms[i].N = int(hs[i].Len)
|
||||
ms[i].NN = hs[i].Hdr.controllen()
|
||||
ms[i].Flags = hs[i].Hdr.flags()
|
||||
if parseFn != nil {
|
||||
var err error
|
||||
ms[i].Addr, err = parseFn(hs[i].Hdr.name(), hint)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd netbsd openbsd
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) {
|
||||
for i := range vs {
|
||||
vs[i].set(bs[i])
|
||||
}
|
||||
h.setIov(vs)
|
||||
if len(oob) > 0 {
|
||||
h.Control = (*byte)(unsafe.Pointer(&oob[0]))
|
||||
h.Controllen = uint32(len(oob))
|
||||
}
|
||||
if sa != nil {
|
||||
h.Name = (*byte)(unsafe.Pointer(&sa[0]))
|
||||
h.Namelen = uint32(len(sa))
|
||||
}
|
||||
}
|
||||
|
||||
func (h *msghdr) name() []byte {
|
||||
if h.Name != nil && h.Namelen > 0 {
|
||||
return (*[sizeofSockaddrInet6]byte)(unsafe.Pointer(h.Name))[:h.Namelen]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *msghdr) controllen() int {
|
||||
return int(h.Controllen)
|
||||
}
|
||||
|
||||
func (h *msghdr) flags() int {
|
||||
return int(h.Flags)
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd netbsd
|
||||
|
||||
package socket
|
||||
|
||||
func (h *msghdr) setIov(vs []iovec) {
|
||||
l := len(vs)
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
h.Iov = &vs[0]
|
||||
h.Iovlen = int32(l)
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) {
|
||||
for i := range vs {
|
||||
vs[i].set(bs[i])
|
||||
}
|
||||
h.setIov(vs)
|
||||
if len(oob) > 0 {
|
||||
h.setControl(oob)
|
||||
}
|
||||
if sa != nil {
|
||||
h.Name = (*byte)(unsafe.Pointer(&sa[0]))
|
||||
h.Namelen = uint32(len(sa))
|
||||
}
|
||||
}
|
||||
|
||||
func (h *msghdr) name() []byte {
|
||||
if h.Name != nil && h.Namelen > 0 {
|
||||
return (*[sizeofSockaddrInet6]byte)(unsafe.Pointer(h.Name))[:h.Namelen]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *msghdr) controllen() int {
|
||||
return int(h.Controllen)
|
||||
}
|
||||
|
||||
func (h *msghdr) flags() int {
|
||||
return int(h.Flags)
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build arm mips mipsle 386
|
||||
// +build linux
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (h *msghdr) setIov(vs []iovec) {
|
||||
l := len(vs)
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
h.Iov = &vs[0]
|
||||
h.Iovlen = uint32(l)
|
||||
}
|
||||
|
||||
func (h *msghdr) setControl(b []byte) {
|
||||
h.Control = (*byte)(unsafe.Pointer(&b[0]))
|
||||
h.Controllen = uint32(len(b))
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x
|
||||
// +build linux
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (h *msghdr) setIov(vs []iovec) {
|
||||
l := len(vs)
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
h.Iov = &vs[0]
|
||||
h.Iovlen = uint64(l)
|
||||
}
|
||||
|
||||
func (h *msghdr) setControl(b []byte) {
|
||||
h.Control = (*byte)(unsafe.Pointer(&b[0]))
|
||||
h.Controllen = uint64(len(b))
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
func (h *msghdr) setIov(vs []iovec) {
|
||||
l := len(vs)
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
h.Iov = &vs[0]
|
||||
h.Iovlen = uint32(l)
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build amd64
|
||||
// +build solaris
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) {
|
||||
for i := range vs {
|
||||
vs[i].set(bs[i])
|
||||
}
|
||||
if len(vs) > 0 {
|
||||
h.Iov = &vs[0]
|
||||
h.Iovlen = int32(len(vs))
|
||||
}
|
||||
if len(oob) > 0 {
|
||||
h.Accrights = (*int8)(unsafe.Pointer(&oob[0]))
|
||||
h.Accrightslen = int32(len(oob))
|
||||
}
|
||||
if sa != nil {
|
||||
h.Name = (*byte)(unsafe.Pointer(&sa[0]))
|
||||
h.Namelen = uint32(len(sa))
|
||||
}
|
||||
}
|
||||
|
||||
func (h *msghdr) controllen() int {
|
||||
return int(h.Accrightslen)
|
||||
}
|
||||
|
||||
func (h *msghdr) flags() int {
|
||||
return int(NativeEndian.Uint32(h.Pad_cgo_2[:]))
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris
|
||||
|
||||
package socket
|
||||
|
||||
type msghdr struct{}
|
||||
|
||||
func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) {}
|
||||
func (h *msghdr) name() []byte { return nil }
|
||||
func (h *msghdr) controllen() int { return 0 }
|
||||
func (h *msghdr) flags() int { return 0 }
|
|
@ -0,0 +1,66 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.9
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// A Conn represents a raw connection.
|
||||
type Conn struct {
|
||||
network string
|
||||
c syscall.RawConn
|
||||
}
|
||||
|
||||
// NewConn returns a new raw connection.
|
||||
func NewConn(c net.Conn) (*Conn, error) {
|
||||
var err error
|
||||
var cc Conn
|
||||
switch c := c.(type) {
|
||||
case *net.TCPConn:
|
||||
cc.network = "tcp"
|
||||
cc.c, err = c.SyscallConn()
|
||||
case *net.UDPConn:
|
||||
cc.network = "udp"
|
||||
cc.c, err = c.SyscallConn()
|
||||
case *net.IPConn:
|
||||
cc.network = "ip"
|
||||
cc.c, err = c.SyscallConn()
|
||||
default:
|
||||
return nil, errors.New("unknown connection type")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cc, nil
|
||||
}
|
||||
|
||||
func (o *Option) get(c *Conn, b []byte) (int, error) {
|
||||
var operr error
|
||||
var n int
|
||||
fn := func(s uintptr) {
|
||||
n, operr = getsockopt(s, o.Level, o.Name, b)
|
||||
}
|
||||
if err := c.c.Control(fn); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, os.NewSyscallError("getsockopt", operr)
|
||||
}
|
||||
|
||||
func (o *Option) set(c *Conn, b []byte) error {
|
||||
var operr error
|
||||
fn := func(s uintptr) {
|
||||
operr = setsockopt(s, o.Level, o.Name, b)
|
||||
}
|
||||
if err := c.c.Control(fn); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.NewSyscallError("setsockopt", operr)
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.9
|
||||
// +build linux
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) {
|
||||
hs := make(mmsghdrs, len(ms))
|
||||
var parseFn func([]byte, string) (net.Addr, error)
|
||||
if c.network != "tcp" {
|
||||
parseFn = parseInetAddr
|
||||
}
|
||||
if err := hs.pack(ms, parseFn, nil); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var operr error
|
||||
var n int
|
||||
fn := func(s uintptr) bool {
|
||||
n, operr = recvmmsg(s, hs, flags)
|
||||
if operr == syscall.EAGAIN {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if err := c.c.Read(fn); err != nil {
|
||||
return n, err
|
||||
}
|
||||
if operr != nil {
|
||||
return n, os.NewSyscallError("recvmmsg", operr)
|
||||
}
|
||||
if err := hs[:n].unpack(ms[:n], parseFn, c.network); err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) {
|
||||
hs := make(mmsghdrs, len(ms))
|
||||
var marshalFn func(net.Addr) []byte
|
||||
if c.network != "tcp" {
|
||||
marshalFn = marshalInetAddr
|
||||
}
|
||||
if err := hs.pack(ms, nil, marshalFn); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var operr error
|
||||
var n int
|
||||
fn := func(s uintptr) bool {
|
||||
n, operr = sendmmsg(s, hs, flags)
|
||||
if operr == syscall.EAGAIN {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if err := c.c.Write(fn); err != nil {
|
||||
return n, err
|
||||
}
|
||||
if operr != nil {
|
||||
return n, os.NewSyscallError("sendmmsg", operr)
|
||||
}
|
||||
if err := hs[:n].unpack(ms[:n], nil, ""); err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.9
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris windows
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func (c *Conn) recvMsg(m *Message, flags int) error {
|
||||
var h msghdr
|
||||
vs := make([]iovec, len(m.Buffers))
|
||||
var sa []byte
|
||||
if c.network != "tcp" {
|
||||
sa = make([]byte, sizeofSockaddrInet6)
|
||||
}
|
||||
h.pack(vs, m.Buffers, m.OOB, sa)
|
||||
var operr error
|
||||
var n int
|
||||
fn := func(s uintptr) bool {
|
||||
n, operr = recvmsg(s, &h, flags)
|
||||
if operr == syscall.EAGAIN {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if err := c.c.Read(fn); err != nil {
|
||||
return err
|
||||
}
|
||||
if operr != nil {
|
||||
return os.NewSyscallError("recvmsg", operr)
|
||||
}
|
||||
if c.network != "tcp" {
|
||||
var err error
|
||||
m.Addr, err = parseInetAddr(sa[:], c.network)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
m.N = n
|
||||
m.NN = h.controllen()
|
||||
m.Flags = h.flags()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) sendMsg(m *Message, flags int) error {
|
||||
var h msghdr
|
||||
vs := make([]iovec, len(m.Buffers))
|
||||
var sa []byte
|
||||
if m.Addr != nil {
|
||||
sa = marshalInetAddr(m.Addr)
|
||||
}
|
||||
h.pack(vs, m.Buffers, m.OOB, sa)
|
||||
var operr error
|
||||
var n int
|
||||
fn := func(s uintptr) bool {
|
||||
n, operr = sendmsg(s, &h, flags)
|
||||
if operr == syscall.EAGAIN {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if err := c.c.Write(fn); err != nil {
|
||||
return err
|
||||
}
|
||||
if operr != nil {
|
||||
return os.NewSyscallError("sendmsg", operr)
|
||||
}
|
||||
m.N = n
|
||||
m.NN = len(m.OOB)
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.9
|
||||
// +build !linux
|
||||
|
||||
package socket
|
||||
|
||||
import "errors"
|
||||
|
||||
func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.9
|
||||
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows
|
||||
|
||||
package socket
|
||||
|
||||
import "errors"
|
||||
|
||||
func (c *Conn) recvMsg(m *Message, flags int) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (c *Conn) sendMsg(m *Message, flags int) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !go1.9
|
||||
|
||||
package socket
|
||||
|
||||
import "errors"
|
||||
|
||||
func (c *Conn) recvMsg(m *Message, flags int) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (c *Conn) sendMsg(m *Message, flags int) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !go1.9
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// A Conn represents a raw connection.
|
||||
type Conn struct {
|
||||
c net.Conn
|
||||
}
|
||||
|
||||
// NewConn returns a new raw connection.
|
||||
func NewConn(c net.Conn) (*Conn, error) {
|
||||
return &Conn{c: c}, nil
|
||||
}
|
||||
|
||||
func (o *Option) get(c *Conn, b []byte) (int, error) {
|
||||
s, err := socketOf(c.c)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, err := getsockopt(s, o.Level, o.Name, b)
|
||||
return n, os.NewSyscallError("getsockopt", err)
|
||||
}
|
||||
|
||||
func (o *Option) set(c *Conn, b []byte) error {
|
||||
s, err := socketOf(c.c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.NewSyscallError("setsockopt", setsockopt(s, o.Level, o.Name, b))
|
||||
}
|
||||
|
||||
func socketOf(c net.Conn) (uintptr, error) {
|
||||
switch c.(type) {
|
||||
case *net.TCPConn, *net.UDPConn, *net.IPConn:
|
||||
v := reflect.ValueOf(c)
|
||||
switch e := v.Elem(); e.Kind() {
|
||||
case reflect.Struct:
|
||||
fd := e.FieldByName("conn").FieldByName("fd")
|
||||
switch e := fd.Elem(); e.Kind() {
|
||||
case reflect.Struct:
|
||||
sysfd := e.FieldByName("sysfd")
|
||||
if runtime.GOOS == "windows" {
|
||||
return uintptr(sysfd.Uint()), nil
|
||||
}
|
||||
return uintptr(sysfd.Int()), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, errors.New("invalid type")
|
||||
}
|
|
@ -0,0 +1,285 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package socket provides a portable interface for socket system
|
||||
// calls.
|
||||
package socket // import "golang.org/x/net/internal/socket"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// An Option represents a sticky socket option.
|
||||
type Option struct {
|
||||
Level int // level
|
||||
Name int // name; must be equal or greater than 1
|
||||
Len int // length of value in bytes; must be equal or greater than 1
|
||||
}
|
||||
|
||||
// Get reads a value for the option from the kernel.
|
||||
// It returns the number of bytes written into b.
|
||||
func (o *Option) Get(c *Conn, b []byte) (int, error) {
|
||||
if o.Name < 1 || o.Len < 1 {
|
||||
return 0, errors.New("invalid option")
|
||||
}
|
||||
if len(b) < o.Len {
|
||||
return 0, errors.New("short buffer")
|
||||
}
|
||||
return o.get(c, b)
|
||||
}
|
||||
|
||||
// GetInt returns an integer value for the option.
|
||||
//
|
||||
// The Len field of Option must be either 1 or 4.
|
||||
func (o *Option) GetInt(c *Conn) (int, error) {
|
||||
if o.Len != 1 && o.Len != 4 {
|
||||
return 0, errors.New("invalid option")
|
||||
}
|
||||
var b []byte
|
||||
var bb [4]byte
|
||||
if o.Len == 1 {
|
||||
b = bb[:1]
|
||||
} else {
|
||||
b = bb[:4]
|
||||
}
|
||||
n, err := o.get(c, b)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if n != o.Len {
|
||||
return 0, errors.New("invalid option length")
|
||||
}
|
||||
if o.Len == 1 {
|
||||
return int(b[0]), nil
|
||||
}
|
||||
return int(NativeEndian.Uint32(b[:4])), nil
|
||||
}
|
||||
|
||||
// Set writes the option and value to the kernel.
|
||||
func (o *Option) Set(c *Conn, b []byte) error {
|
||||
if o.Name < 1 || o.Len < 1 {
|
||||
return errors.New("invalid option")
|
||||
}
|
||||
if len(b) < o.Len {
|
||||
return errors.New("short buffer")
|
||||
}
|
||||
return o.set(c, b)
|
||||
}
|
||||
|
||||
// SetInt writes the option and value to the kernel.
|
||||
//
|
||||
// The Len field of Option must be either 1 or 4.
|
||||
func (o *Option) SetInt(c *Conn, v int) error {
|
||||
if o.Len != 1 && o.Len != 4 {
|
||||
return errors.New("invalid option")
|
||||
}
|
||||
var b []byte
|
||||
if o.Len == 1 {
|
||||
b = []byte{byte(v)}
|
||||
} else {
|
||||
var bb [4]byte
|
||||
NativeEndian.PutUint32(bb[:o.Len], uint32(v))
|
||||
b = bb[:4]
|
||||
}
|
||||
return o.set(c, b)
|
||||
}
|
||||
|
||||
func controlHeaderLen() int {
|
||||
return roundup(sizeofCmsghdr)
|
||||
}
|
||||
|
||||
func controlMessageLen(dataLen int) int {
|
||||
return roundup(sizeofCmsghdr) + dataLen
|
||||
}
|
||||
|
||||
// ControlMessageSpace returns the whole length of control message.
|
||||
func ControlMessageSpace(dataLen int) int {
|
||||
return roundup(sizeofCmsghdr) + roundup(dataLen)
|
||||
}
|
||||
|
||||
// A ControlMessage represents the head message in a stream of control
|
||||
// messages.
|
||||
//
|
||||
// A control message comprises of a header, data and a few padding
|
||||
// fields to conform to the interface to the kernel.
|
||||
//
|
||||
// See RFC 3542 for further information.
|
||||
type ControlMessage []byte
|
||||
|
||||
// Data returns the data field of the control message at the head on
|
||||
// m.
|
||||
func (m ControlMessage) Data(dataLen int) []byte {
|
||||
l := controlHeaderLen()
|
||||
if len(m) < l || len(m) < l+dataLen {
|
||||
return nil
|
||||
}
|
||||
return m[l : l+dataLen]
|
||||
}
|
||||
|
||||
// Next returns the control message at the next on m.
|
||||
//
|
||||
// Next works only for standard control messages.
|
||||
func (m ControlMessage) Next(dataLen int) ControlMessage {
|
||||
l := ControlMessageSpace(dataLen)
|
||||
if len(m) < l {
|
||||
return nil
|
||||
}
|
||||
return m[l:]
|
||||
}
|
||||
|
||||
// MarshalHeader marshals the header fields of the control message at
|
||||
// the head on m.
|
||||
func (m ControlMessage) MarshalHeader(lvl, typ, dataLen int) error {
|
||||
if len(m) < controlHeaderLen() {
|
||||
return errors.New("short message")
|
||||
}
|
||||
h := (*cmsghdr)(unsafe.Pointer(&m[0]))
|
||||
h.set(controlMessageLen(dataLen), lvl, typ)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseHeader parses and returns the header fields of the control
|
||||
// message at the head on m.
|
||||
func (m ControlMessage) ParseHeader() (lvl, typ, dataLen int, err error) {
|
||||
l := controlHeaderLen()
|
||||
if len(m) < l {
|
||||
return 0, 0, 0, errors.New("short message")
|
||||
}
|
||||
h := (*cmsghdr)(unsafe.Pointer(&m[0]))
|
||||
return h.lvl(), h.typ(), int(uint64(h.len()) - uint64(l)), nil
|
||||
}
|
||||
|
||||
// Marshal marshals the control message at the head on m, and returns
|
||||
// the next control message.
|
||||
func (m ControlMessage) Marshal(lvl, typ int, data []byte) (ControlMessage, error) {
|
||||
l := len(data)
|
||||
if len(m) < ControlMessageSpace(l) {
|
||||
return nil, errors.New("short message")
|
||||
}
|
||||
h := (*cmsghdr)(unsafe.Pointer(&m[0]))
|
||||
h.set(controlMessageLen(l), lvl, typ)
|
||||
if l > 0 {
|
||||
copy(m.Data(l), data)
|
||||
}
|
||||
return m.Next(l), nil
|
||||
}
|
||||
|
||||
// Parse parses m as a single or multiple control messages.
|
||||
//
|
||||
// Parse works for both standard and compatible messages.
|
||||
func (m ControlMessage) Parse() ([]ControlMessage, error) {
|
||||
var ms []ControlMessage
|
||||
for len(m) >= controlHeaderLen() {
|
||||
h := (*cmsghdr)(unsafe.Pointer(&m[0]))
|
||||
l := h.len()
|
||||
if l <= 0 {
|
||||
return nil, errors.New("invalid header length")
|
||||
}
|
||||
if uint64(l) < uint64(controlHeaderLen()) {
|
||||
return nil, errors.New("invalid message length")
|
||||
}
|
||||
if uint64(l) > uint64(len(m)) {
|
||||
return nil, errors.New("short buffer")
|
||||
}
|
||||
// On message reception:
|
||||
//
|
||||
// |<- ControlMessageSpace --------------->|
|
||||
// |<- controlMessageLen ---------->| |
|
||||
// |<- controlHeaderLen ->| | |
|
||||
// +---------------+------+---------+------+
|
||||
// | Header | PadH | Data | PadD |
|
||||
// +---------------+------+---------+------+
|
||||
//
|
||||
// On compatible message reception:
|
||||
//
|
||||
// | ... |<- controlMessageLen ----------->|
|
||||
// | ... |<- controlHeaderLen ->| |
|
||||
// +-----+---------------+------+----------+
|
||||
// | ... | Header | PadH | Data |
|
||||
// +-----+---------------+------+----------+
|
||||
ms = append(ms, ControlMessage(m[:l]))
|
||||
ll := l - controlHeaderLen()
|
||||
if len(m) >= ControlMessageSpace(ll) {
|
||||
m = m[ControlMessageSpace(ll):]
|
||||
} else {
|
||||
m = m[controlMessageLen(ll):]
|
||||
}
|
||||
}
|
||||
return ms, nil
|
||||
}
|
||||
|
||||
// NewControlMessage returns a new stream of control messages.
|
||||
func NewControlMessage(dataLen []int) ControlMessage {
|
||||
var l int
|
||||
for i := range dataLen {
|
||||
l += ControlMessageSpace(dataLen[i])
|
||||
}
|
||||
return make([]byte, l)
|
||||
}
|
||||
|
||||
// A Message represents an IO message.
|
||||
type Message struct {
|
||||
// When writing, the Buffers field must contain at least one
|
||||
// byte to write.
|
||||
// When reading, the Buffers field will always contain a byte
|
||||
// to read.
|
||||
Buffers [][]byte
|
||||
|
||||
// OOB contains protocol-specific control or miscellaneous
|
||||
// ancillary data known as out-of-band data.
|
||||
OOB []byte
|
||||
|
||||
// Addr specifies a destination address when writing.
|
||||
// It can be nil when the underlying protocol of the raw
|
||||
// connection uses connection-oriented communication.
|
||||
// After a successful read, it may contain the source address
|
||||
// on the received packet.
|
||||
Addr net.Addr
|
||||
|
||||
N int // # of bytes read or written from/to Buffers
|
||||
NN int // # of bytes read or written from/to OOB
|
||||
Flags int // protocol-specific information on the received message
|
||||
}
|
||||
|
||||
// RecvMsg wraps recvmsg system call.
|
||||
//
|
||||
// The provided flags is a set of platform-dependent flags, such as
|
||||
// syscall.MSG_PEEK.
|
||||
func (c *Conn) RecvMsg(m *Message, flags int) error {
|
||||
return c.recvMsg(m, flags)
|
||||
}
|
||||
|
||||
// SendMsg wraps sendmsg system call.
|
||||
//
|
||||
// The provided flags is a set of platform-dependent flags, such as
|
||||
// syscall.MSG_DONTROUTE.
|
||||
func (c *Conn) SendMsg(m *Message, flags int) error {
|
||||
return c.sendMsg(m, flags)
|
||||
}
|
||||
|
||||
// RecvMsgs wraps recvmmsg system call.
|
||||
//
|
||||
// It returns the number of processed messages.
|
||||
//
|
||||
// The provided flags is a set of platform-dependent flags, such as
|
||||
// syscall.MSG_PEEK.
|
||||
//
|
||||
// Only Linux supports this.
|
||||
func (c *Conn) RecvMsgs(ms []Message, flags int) (int, error) {
|
||||
return c.recvMsgs(ms, flags)
|
||||
}
|
||||
|
||||
// SendMsgs wraps sendmmsg system call.
|
||||
//
|
||||
// It returns the number of processed messages.
|
||||
//
|
||||
// The provided flags is a set of platform-dependent flags, such as
|
||||
// syscall.MSG_DONTROUTE.
|
||||
//
|
||||
// Only Linux supports this.
|
||||
func (c *Conn) SendMsgs(ms []Message, flags int) (int, error) {
|
||||
return c.sendMsgs(ms, flags)
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
// NativeEndian is the machine native endian implementation of
|
||||
// ByteOrder.
|
||||
NativeEndian binary.ByteOrder
|
||||
|
||||
kernelAlign int
|
||||
)
|
||||
|
||||
func init() {
|
||||
i := uint32(1)
|
||||
b := (*[4]byte)(unsafe.Pointer(&i))
|
||||
if b[0] == 1 {
|
||||
NativeEndian = binary.LittleEndian
|
||||
} else {
|
||||
NativeEndian = binary.BigEndian
|
||||
}
|
||||
kernelAlign = probeProtocolStack()
|
||||
}
|
||||
|
||||
func roundup(l int) int {
|
||||
return (l + kernelAlign - 1) & ^(kernelAlign - 1)
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd openbsd
|
||||
|
||||
package socket
|
||||
|
||||
import "errors"
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build freebsd netbsd openbsd
|
||||
|
||||
package socket
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func probeProtocolStack() int {
|
||||
var p uintptr
|
||||
return int(unsafe.Sizeof(p))
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
func probeProtocolStack() int { return 4 }
|
|
@ -0,0 +1,7 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
func probeProtocolStack() int { return 4 }
|
|
@ -0,0 +1,27 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build linux,!s390x,!386
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func probeProtocolStack() int {
|
||||
var p uintptr
|
||||
return int(unsafe.Sizeof(p))
|
||||
}
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, _, errno := syscall.Syscall6(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, _, errno := syscall.Syscall6(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func probeProtocolStack() int { return 4 }
|
||||
|
||||
const (
|
||||
sysSETSOCKOPT = 0xe
|
||||
sysGETSOCKOPT = 0xf
|
||||
sysSENDMSG = 0x10
|
||||
sysRECVMSG = 0x11
|
||||
sysRECVMMSG = 0x13
|
||||
sysSENDMMSG = 0x14
|
||||
)
|
||||
|
||||
func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno)
|
||||
func rawsocketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno)
|
||||
|
||||
func getsockopt(s uintptr, level, name int, b []byte) (int, error) {
|
||||
l := uint32(len(b))
|
||||
_, errno := socketcall(sysGETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0)
|
||||
return int(l), errnoErr(errno)
|
||||
}
|
||||
|
||||
func setsockopt(s uintptr, level, name int, b []byte) error {
|
||||
_, errno := socketcall(sysSETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0)
|
||||
return errnoErr(errno)
|
||||
}
|
||||
|
||||
func recvmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysRECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysSENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
TEXT ·socketcall(SB),NOSPLIT,$0-36
|
||||
JMP syscall·socketcall(SB)
|
||||
|
||||
TEXT ·rawsocketcall(SB),NOSPLIT,$0-36
|
||||
JMP syscall·rawsocketcall(SB)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x12b
|
||||
sysSENDMMSG = 0x133
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x16d
|
||||
sysSENDMMSG = 0x176
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0xf3
|
||||
sysSENDMMSG = 0x10d
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x10ef
|
||||
sysSENDMMSG = 0x10f7
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x14ae
|
||||
sysSENDMMSG = 0x14b6
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x14ae
|
||||
sysSENDMMSG = 0x14b6
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x10ef
|
||||
sysSENDMMSG = 0x10f7
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x157
|
||||
sysSENDMMSG = 0x15d
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x157
|
||||
sysSENDMMSG = 0x15d
|
||||
)
|
|
@ -0,0 +1,55 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func probeProtocolStack() int { return 8 }
|
||||
|
||||
const (
|
||||
sysSETSOCKOPT = 0xe
|
||||
sysGETSOCKOPT = 0xf
|
||||
sysSENDMSG = 0x10
|
||||
sysRECVMSG = 0x11
|
||||
sysRECVMMSG = 0x13
|
||||
sysSENDMMSG = 0x14
|
||||
)
|
||||
|
||||
func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno)
|
||||
func rawsocketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno)
|
||||
|
||||
func getsockopt(s uintptr, level, name int, b []byte) (int, error) {
|
||||
l := uint32(len(b))
|
||||
_, errno := socketcall(sysGETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0)
|
||||
return int(l), errnoErr(errno)
|
||||
}
|
||||
|
||||
func setsockopt(s uintptr, level, name int, b []byte) error {
|
||||
_, errno := socketcall(sysSETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0)
|
||||
return errnoErr(errno)
|
||||
}
|
||||
|
||||
func recvmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysRECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysSENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, errno := socketcall(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
TEXT ·socketcall(SB),NOSPLIT,$0-72
|
||||
JMP syscall·socketcall(SB)
|
||||
|
||||
TEXT ·rawsocketcall(SB),NOSPLIT,$0-72
|
||||
JMP syscall·rawsocketcall(SB)
|
|
@ -0,0 +1,25 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
sysRECVMMSG = 0x1db
|
||||
sysSENDMMSG = 0x1dc
|
||||
)
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, _, errno := syscall.Syscall6(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
n, _, errno := syscall.Syscall6(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
|
@ -0,0 +1,168 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build go1.9
|
||||
// +build darwin dragonfly freebsd linux netbsd openbsd solaris windows
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"net"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func marshalInetAddr(a net.Addr) []byte {
|
||||
switch a := a.(type) {
|
||||
case *net.TCPAddr:
|
||||
return marshalSockaddr(a.IP, a.Port, a.Zone)
|
||||
case *net.UDPAddr:
|
||||
return marshalSockaddr(a.IP, a.Port, a.Zone)
|
||||
case *net.IPAddr:
|
||||
return marshalSockaddr(a.IP, 0, a.Zone)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func marshalSockaddr(ip net.IP, port int, zone string) []byte {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
b := make([]byte, sizeofSockaddrInet)
|
||||
switch runtime.GOOS {
|
||||
case "android", "linux", "solaris", "windows":
|
||||
NativeEndian.PutUint16(b[:2], uint16(sysAF_INET))
|
||||
default:
|
||||
b[0] = sizeofSockaddrInet
|
||||
b[1] = sysAF_INET
|
||||
}
|
||||
binary.BigEndian.PutUint16(b[2:4], uint16(port))
|
||||
copy(b[4:8], ip4)
|
||||
return b
|
||||
}
|
||||
if ip6 := ip.To16(); ip6 != nil && ip.To4() == nil {
|
||||
b := make([]byte, sizeofSockaddrInet6)
|
||||
switch runtime.GOOS {
|
||||
case "android", "linux", "solaris", "windows":
|
||||
NativeEndian.PutUint16(b[:2], uint16(sysAF_INET6))
|
||||
default:
|
||||
b[0] = sizeofSockaddrInet6
|
||||
b[1] = sysAF_INET6
|
||||
}
|
||||
binary.BigEndian.PutUint16(b[2:4], uint16(port))
|
||||
copy(b[8:24], ip6)
|
||||
if zone != "" {
|
||||
NativeEndian.PutUint32(b[24:28], uint32(zoneCache.index(zone)))
|
||||
}
|
||||
return b
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseInetAddr(b []byte, network string) (net.Addr, error) {
|
||||
if len(b) < 2 {
|
||||
return nil, errors.New("invalid address")
|
||||
}
|
||||
var af int
|
||||
switch runtime.GOOS {
|
||||
case "android", "linux", "solaris", "windows":
|
||||
af = int(NativeEndian.Uint16(b[:2]))
|
||||
default:
|
||||
af = int(b[1])
|
||||
}
|
||||
var ip net.IP
|
||||
var zone string
|
||||
if af == sysAF_INET {
|
||||
if len(b) < sizeofSockaddrInet {
|
||||
return nil, errors.New("short address")
|
||||
}
|
||||
ip = make(net.IP, net.IPv4len)
|
||||
copy(ip, b[4:8])
|
||||
}
|
||||
if af == sysAF_INET6 {
|
||||
if len(b) < sizeofSockaddrInet6 {
|
||||
return nil, errors.New("short address")
|
||||
}
|
||||
ip = make(net.IP, net.IPv6len)
|
||||
copy(ip, b[8:24])
|
||||
if id := int(NativeEndian.Uint32(b[24:28])); id > 0 {
|
||||
zone = zoneCache.name(id)
|
||||
}
|
||||
}
|
||||
switch network {
|
||||
case "tcp", "tcp4", "tcp6":
|
||||
return &net.TCPAddr{IP: ip, Port: int(binary.BigEndian.Uint16(b[2:4])), Zone: zone}, nil
|
||||
case "udp", "udp4", "udp6":
|
||||
return &net.UDPAddr{IP: ip, Port: int(binary.BigEndian.Uint16(b[2:4])), Zone: zone}, nil
|
||||
default:
|
||||
return &net.IPAddr{IP: ip, Zone: zone}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// An ipv6ZoneCache represents a cache holding partial network
|
||||
// interface information. It is used for reducing the cost of IPv6
|
||||
// addressing scope zone resolution.
|
||||
//
|
||||
// Multiple names sharing the index are managed by first-come
|
||||
// first-served basis for consistency.
|
||||
type ipv6ZoneCache struct {
|
||||
sync.RWMutex // guard the following
|
||||
lastFetched time.Time // last time routing information was fetched
|
||||
toIndex map[string]int // interface name to its index
|
||||
toName map[int]string // interface index to its name
|
||||
}
|
||||
|
||||
var zoneCache = ipv6ZoneCache{
|
||||
toIndex: make(map[string]int),
|
||||
toName: make(map[int]string),
|
||||
}
|
||||
|
||||
func (zc *ipv6ZoneCache) update(ift []net.Interface) {
|
||||
zc.Lock()
|
||||
defer zc.Unlock()
|
||||
now := time.Now()
|
||||
if zc.lastFetched.After(now.Add(-60 * time.Second)) {
|
||||
return
|
||||
}
|
||||
zc.lastFetched = now
|
||||
if len(ift) == 0 {
|
||||
var err error
|
||||
if ift, err = net.Interfaces(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
zc.toIndex = make(map[string]int, len(ift))
|
||||
zc.toName = make(map[int]string, len(ift))
|
||||
for _, ifi := range ift {
|
||||
zc.toIndex[ifi.Name] = ifi.Index
|
||||
if _, ok := zc.toName[ifi.Index]; !ok {
|
||||
zc.toName[ifi.Index] = ifi.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (zc *ipv6ZoneCache) name(zone int) string {
|
||||
zoneCache.update(nil)
|
||||
zoneCache.RLock()
|
||||
defer zoneCache.RUnlock()
|
||||
name, ok := zoneCache.toName[zone]
|
||||
if !ok {
|
||||
name = strconv.Itoa(zone)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func (zc *ipv6ZoneCache) index(zone string) int {
|
||||
zoneCache.update(nil)
|
||||
zoneCache.RLock()
|
||||
defer zoneCache.RUnlock()
|
||||
index, ok := zoneCache.toIndex[zone]
|
||||
if !ok {
|
||||
index, _ = strconv.Atoi(zone)
|
||||
}
|
||||
return index
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func probeProtocolStack() int {
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return 4
|
||||
default:
|
||||
var p uintptr
|
||||
return int(unsafe.Sizeof(p))
|
||||
}
|
||||
}
|
||||
|
||||
//go:cgo_import_dynamic libc___xnet_getsockopt __xnet_getsockopt "libsocket.so"
|
||||
//go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so"
|
||||
//go:cgo_import_dynamic libc___xnet_recvmsg __xnet_recvmsg "libsocket.so"
|
||||
//go:cgo_import_dynamic libc___xnet_sendmsg __xnet_sendmsg "libsocket.so"
|
||||
|
||||
//go:linkname procGetsockopt libc___xnet_getsockopt
|
||||
//go:linkname procSetsockopt libc_setsockopt
|
||||
//go:linkname procRecvmsg libc___xnet_recvmsg
|
||||
//go:linkname procSendmsg libc___xnet_sendmsg
|
||||
|
||||
var (
|
||||
procGetsockopt uintptr
|
||||
procSetsockopt uintptr
|
||||
procRecvmsg uintptr
|
||||
procSendmsg uintptr
|
||||
)
|
||||
|
||||
func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (uintptr, uintptr, syscall.Errno)
|
||||
func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (uintptr, uintptr, syscall.Errno)
|
||||
|
||||
func getsockopt(s uintptr, level, name int, b []byte) (int, error) {
|
||||
l := uint32(len(b))
|
||||
_, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procGetsockopt)), 5, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0)
|
||||
return int(l), errnoErr(errno)
|
||||
}
|
||||
|
||||
func setsockopt(s uintptr, level, name int, b []byte) error {
|
||||
_, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procSetsockopt)), 5, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0)
|
||||
return errnoErr(errno)
|
||||
}
|
||||
|
||||
func recvmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procRecvmsg)), 3, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procSendmsg)), 3, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0)
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
#include "textflag.h"
|
||||
|
||||
TEXT ·sysvicall6(SB),NOSPLIT,$0-88
|
||||
JMP syscall·sysvicall6(SB)
|
||||
|
||||
TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88
|
||||
JMP syscall·rawSysvicall6(SB)
|
|
@ -0,0 +1,64 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"runtime"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0xa
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
func probeProtocolStack() int {
|
||||
switch runtime.GOARCH {
|
||||
case "amd64p32", "mips64p32":
|
||||
return 4
|
||||
default:
|
||||
var p uintptr
|
||||
return int(unsafe.Sizeof(p))
|
||||
}
|
||||
}
|
||||
|
||||
func marshalInetAddr(ip net.IP, port int, zone string) []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseInetAddr(b []byte, network string) (net.Addr, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func getsockopt(s uintptr, level, name int, b []byte) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func setsockopt(s uintptr, level, name int, b []byte) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func recvmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func sendmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build darwin dragonfly freebsd linux,!s390x,!386 netbsd openbsd
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func getsockopt(s uintptr, level, name int, b []byte) (int, error) {
|
||||
l := uint32(len(b))
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0)
|
||||
return int(l), errnoErr(errno)
|
||||
}
|
||||
|
||||
func setsockopt(s uintptr, level, name int, b []byte) error {
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS_SETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0)
|
||||
return errnoErr(errno)
|
||||
}
|
||||
|
||||
func recvmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, _, errno := syscall.Syscall(syscall.SYS_RECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags))
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
||||
|
||||
func sendmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
n, _, errno := syscall.Syscall(syscall.SYS_SENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags))
|
||||
return int(n), errnoErr(errno)
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socket
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func probeProtocolStack() int {
|
||||
var p uintptr
|
||||
return int(unsafe.Sizeof(p))
|
||||
}
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x17
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type sockaddrInet struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]uint8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
||||
|
||||
func getsockopt(s uintptr, level, name int, b []byte) (int, error) {
|
||||
l := uint32(len(b))
|
||||
err := syscall.Getsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(unsafe.Pointer(&b[0])), (*int32)(unsafe.Pointer(&l)))
|
||||
return int(l), err
|
||||
}
|
||||
|
||||
func setsockopt(s uintptr, level, name int, b []byte) error {
|
||||
return syscall.Setsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(unsafe.Pointer(&b[0])), int32(len(b)))
|
||||
}
|
||||
|
||||
func recvmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func sendmsg(s uintptr, h *msghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) {
|
||||
return 0, errors.New("not implemented")
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_darwin.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1e
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x8
|
||||
sizeofMsghdr = 0x1c
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,61 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_darwin.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1e
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint64
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Pad_cgo_1 [4]byte
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x10
|
||||
sizeofMsghdr = 0x30
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,59 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_darwin.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1e
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x8
|
||||
sizeofMsghdr = 0x1c
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,61 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_darwin.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1e
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint64
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Pad_cgo_1 [4]byte
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x10
|
||||
sizeofMsghdr = 0x30
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,61 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_dragonfly.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1c
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint64
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Pad_cgo_1 [4]byte
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x10
|
||||
sizeofMsghdr = 0x30
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,59 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_freebsd.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1c
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x8
|
||||
sizeofMsghdr = 0x1c
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,61 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_freebsd.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1c
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint64
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Pad_cgo_1 [4]byte
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x10
|
||||
sizeofMsghdr = 0x30
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,59 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_freebsd.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0x1c
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Iov *iovec
|
||||
Iovlen int32
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
Zero [8]int8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Len uint8
|
||||
Family uint8
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x8
|
||||
sizeofMsghdr = 0x1c
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,63 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_linux.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0xa
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Iov *iovec
|
||||
Iovlen uint32
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type mmsghdr struct {
|
||||
Hdr msghdr
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
X__pad [8]uint8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x8
|
||||
sizeofMsghdr = 0x1c
|
||||
sizeofMmsghdr = 0x20
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,66 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_linux.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0xa
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint64
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
Iov *iovec
|
||||
Iovlen uint64
|
||||
Control *byte
|
||||
Controllen uint64
|
||||
Flags int32
|
||||
Pad_cgo_1 [4]byte
|
||||
}
|
||||
|
||||
type mmsghdr struct {
|
||||
Hdr msghdr
|
||||
Len uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint64
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
X__pad [8]uint8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x10
|
||||
sizeofMsghdr = 0x38
|
||||
sizeofMmsghdr = 0x40
|
||||
sizeofCmsghdr = 0x10
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,63 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_linux.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0xa
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Iov *iovec
|
||||
Iovlen uint32
|
||||
Control *byte
|
||||
Controllen uint32
|
||||
Flags int32
|
||||
}
|
||||
|
||||
type mmsghdr struct {
|
||||
Hdr msghdr
|
||||
Len uint32
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint32
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
X__pad [8]uint8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x8
|
||||
sizeofMsghdr = 0x1c
|
||||
sizeofMmsghdr = 0x20
|
||||
sizeofCmsghdr = 0xc
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
|
@ -0,0 +1,66 @@
|
|||
// Created by cgo -godefs - DO NOT EDIT
|
||||
// cgo -godefs defs_linux.go
|
||||
|
||||
package socket
|
||||
|
||||
const (
|
||||
sysAF_UNSPEC = 0x0
|
||||
sysAF_INET = 0x2
|
||||
sysAF_INET6 = 0xa
|
||||
|
||||
sysSOCK_RAW = 0x3
|
||||
)
|
||||
|
||||
type iovec struct {
|
||||
Base *byte
|
||||
Len uint64
|
||||
}
|
||||
|
||||
type msghdr struct {
|
||||
Name *byte
|
||||
Namelen uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
Iov *iovec
|
||||
Iovlen uint64
|
||||
Control *byte
|
||||
Controllen uint64
|
||||
Flags int32
|
||||
Pad_cgo_1 [4]byte
|
||||
}
|
||||
|
||||
type mmsghdr struct {
|
||||
Hdr msghdr
|
||||
Len uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
}
|
||||
|
||||
type cmsghdr struct {
|
||||
Len uint64
|
||||
Level int32
|
||||
Type int32
|
||||
}
|
||||
|
||||
type sockaddrInet struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Addr [4]byte /* in_addr */
|
||||
X__pad [8]uint8
|
||||
}
|
||||
|
||||
type sockaddrInet6 struct {
|
||||
Family uint16
|
||||
Port uint16
|
||||
Flowinfo uint32
|
||||
Addr [16]byte /* in6_addr */
|
||||
Scope_id uint32
|
||||
}
|
||||
|
||||
const (
|
||||
sizeofIovec = 0x10
|
||||
sizeofMsghdr = 0x38
|
||||
sizeofMmsghdr = 0x40
|
||||
sizeofCmsghdr = 0x10
|
||||
|
||||
sizeofSockaddrInet = 0x10
|
||||
sizeofSockaddrInet6 = 0x1c
|
||||
)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue