Merge pull request #32 from coreos/grpc-api

Add gRPC service for interacting with storages
This commit is contained in:
Eric Chiang
2016-07-31 23:27:53 -07:00
committed by GitHub
177 changed files with 39648 additions and 9230 deletions
+11 -3
View File
@@ -1,6 +1,7 @@
PROJ="poke"
ORG_PATH="github.com/coreos"
REPO_PATH="$(ORG_PATH)/$(PROJ)"
export PATH := $(PWD)/bin:$(PATH)
export GOBIN=$(PWD)/bin
export GO15VENDOREXPERIMENT=1
@@ -41,15 +42,22 @@ fmt:
@go fmt $(shell go list ./... | grep -v '/vendor/')
lint:
@for package in $(shell go list ./... | grep -v '/vendor/'); do \
@for package in $(shell go list ./... | grep -v '/vendor/' | grep -v 'api/apipb'); do \
golint $$package; \
done
# TODO(ericchiang): Grab protoc as well.
grpc: bin/protoc-gen-go
@protoc --go_out=plugins=grpc:. ./api/apipb/*.proto
bin/protoc-gen-go:
@go install ${REPO_PATH}/vendor/github.com/golang/protobuf/protoc-gen-go
clean:
rm bin/poke bin/pokectl
@rm bin/*
testall: testrace vet fmt lint
FORCE:
.PHONY: test testrace vet fmt lint testall
.PHONY: test testrace vet fmt lint testall grpc
+136
View File
@@ -0,0 +1,136 @@
package api
import (
"errors"
"golang.org/x/net/context"
"github.com/coreos/poke/api/apipb"
"github.com/coreos/poke/storage"
)
// NewServer returns a gRPC server for talking to a storage.
func NewServer(s storage.Storage) apipb.StorageServer {
return &server{s}
}
type server struct {
storage storage.Storage
}
func fromPBClient(client *apipb.Client) storage.Client {
return storage.Client{
ID: client.Id,
Secret: client.Secret,
RedirectURIs: client.RedirectUris,
TrustedPeers: client.TrustedPeers,
Public: client.Public,
Name: client.Name,
LogoURL: client.LogoUrl,
}
}
func toPBClient(client storage.Client) *apipb.Client {
return &apipb.Client{
Id: client.ID,
Secret: client.Secret,
RedirectUris: client.RedirectURIs,
TrustedPeers: client.TrustedPeers,
Public: client.Public,
Name: client.Name,
LogoUrl: client.LogoURL,
}
}
func (s *server) CreateClient(ctx context.Context, req *apipb.CreateClientReq) (*apipb.CreateClientResp, error) {
// TODO(ericchiang): Create a more centralized strategy for creating client IDs
// and secrets which are restricted based on the storage.
client := fromPBClient(req.Client)
if client.ID == "" {
client.ID = storage.NewNonce()
}
if client.Secret == "" {
client.Secret = storage.NewNonce() + storage.NewNonce()
}
if err := s.storage.CreateClient(client); err != nil {
return nil, err
}
return &apipb.CreateClientResp{Client: toPBClient(client)}, nil
}
func (s *server) UpdateClient(ctx context.Context, req *apipb.UpdateClientReq) (*apipb.UpdateClientResp, error) {
switch {
case req.Id == "":
return nil, errors.New("no ID supplied")
case req.MakePublic && req.MakePrivate:
return nil, errors.New("cannot both make public and private")
case req.MakePublic && len(req.RedirectUris) != 0:
return nil, errors.New("redirect uris supplied for a public client")
}
var client *storage.Client
updater := func(old storage.Client) (storage.Client, error) {
if req.MakePublic {
old.Public = true
}
if req.MakePrivate {
old.Public = false
}
if req.Secret != "" {
old.Secret = req.Secret
}
if req.Name != "" {
old.Name = req.Name
}
if req.LogoUrl != "" {
old.LogoURL = req.LogoUrl
}
if len(req.RedirectUris) != 0 {
if old.Public {
return old, errors.New("public clients cannot have redirect URIs")
}
old.RedirectURIs = req.RedirectUris
}
client = &old
return old, nil
}
if err := s.storage.UpdateClient(req.Id, updater); err != nil {
return nil, err
}
return &apipb.UpdateClientResp{Client: toPBClient(*client)}, nil
}
func (s *server) DeleteClient(ctx context.Context, req *apipb.DeleteClientReq) (*apipb.DeleteClientReq, error) {
if req.Id == "" {
return nil, errors.New("no client ID supplied")
}
if err := s.storage.DeleteClient(req.Id); err != nil {
return nil, err
}
return &apipb.DeleteClientReq{}, nil
}
func (s *server) ListClients(ctx context.Context, req *apipb.ListClientsReq) (*apipb.ListClientsResp, error) {
clients, err := s.storage.ListClients()
if err != nil {
return nil, err
}
resp := make([]*apipb.Client, len(clients))
for i, client := range clients {
resp[i] = toPBClient(client)
}
return &apipb.ListClientsResp{Clients: resp}, nil
}
func (s *server) GetClient(ctx context.Context, req *apipb.GetClientReq) (*apipb.GetClientResp, error) {
if req.Id == "" {
return nil, errors.New("no client ID supplied")
}
client, err := s.storage.GetClient(req.Id)
if err != nil {
return nil, err
}
return &apipb.GetClientResp{Client: toPBClient(client)}, nil
}
+443
View File
@@ -0,0 +1,443 @@
// Code generated by protoc-gen-go.
// source: api/apipb/api.proto
// DO NOT EDIT!
/*
Package apipb is a generated protocol buffer package.
It is generated from these files:
api/apipb/api.proto
It has these top-level messages:
Client
CreateClientReq
CreateClientResp
UpdateClientReq
UpdateClientResp
ListClientsReq
ListClientsResp
DeleteClientReq
DeleteClientResp
GetClientReq
GetClientResp
*/
package apipb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type Client struct {
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Secret string `protobuf:"bytes,2,opt,name=secret" json:"secret,omitempty"`
RedirectUris []string `protobuf:"bytes,3,rep,name=redirect_uris,json=redirectUris" json:"redirect_uris,omitempty"`
TrustedPeers []string `protobuf:"bytes,4,rep,name=trusted_peers,json=trustedPeers" json:"trusted_peers,omitempty"`
Public bool `protobuf:"varint,5,opt,name=public" json:"public,omitempty"`
Name string `protobuf:"bytes,6,opt,name=name" json:"name,omitempty"`
LogoUrl string `protobuf:"bytes,7,opt,name=logo_url,json=logoUrl" json:"logo_url,omitempty"`
}
func (m *Client) Reset() { *m = Client{} }
func (m *Client) String() string { return proto.CompactTextString(m) }
func (*Client) ProtoMessage() {}
func (*Client) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
type CreateClientReq struct {
Client *Client `protobuf:"bytes,1,opt,name=client" json:"client,omitempty"`
}
func (m *CreateClientReq) Reset() { *m = CreateClientReq{} }
func (m *CreateClientReq) String() string { return proto.CompactTextString(m) }
func (*CreateClientReq) ProtoMessage() {}
func (*CreateClientReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *CreateClientReq) GetClient() *Client {
if m != nil {
return m.Client
}
return nil
}
type CreateClientResp struct {
Client *Client `protobuf:"bytes,1,opt,name=client" json:"client,omitempty"`
}
func (m *CreateClientResp) Reset() { *m = CreateClientResp{} }
func (m *CreateClientResp) String() string { return proto.CompactTextString(m) }
func (*CreateClientResp) ProtoMessage() {}
func (*CreateClientResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
func (m *CreateClientResp) GetClient() *Client {
if m != nil {
return m.Client
}
return nil
}
type UpdateClientReq struct {
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
// Empty strings indicate that string fields should not be updated.
Secret string `protobuf:"bytes,2,opt,name=secret" json:"secret,omitempty"`
Name string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"`
LogoUrl string `protobuf:"bytes,4,opt,name=logo_url,json=logoUrl" json:"logo_url,omitempty"`
MakePublic bool `protobuf:"varint,5,opt,name=make_public,json=makePublic" json:"make_public,omitempty"`
MakePrivate bool `protobuf:"varint,6,opt,name=make_private,json=makePrivate" json:"make_private,omitempty"`
// If no redirect URIs are specified, the current redirect URIs are preserved.
RedirectUris []string `protobuf:"bytes,7,rep,name=redirect_uris,json=redirectUris" json:"redirect_uris,omitempty"`
}
func (m *UpdateClientReq) Reset() { *m = UpdateClientReq{} }
func (m *UpdateClientReq) String() string { return proto.CompactTextString(m) }
func (*UpdateClientReq) ProtoMessage() {}
func (*UpdateClientReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
type UpdateClientResp struct {
Client *Client `protobuf:"bytes,1,opt,name=client" json:"client,omitempty"`
}
func (m *UpdateClientResp) Reset() { *m = UpdateClientResp{} }
func (m *UpdateClientResp) String() string { return proto.CompactTextString(m) }
func (*UpdateClientResp) ProtoMessage() {}
func (*UpdateClientResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
func (m *UpdateClientResp) GetClient() *Client {
if m != nil {
return m.Client
}
return nil
}
type ListClientsReq struct {
}
func (m *ListClientsReq) Reset() { *m = ListClientsReq{} }
func (m *ListClientsReq) String() string { return proto.CompactTextString(m) }
func (*ListClientsReq) ProtoMessage() {}
func (*ListClientsReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
type ListClientsResp struct {
Clients []*Client `protobuf:"bytes,1,rep,name=clients" json:"clients,omitempty"`
}
func (m *ListClientsResp) Reset() { *m = ListClientsResp{} }
func (m *ListClientsResp) String() string { return proto.CompactTextString(m) }
func (*ListClientsResp) ProtoMessage() {}
func (*ListClientsResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
func (m *ListClientsResp) GetClients() []*Client {
if m != nil {
return m.Clients
}
return nil
}
type DeleteClientReq struct {
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
}
func (m *DeleteClientReq) Reset() { *m = DeleteClientReq{} }
func (m *DeleteClientReq) String() string { return proto.CompactTextString(m) }
func (*DeleteClientReq) ProtoMessage() {}
func (*DeleteClientReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
type DeleteClientResp struct {
}
func (m *DeleteClientResp) Reset() { *m = DeleteClientResp{} }
func (m *DeleteClientResp) String() string { return proto.CompactTextString(m) }
func (*DeleteClientResp) ProtoMessage() {}
func (*DeleteClientResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
type GetClientReq struct {
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
}
func (m *GetClientReq) Reset() { *m = GetClientReq{} }
func (m *GetClientReq) String() string { return proto.CompactTextString(m) }
func (*GetClientReq) ProtoMessage() {}
func (*GetClientReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
type GetClientResp struct {
Client *Client `protobuf:"bytes,1,opt,name=client" json:"client,omitempty"`
}
func (m *GetClientResp) Reset() { *m = GetClientResp{} }
func (m *GetClientResp) String() string { return proto.CompactTextString(m) }
func (*GetClientResp) ProtoMessage() {}
func (*GetClientResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
func (m *GetClientResp) GetClient() *Client {
if m != nil {
return m.Client
}
return nil
}
func init() {
proto.RegisterType((*Client)(nil), "apipb.Client")
proto.RegisterType((*CreateClientReq)(nil), "apipb.CreateClientReq")
proto.RegisterType((*CreateClientResp)(nil), "apipb.CreateClientResp")
proto.RegisterType((*UpdateClientReq)(nil), "apipb.UpdateClientReq")
proto.RegisterType((*UpdateClientResp)(nil), "apipb.UpdateClientResp")
proto.RegisterType((*ListClientsReq)(nil), "apipb.ListClientsReq")
proto.RegisterType((*ListClientsResp)(nil), "apipb.ListClientsResp")
proto.RegisterType((*DeleteClientReq)(nil), "apipb.DeleteClientReq")
proto.RegisterType((*DeleteClientResp)(nil), "apipb.DeleteClientResp")
proto.RegisterType((*GetClientReq)(nil), "apipb.GetClientReq")
proto.RegisterType((*GetClientResp)(nil), "apipb.GetClientResp")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion3
// Client API for Storage service
type StorageClient interface {
GetClient(ctx context.Context, in *GetClientReq, opts ...grpc.CallOption) (*GetClientResp, error)
CreateClient(ctx context.Context, in *CreateClientReq, opts ...grpc.CallOption) (*CreateClientResp, error)
UpdateClient(ctx context.Context, in *UpdateClientReq, opts ...grpc.CallOption) (*UpdateClientResp, error)
DeleteClient(ctx context.Context, in *DeleteClientReq, opts ...grpc.CallOption) (*DeleteClientReq, error)
ListClients(ctx context.Context, in *ListClientsReq, opts ...grpc.CallOption) (*ListClientsResp, error)
}
type storageClient struct {
cc *grpc.ClientConn
}
func NewStorageClient(cc *grpc.ClientConn) StorageClient {
return &storageClient{cc}
}
func (c *storageClient) GetClient(ctx context.Context, in *GetClientReq, opts ...grpc.CallOption) (*GetClientResp, error) {
out := new(GetClientResp)
err := grpc.Invoke(ctx, "/apipb.Storage/GetClient", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *storageClient) CreateClient(ctx context.Context, in *CreateClientReq, opts ...grpc.CallOption) (*CreateClientResp, error) {
out := new(CreateClientResp)
err := grpc.Invoke(ctx, "/apipb.Storage/CreateClient", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *storageClient) UpdateClient(ctx context.Context, in *UpdateClientReq, opts ...grpc.CallOption) (*UpdateClientResp, error) {
out := new(UpdateClientResp)
err := grpc.Invoke(ctx, "/apipb.Storage/UpdateClient", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *storageClient) DeleteClient(ctx context.Context, in *DeleteClientReq, opts ...grpc.CallOption) (*DeleteClientReq, error) {
out := new(DeleteClientReq)
err := grpc.Invoke(ctx, "/apipb.Storage/DeleteClient", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *storageClient) ListClients(ctx context.Context, in *ListClientsReq, opts ...grpc.CallOption) (*ListClientsResp, error) {
out := new(ListClientsResp)
err := grpc.Invoke(ctx, "/apipb.Storage/ListClients", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Storage service
type StorageServer interface {
GetClient(context.Context, *GetClientReq) (*GetClientResp, error)
CreateClient(context.Context, *CreateClientReq) (*CreateClientResp, error)
UpdateClient(context.Context, *UpdateClientReq) (*UpdateClientResp, error)
DeleteClient(context.Context, *DeleteClientReq) (*DeleteClientReq, error)
ListClients(context.Context, *ListClientsReq) (*ListClientsResp, error)
}
func RegisterStorageServer(s *grpc.Server, srv StorageServer) {
s.RegisterService(&_Storage_serviceDesc, srv)
}
func _Storage_GetClient_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetClientReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StorageServer).GetClient(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/apipb.Storage/GetClient",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StorageServer).GetClient(ctx, req.(*GetClientReq))
}
return interceptor(ctx, in, info, handler)
}
func _Storage_CreateClient_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateClientReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StorageServer).CreateClient(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/apipb.Storage/CreateClient",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StorageServer).CreateClient(ctx, req.(*CreateClientReq))
}
return interceptor(ctx, in, info, handler)
}
func _Storage_UpdateClient_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateClientReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StorageServer).UpdateClient(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/apipb.Storage/UpdateClient",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StorageServer).UpdateClient(ctx, req.(*UpdateClientReq))
}
return interceptor(ctx, in, info, handler)
}
func _Storage_DeleteClient_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteClientReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StorageServer).DeleteClient(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/apipb.Storage/DeleteClient",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StorageServer).DeleteClient(ctx, req.(*DeleteClientReq))
}
return interceptor(ctx, in, info, handler)
}
func _Storage_ListClients_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListClientsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StorageServer).ListClients(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/apipb.Storage/ListClients",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StorageServer).ListClients(ctx, req.(*ListClientsReq))
}
return interceptor(ctx, in, info, handler)
}
var _Storage_serviceDesc = grpc.ServiceDesc{
ServiceName: "apipb.Storage",
HandlerType: (*StorageServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetClient",
Handler: _Storage_GetClient_Handler,
},
{
MethodName: "CreateClient",
Handler: _Storage_CreateClient_Handler,
},
{
MethodName: "UpdateClient",
Handler: _Storage_UpdateClient_Handler,
},
{
MethodName: "DeleteClient",
Handler: _Storage_DeleteClient_Handler,
},
{
MethodName: "ListClients",
Handler: _Storage_ListClients_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
func init() { proto.RegisterFile("api/apipb/api.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 459 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x8c, 0x54, 0x41, 0x8f, 0xd2, 0x40,
0x14, 0xa6, 0xc0, 0xb6, 0xf0, 0x28, 0x0b, 0x79, 0xab, 0x6b, 0xe5, 0xa0, 0xec, 0x18, 0x23, 0x27,
0x4c, 0xd6, 0xc4, 0xac, 0x1e, 0x8c, 0x66, 0x4d, 0xbc, 0x78, 0x20, 0x35, 0x9c, 0x49, 0xa1, 0x2f,
0x9b, 0x89, 0xdd, 0xed, 0x30, 0x33, 0xf8, 0xff, 0x3c, 0x7b, 0xf2, 0x1f, 0x99, 0xce, 0xb4, 0x4d,
0x07, 0x64, 0xc3, 0x85, 0xf0, 0xbe, 0xf9, 0xde, 0x7b, 0xf9, 0xbe, 0xef, 0xa5, 0x70, 0x91, 0x08,
0xfe, 0x36, 0x11, 0x5c, 0xac, 0x8b, 0xdf, 0xb9, 0x90, 0xb9, 0xce, 0xf1, 0xcc, 0x00, 0xec, 0xb7,
0x07, 0xfe, 0x6d, 0xc6, 0xe9, 0x41, 0xe3, 0x39, 0xb4, 0x79, 0x1a, 0x79, 0x53, 0x6f, 0xd6, 0x8f,
0xdb, 0x3c, 0xc5, 0x4b, 0xf0, 0x15, 0x6d, 0x24, 0xe9, 0xa8, 0x6d, 0xb0, 0xb2, 0xc2, 0x57, 0x30,
0x94, 0x94, 0x72, 0x49, 0x1b, 0xbd, 0xda, 0x49, 0xae, 0xa2, 0xce, 0xb4, 0x33, 0xeb, 0xc7, 0x61,
0x05, 0x2e, 0x25, 0x57, 0x05, 0x49, 0xcb, 0x9d, 0xd2, 0x94, 0xae, 0x04, 0x91, 0x54, 0x51, 0xd7,
0x92, 0x4a, 0x70, 0x51, 0x60, 0xc5, 0x06, 0xb1, 0x5b, 0x67, 0x7c, 0x13, 0x9d, 0x4d, 0xbd, 0x59,
0x2f, 0x2e, 0x2b, 0x44, 0xe8, 0x3e, 0x24, 0xf7, 0x14, 0xf9, 0x66, 0xaf, 0xf9, 0x8f, 0xcf, 0xa1,
0x97, 0xe5, 0x77, 0xf9, 0x6a, 0x27, 0xb3, 0x28, 0x30, 0x78, 0x50, 0xd4, 0x4b, 0x99, 0xb1, 0x1b,
0x18, 0xdd, 0x4a, 0x4a, 0x34, 0x59, 0x21, 0x31, 0x6d, 0xf1, 0x35, 0xf8, 0x1b, 0x53, 0x18, 0x3d,
0x83, 0xeb, 0xe1, 0xdc, 0xc8, 0x9d, 0x97, 0x8c, 0xf2, 0x91, 0x7d, 0x80, 0xb1, 0xdb, 0xa9, 0xc4,
0xa9, 0xad, 0x7f, 0x3d, 0x18, 0x2d, 0x45, 0xea, 0x6c, 0x3d, 0xd5, 0xc1, 0x4a, 0x5f, 0xe7, 0x88,
0xbe, 0xae, 0xa3, 0x0f, 0x5f, 0xc2, 0xe0, 0x3e, 0xf9, 0x49, 0x2b, 0xc7, 0x2b, 0x28, 0xa0, 0x85,
0xf5, 0xeb, 0x0a, 0x42, 0x4b, 0x90, 0xfc, 0x57, 0xa2, 0xad, 0x6f, 0xbd, 0xd8, 0x34, 0x2d, 0x2c,
0x74, 0x18, 0x5a, 0x70, 0x18, 0x5a, 0x61, 0x87, 0x2b, 0xe9, 0x74, 0x3b, 0xc6, 0x70, 0xfe, 0x9d,
0x2b, 0x6d, 0x51, 0x15, 0xd3, 0x96, 0x7d, 0x84, 0x91, 0x83, 0x28, 0x81, 0x6f, 0x20, 0xb0, 0x74,
0x15, 0x79, 0xd3, 0xce, 0xe1, 0xb0, 0xea, 0x95, 0x5d, 0xc1, 0xe8, 0x2b, 0x65, 0xf4, 0x88, 0xb7,
0x0c, 0x61, 0xec, 0x52, 0x94, 0x60, 0x2f, 0x20, 0xfc, 0x46, 0xfa, 0x78, 0xcf, 0x7b, 0x18, 0x36,
0xde, 0x4f, 0x16, 0x77, 0xfd, 0xa7, 0x0d, 0xc1, 0x0f, 0x9d, 0xcb, 0xe4, 0x8e, 0xf0, 0x06, 0xfa,
0xf5, 0x0c, 0xbc, 0x28, 0xf9, 0xcd, 0xad, 0x93, 0x27, 0x87, 0xa0, 0x12, 0xac, 0x85, 0x5f, 0x20,
0x6c, 0x1e, 0x1b, 0x5e, 0x56, 0xcb, 0xdc, 0xdb, 0x9d, 0x3c, 0xfb, 0x2f, 0x5e, 0x8d, 0x68, 0x06,
0x54, 0x8f, 0xd8, 0x3b, 0xc4, 0x7a, 0xc4, 0x7e, 0x9a, 0xac, 0x85, 0x9f, 0x21, 0x6c, 0xfa, 0x56,
0x8f, 0xd8, 0xf3, 0x7b, 0x72, 0x04, 0x67, 0x2d, 0xfc, 0x04, 0x83, 0x46, 0xb0, 0xf8, 0xb4, 0x24,
0xba, 0xf1, 0xd7, 0xfd, 0x7b, 0x37, 0xc0, 0x5a, 0x6b, 0xdf, 0x7c, 0x80, 0xde, 0xfd, 0x0b, 0x00,
0x00, 0xff, 0xff, 0x76, 0xa0, 0x50, 0x77, 0x97, 0x04, 0x00, 0x00,
}
+74
View File
@@ -0,0 +1,74 @@
syntax = "proto3";
// Run `make grpc` at the top level directory to regenerate Go source code.
package apipb;
message Client {
string id = 1;
string secret = 2;
repeated string redirect_uris = 3;
repeated string trusted_peers = 4;
bool public = 5;
string name = 6;
string logo_url = 7;
}
message CreateClientReq {
Client client = 1;
}
message CreateClientResp {
Client client = 1;
}
message UpdateClientReq {
string id = 1;
// Empty strings indicate that string fields should not be updated.
string secret = 2;
string name = 3;
string logo_url = 4;
bool make_public = 5;
bool make_private = 6;
// If no redirect URIs are specified, the current redirect URIs are preserved.
repeated string redirect_uris = 7;
}
message UpdateClientResp {
Client client = 1;
}
message ListClientsReq {
}
message ListClientsResp {
repeated Client clients = 1;
}
message DeleteClientReq {
string id = 1;
}
message DeleteClientResp {}
message GetClientReq {
string id = 1;
}
message GetClientResp {
Client client = 1;
}
service Storage {
rpc CreateClient(CreateClientReq) returns (CreateClientResp) {}
rpc DeleteClient(DeleteClientReq) returns (DeleteClientReq) {}
rpc GetClient(GetClientReq) returns (GetClientResp) {}
rpc ListClients(ListClientsReq) returns (ListClientsResp) {}
rpc UpdateClient(UpdateClientReq) returns (UpdateClientResp) {}
}
+2
View File
@@ -0,0 +1,2 @@
// Package api implements a gRPC interface for interacting with a storage.
package api
Generated
+21 -3
View File
@@ -1,5 +1,5 @@
hash: 8b33b8abf5bca183ffa7108b03f4001f4d23f7f2e26f773f5bcb4bfefa51a26f
updated: 2016-07-22T23:25:33.173188655-07:00
hash: 66d8717b42e620d52ceec62e7cb3f2bc23f21bfe35547587338d85564bd330c9
updated: 2016-07-31T12:19:29.812965492-07:00
imports:
- name: github.com/ericchiang/oidc
version: 69fec81d167d815f4f455c741b2a94ffaf547ed2
@@ -7,6 +7,7 @@ imports:
version: 874264fbbb43f4d91e999fecb4b40143ed611400
subpackages:
- proto
- protoc-gen-go
- name: github.com/gorilla/context
version: aed02d124ae4a0e94fea4541c8effd05bf0c8296
- name: github.com/gorilla/mux
@@ -31,12 +32,18 @@ imports:
- bcrypt
- blowfish
- name: golang.org/x/net
version: d7bf3545bb0dacf009c535b3d3fbf53ac0a339ab
version: 6a513affb38dc9788b449d59ffed099b8de18fa0
subpackages:
- context
- http2
- http2/hpack
- trace
- lex/httplex
- internal/timeseries
- name: golang.org/x/oauth2
version: 08c8d727d2392d18286f9f88ad775ad98f09ab33
subpackages:
- github
- internal
- name: google.golang.org/appengine
version: 267c27e7492265b84fc6719503b14a1e17975d79
@@ -48,6 +55,17 @@ imports:
- internal/datastore
- internal/log
- internal/remote_api
- name: google.golang.org/grpc
version: 13edeeffdea7a41d5aad96c28deb4c7bd01a9397
subpackages:
- codes
- credentials
- grpclog
- internal
- metadata
- naming
- transport
- peer
- name: gopkg.in/asn1-ber.v1
version: 4e86f4367175e39f69d9358a5f17b4dda270378d
- name: gopkg.in/ldap.v2
+29 -3
View File
@@ -1,5 +1,9 @@
# NOTE(ericchiang): Create a separate block for each dependency so it's clear
# which dependencies require which transitive dependencies.
package: github.com/coreos/poke
import:
- package: github.com/spf13/cobra
version: bc81c21bd0d8be5ba2d6630a505d79d4467566e7
- package: github.com/spf13/pflag
@@ -21,9 +25,6 @@ import:
- package: gopkg.in/yaml.v2
version: a83829b6f1293c91addabc89d0571c246397bbf4
- package: golang.org/x/net/context
version: d7bf3545bb0dacf009c535b3d3fbf53ac0a339ab
- package: github.com/gorilla/mux
version: 9fa818a44c2bf1396a17f9d5a3c0f6dd39d2ff8e
- package: github.com/gorilla/context
@@ -44,6 +45,8 @@ import:
version: v1.0.2
- package: golang.org/x/oauth2
version: 08c8d727d2392d18286f9f88ad775ad98f09ab33
# Not actually imported but glide detects it. Consider adding subpackages to
# the oauth2 package to eliminate.
- package: google.golang.org/appengine
version: 267c27e7492265b84fc6719503b14a1e17975d79
subpackages:
@@ -54,10 +57,33 @@ import:
- internal/datastore
- internal/log
- internal/remote_api
# Go's protobuf generator is also a direct dependency of this repo.
- package: github.com/golang/protobuf
version: 874264fbbb43f4d91e999fecb4b40143ed611400
subpackages:
- proto
- protoc-gen-go
- package: github.com/mitchellh/go-homedir
verison: 756f7b183b7ab78acdbbee5c7f392838ed459dda
- package: google.golang.org/grpc
version: v1.0.0
subpackages:
- codes
- credentials
- grpclog
- internal
- metadata
- naming
- transport
- peer
- package: golang.org/x/net
version: 6a513affb38dc9788b449d59ffed099b8de18fa0
subpackages:
- context # context is also imported directly by this repo.
- http2
- http2/hpack
- trace
- lex/httplex
- internal/timeseries
+3
View File
@@ -15,6 +15,9 @@ const keysName = "openid-connect-keys"
// Client is a mirrored struct from storage with JSON struct tags and
// Kubernetes type metadata.
//
// TODO(ericchiang): Kubernetes has an extremely restricted set of characters it can use for IDs.
// Consider base32ing client IDs.
type Client struct {
k8sapi.TypeMeta `json:",inline"`
k8sapi.ObjectMeta `json:"metadata,omitempty"`
+2 -1
View File
@@ -77,13 +77,14 @@ func Open(driverName string, config map[string]string) (Storage, error) {
type Storage interface {
Close() error
// TODO(ericchiang): Let the storages set the IDs of these objects.
CreateAuthRequest(a AuthRequest) error
CreateClient(c Client) error
CreateAuthCode(c AuthCode) error
CreateRefresh(r Refresh) error
// TODO(ericchiang): return (T, bool, error) so we can indicate not found
// requests that way.
// requests that way instead of using ErrNotFound.
GetAuthRequest(id string) (AuthRequest, error)
GetAuthCode(id string) (AuthCode, error)
GetClient(id string) (Client, error)
+2 -1
View File
@@ -5,7 +5,8 @@
/*
Package bpf implements marshaling and unmarshaling of programs for the
Berkeley Packet Filter virtual machine.
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
+140
View File
@@ -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
}
+512
View File
File diff suppressed because it is too large Load Diff
+192
View File
@@ -0,0 +1,192 @@
// 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_test
import (
"net"
"runtime"
"testing"
"time"
"golang.org/x/net/bpf"
"golang.org/x/net/ipv4"
)
// A virtualMachine is a BPF virtual machine which can process an
// input packet against a BPF program and render a verdict.
type virtualMachine interface {
Run(in []byte) (int, error)
}
// canUseOSVM indicates if the OS BPF VM is available on this platform.
func canUseOSVM() bool {
// OS BPF VM can only be used on platforms where x/net/ipv4 supports
// attaching a BPF program to a socket.
switch runtime.GOOS {
case "linux":
return true
}
return false
}
// All BPF tests against both the Go VM and OS VM are assumed to
// be used with a UDP socket. As a result, the entire contents
// of a UDP datagram is sent through the BPF program, but only
// the body after the UDP header will ever be returned in output.
// testVM sets up a Go BPF VM, and if available, a native OS BPF VM
// for integration testing.
func testVM(t *testing.T, filter []bpf.Instruction) (virtualMachine, func(), error) {
goVM, err := bpf.NewVM(filter)
if err != nil {
// Some tests expect an error, so this error must be returned
// instead of fatally exiting the test
return nil, nil, err
}
mvm := &multiVirtualMachine{
goVM: goVM,
t: t,
}
// If available, add the OS VM for tests which verify that both the Go
// VM and OS VM have exactly the same output for the same input program
// and packet.
done := func() {}
if canUseOSVM() {
osVM, osVMDone := testOSVM(t, filter)
done = func() { osVMDone() }
mvm.osVM = osVM
}
return mvm, done, nil
}
// udpHeaderLen is the length of a UDP header.
const udpHeaderLen = 8
// A multiVirtualMachine is a virtualMachine which can call out to both the Go VM
// and the native OS VM, if the OS VM is available.
type multiVirtualMachine struct {
goVM virtualMachine
osVM virtualMachine
t *testing.T
}
func (mvm *multiVirtualMachine) Run(in []byte) (int, error) {
if len(in) < udpHeaderLen {
mvm.t.Fatalf("input must be at least length of UDP header (%d), got: %d",
udpHeaderLen, len(in))
}
// All tests have a UDP header as part of input, because the OS VM
// packets always will. For the Go VM, this output is trimmed before
// being sent back to tests.
goOut, goErr := mvm.goVM.Run(in)
if goOut >= udpHeaderLen {
goOut -= udpHeaderLen
}
// If Go output is larger than the size of the packet, packet filtering
// interop tests must trim the output bytes to the length of the packet.
// The BPF VM should not do this on its own, as other uses of it do
// not trim the output byte count.
trim := len(in) - udpHeaderLen
if goOut > trim {
goOut = trim
}
// When the OS VM is not available, process using the Go VM alone
if mvm.osVM == nil {
return goOut, goErr
}
// The OS VM will apply its own UDP header, so remove the pseudo header
// that the Go VM needs.
osOut, err := mvm.osVM.Run(in[udpHeaderLen:])
if err != nil {
mvm.t.Fatalf("error while running OS VM: %v", err)
}
// Verify both VMs return same number of bytes
var mismatch bool
if goOut != osOut {
mismatch = true
mvm.t.Logf("output byte count does not match:\n- go: %v\n- os: %v", goOut, osOut)
}
if mismatch {
mvm.t.Fatal("Go BPF and OS BPF packet outputs do not match")
}
return goOut, goErr
}
// An osVirtualMachine is a virtualMachine which uses the OS's BPF VM for
// processing BPF programs.
type osVirtualMachine struct {
l net.PacketConn
s net.Conn
}
// testOSVM creates a virtualMachine which uses the OS's BPF VM by injecting
// packets into a UDP listener with a BPF program attached to it.
func testOSVM(t *testing.T, filter []bpf.Instruction) (virtualMachine, func()) {
l, err := net.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to open OS VM UDP listener: %v", err)
}
prog, err := bpf.Assemble(filter)
if err != nil {
t.Fatalf("failed to compile BPF program: %v", err)
}
p := ipv4.NewPacketConn(l)
if err = p.SetBPF(prog); err != nil {
t.Fatalf("failed to attach BPF program to listener: %v", err)
}
s, err := net.Dial("udp4", l.LocalAddr().String())
if err != nil {
t.Fatalf("failed to dial connection to listener: %v", err)
}
done := func() {
_ = s.Close()
_ = l.Close()
}
return &osVirtualMachine{
l: l,
s: s,
}, done
}
// Run sends the input bytes into the OS's BPF VM and returns its verdict.
func (vm *osVirtualMachine) Run(in []byte) (int, error) {
go func() {
_, _ = vm.s.Write(in)
}()
vm.l.SetDeadline(time.Now().Add(50 * time.Millisecond))
var b [512]byte
n, _, err := vm.l.ReadFrom(b[:])
if err != nil {
// A timeout indicates that BPF filtered out the packet, and thus,
// no input should be returned.
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
return n, nil
}
return n, err
}
return n, nil
}
+49
View File
@@ -0,0 +1,49 @@
// 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_test
import (
"testing"
"golang.org/x/net/bpf"
)
func TestVMLoadExtensionNotImplemented(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.LoadExtension{
Num: 100,
},
bpf.RetA{},
})
if errStr(err) != "extension 100 not implemented" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMLoadExtensionExtLen(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadExtension{
Num: bpf.ExtLen,
},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1, 2, 3,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 4, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
+174
View File
@@ -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
}
+380
View File
@@ -0,0 +1,380 @@
// 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_test
import (
"testing"
"golang.org/x/net/bpf"
)
func TestVMJumpOne(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 1,
},
bpf.Jump{
Skip: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 9,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
1,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 1, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpOutOfProgram(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.Jump{
Skip: 1,
},
bpf.RetA{},
})
if errStr(err) != "cannot jump 1 instructions; jumping past program bounds" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMJumpIfTrueOutOfProgram(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.JumpIf{
Cond: bpf.JumpEqual,
SkipTrue: 2,
},
bpf.RetA{},
})
if errStr(err) != "cannot jump 2 instructions in true case; jumping past program bounds" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMJumpIfFalseOutOfProgram(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.JumpIf{
Cond: bpf.JumpEqual,
SkipFalse: 3,
},
bpf.RetA{},
})
if errStr(err) != "cannot jump 3 instructions in false case; jumping past program bounds" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMJumpIfEqual(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 1,
},
bpf.JumpIf{
Cond: bpf.JumpEqual,
Val: 1,
SkipTrue: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 9,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
1,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 1, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpIfNotEqual(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 1,
},
bpf.JumpIf{
Cond: bpf.JumpNotEqual,
Val: 1,
SkipFalse: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 9,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
1,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 1, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpIfGreaterThan(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 4,
},
bpf.JumpIf{
Cond: bpf.JumpGreaterThan,
Val: 0x00010202,
SkipTrue: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 12,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1, 2, 3,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 4, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpIfLessThan(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 4,
},
bpf.JumpIf{
Cond: bpf.JumpLessThan,
Val: 0xff010203,
SkipTrue: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 12,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1, 2, 3,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 4, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpIfGreaterOrEqual(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 4,
},
bpf.JumpIf{
Cond: bpf.JumpGreaterOrEqual,
Val: 0x00010203,
SkipTrue: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 12,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1, 2, 3,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 4, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpIfLessOrEqual(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 4,
},
bpf.JumpIf{
Cond: bpf.JumpLessOrEqual,
Val: 0xff010203,
SkipTrue: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 12,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1, 2, 3,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 4, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpIfBitsSet(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 2,
},
bpf.JumpIf{
Cond: bpf.JumpBitsSet,
Val: 0x1122,
SkipTrue: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 10,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0x01, 0x02,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 2, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMJumpIfBitsNotSet(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 2,
},
bpf.JumpIf{
Cond: bpf.JumpBitsNotSet,
Val: 0x1221,
SkipTrue: 1,
},
bpf.RetConstant{
Val: 0,
},
bpf.RetConstant{
Val: 10,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0x01, 0x02,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 2, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
+246
View File
@@ -0,0 +1,246 @@
// 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_test
import (
"net"
"testing"
"golang.org/x/net/bpf"
"golang.org/x/net/ipv4"
)
func TestVMLoadAbsoluteOffsetOutOfBounds(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 100,
Size: 2,
},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1, 2, 3,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 0, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMLoadAbsoluteOffsetPlusSizeOutOfBounds(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 2,
},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 0, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMLoadAbsoluteBadInstructionSize(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Size: 5,
},
bpf.RetA{},
})
if errStr(err) != "assembling instruction 1: invalid load byte length 0" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMLoadConstantOK(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadConstant{
Dst: bpf.RegX,
Val: 9,
},
bpf.TXA{},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 1, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMLoadIndirectOutOfBounds(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadIndirect{
Off: 100,
Size: 1,
},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 0, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMLoadMemShiftOutOfBounds(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadMemShift{
Off: 100,
},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 0, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
const (
dhcp4Port = 53
)
func TestVMLoadMemShiftLoadIndirectNoResult(t *testing.T) {
vm, in, done := testDHCPv4(t)
defer done()
// Append mostly empty UDP header with incorrect DHCPv4 port
in = append(in, []byte{
0, 0,
0, dhcp4Port + 1,
0, 0,
0, 0,
}...)
out, err := vm.Run(in)
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 0, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMLoadMemShiftLoadIndirectOK(t *testing.T) {
vm, in, done := testDHCPv4(t)
defer done()
// Append mostly empty UDP header with correct DHCPv4 port
in = append(in, []byte{
0, 0,
0, dhcp4Port,
0, 0,
0, 0,
}...)
out, err := vm.Run(in)
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := len(in)-8, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func testDHCPv4(t *testing.T) (virtualMachine, []byte, func()) {
// DHCPv4 test data courtesy of David Anderson:
// https://github.com/google/netboot/blob/master/dhcp4/conn_linux.go#L59-L70
vm, done, err := testVM(t, []bpf.Instruction{
// Load IPv4 packet length
bpf.LoadMemShift{Off: 8},
// Get UDP dport
bpf.LoadIndirect{Off: 8 + 2, Size: 2},
// Correct dport?
bpf.JumpIf{Cond: bpf.JumpEqual, Val: dhcp4Port, SkipFalse: 1},
// Accept
bpf.RetConstant{Val: 1500},
// Ignore
bpf.RetConstant{Val: 0},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
// Minimal requirements to make a valid IPv4 header
h := &ipv4.Header{
Len: ipv4.HeaderLen,
Src: net.IPv4(192, 168, 1, 1),
Dst: net.IPv4(192, 168, 1, 2),
}
hb, err := h.Marshal()
if err != nil {
t.Fatalf("failed to marshal IPv4 header: %v", err)
}
hb = append([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
}, hb...)
return vm, hb, done
}
+115
View File
@@ -0,0 +1,115 @@
// 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_test
import (
"testing"
"golang.org/x/net/bpf"
)
func TestVMRetA(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 1,
},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
9,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 1, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMRetALargerThanInput(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadAbsolute{
Off: 8,
Size: 2,
},
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 255,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 2, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMRetConstant(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.RetConstant{
Val: 9,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 1, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMRetConstantLargerThanInput(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.RetConstant{
Val: 16,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0, 1,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 2, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
+247
View File
@@ -0,0 +1,247 @@
// 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_test
import (
"testing"
"golang.org/x/net/bpf"
)
func TestVMStoreScratchInvalidScratchRegisterTooSmall(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.StoreScratch{
Src: bpf.RegA,
N: -1,
},
bpf.RetA{},
})
if errStr(err) != "assembling instruction 1: invalid scratch slot -1" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMStoreScratchInvalidScratchRegisterTooLarge(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.StoreScratch{
Src: bpf.RegA,
N: 16,
},
bpf.RetA{},
})
if errStr(err) != "assembling instruction 1: invalid scratch slot 16" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMStoreScratchUnknownSourceRegister(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.StoreScratch{
Src: 100,
N: 0,
},
bpf.RetA{},
})
if errStr(err) != "assembling instruction 1: invalid source register 100" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMLoadScratchInvalidScratchRegisterTooSmall(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.LoadScratch{
Dst: bpf.RegX,
N: -1,
},
bpf.RetA{},
})
if errStr(err) != "assembling instruction 1: invalid scratch slot -1" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMLoadScratchInvalidScratchRegisterTooLarge(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.LoadScratch{
Dst: bpf.RegX,
N: 16,
},
bpf.RetA{},
})
if errStr(err) != "assembling instruction 1: invalid scratch slot 16" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMLoadScratchUnknownDestinationRegister(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.LoadScratch{
Dst: 100,
N: 0,
},
bpf.RetA{},
})
if errStr(err) != "assembling instruction 1: invalid target register 100" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMStoreScratchLoadScratchOneValue(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
// Load byte 255
bpf.LoadAbsolute{
Off: 8,
Size: 1,
},
// Copy to X and store in scratch[0]
bpf.TAX{},
bpf.StoreScratch{
Src: bpf.RegX,
N: 0,
},
// Load byte 1
bpf.LoadAbsolute{
Off: 9,
Size: 1,
},
// Overwrite 1 with 255 from scratch[0]
bpf.LoadScratch{
Dst: bpf.RegA,
N: 0,
},
// Return 255
bpf.RetA{},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
255, 1, 2,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 3, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
func TestVMStoreScratchLoadScratchMultipleValues(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
// Load byte 10
bpf.LoadAbsolute{
Off: 8,
Size: 1,
},
// Store in scratch[0]
bpf.StoreScratch{
Src: bpf.RegA,
N: 0,
},
// Load byte 20
bpf.LoadAbsolute{
Off: 9,
Size: 1,
},
// Store in scratch[1]
bpf.StoreScratch{
Src: bpf.RegA,
N: 1,
},
// Load byte 30
bpf.LoadAbsolute{
Off: 10,
Size: 1,
},
// Store in scratch[2]
bpf.StoreScratch{
Src: bpf.RegA,
N: 2,
},
// Load byte 1
bpf.LoadAbsolute{
Off: 11,
Size: 1,
},
// Store in scratch[3]
bpf.StoreScratch{
Src: bpf.RegA,
N: 3,
},
// Load in byte 10 to X
bpf.LoadScratch{
Dst: bpf.RegX,
N: 0,
},
// Copy X -> A
bpf.TXA{},
// Verify value is 10
bpf.JumpIf{
Cond: bpf.JumpEqual,
Val: 10,
SkipTrue: 1,
},
// Fail test if incorrect
bpf.RetConstant{
Val: 0,
},
// Load in byte 20 to A
bpf.LoadScratch{
Dst: bpf.RegA,
N: 1,
},
// Verify value is 20
bpf.JumpIf{
Cond: bpf.JumpEqual,
Val: 20,
SkipTrue: 1,
},
// Fail test if incorrect
bpf.RetConstant{
Val: 0,
},
// Load in byte 30 to A
bpf.LoadScratch{
Dst: bpf.RegA,
N: 2,
},
// Verify value is 30
bpf.JumpIf{
Cond: bpf.JumpEqual,
Val: 30,
SkipTrue: 1,
},
// Fail test if incorrect
bpf.RetConstant{
Val: 0,
},
// Return first two bytes on success
bpf.RetConstant{
Val: 10,
},
})
if err != nil {
t.Fatalf("failed to load BPF program: %v", err)
}
defer done()
out, err := vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
10, 20, 30, 1,
})
if err != nil {
t.Fatalf("unexpected error while running program: %v", err)
}
if want, got := 2, out; want != got {
t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d",
want, got)
}
}
+144
View File
@@ -0,0 +1,144 @@
// 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_test
import (
"fmt"
"testing"
"golang.org/x/net/bpf"
)
var _ bpf.Instruction = unknown{}
type unknown struct{}
func (unknown) Assemble() (bpf.RawInstruction, error) {
return bpf.RawInstruction{}, nil
}
func TestVMUnknownInstruction(t *testing.T) {
vm, done, err := testVM(t, []bpf.Instruction{
bpf.LoadConstant{
Dst: bpf.RegA,
Val: 100,
},
// Should terminate the program with an error immediately
unknown{},
bpf.RetA{},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer done()
_, err = vm.Run([]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0x00, 0x00,
})
if errStr(err) != "unknown Instruction at index 1: bpf_test.unknown" {
t.Fatalf("unexpected error while running program: %v", err)
}
}
func TestVMNoReturnInstruction(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{
bpf.LoadConstant{
Dst: bpf.RegA,
Val: 1,
},
})
if errStr(err) != "BPF program must end with RetA or RetConstant" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestVMNoInputInstructions(t *testing.T) {
_, _, err := testVM(t, []bpf.Instruction{})
if errStr(err) != "one or more Instructions must be specified" {
t.Fatalf("unexpected error: %v", err)
}
}
// ExampleNewVM demonstrates usage of a VM, using an Ethernet frame
// as input and checking its EtherType to determine if it should be accepted.
func ExampleNewVM() {
// Offset | Length | Comment
// -------------------------
// 00 | 06 | Ethernet destination MAC address
// 06 | 06 | Ethernet source MAC address
// 12 | 02 | Ethernet EtherType
const (
etOff = 12
etLen = 2
etARP = 0x0806
)
// Set up a VM to filter traffic based on if its EtherType
// matches the ARP EtherType.
vm, err := bpf.NewVM([]bpf.Instruction{
// Load EtherType value from Ethernet header
bpf.LoadAbsolute{
Off: etOff,
Size: etLen,
},
// If EtherType is equal to the ARP EtherType, jump to allow
// packet to be accepted
bpf.JumpIf{
Cond: bpf.JumpEqual,
Val: etARP,
SkipTrue: 1,
},
// EtherType does not match the ARP EtherType
bpf.RetConstant{
Val: 0,
},
// EtherType matches the ARP EtherType, accept up to 1500
// bytes of packet
bpf.RetConstant{
Val: 1500,
},
})
if err != nil {
panic(fmt.Sprintf("failed to load BPF program: %v", err))
}
// Create an Ethernet frame with the ARP EtherType for testing
frame := []byte{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
0x08, 0x06,
// Payload omitted for brevity
}
// Run our VM's BPF program using the Ethernet frame as input
out, err := vm.Run(frame)
if err != nil {
panic(fmt.Sprintf("failed to accept Ethernet frame: %v", err))
}
// BPF VM can return a byte count greater than the number of input
// bytes, so trim the output to match the input byte length
if out > len(frame) {
out = len(frame)
}
fmt.Printf("out: %d bytes", out)
// Output:
// out: 14 bytes
}
// errStr returns the string representation of an error, or
// "<nil>" if it is nil.
func errStr(err error) string {
if err == nil {
return "<nil>"
}
return err.Error()
}

Some files were not shown because too many files have changed in this diff Show More