cacert-gosigner/pkg/protocol/protocol.go

414 lines
8.5 KiB
Go
Raw Normal View History

/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package protocol handles the protocol message marshaling and unmarshalling.
package protocol
import (
"bytes"
"errors"
"fmt"
"io"
"time"
"github.com/justincpresley/go-cobs"
"github.com/sirupsen/logrus"
"git.cacert.org/cacert-gosigner/pkg/messages"
)
const CobsDelimiter = 0x00
type Command struct {
Announce *messages.CommandAnnounce
Command interface{}
}
func (c *Command) String() string {
return fmt.Sprintf("Cmd[announce={%s}, data={%s}]", c.Announce, c.Command)
}
type Response struct {
Announce *messages.ResponseAnnounce
Response interface{}
}
func (r *Response) String() string {
return fmt.Sprintf("Rsp[announce={%s}, data={%s}]", r.Announce, r.Response)
}
// ServerHandler is responsible for parsing incoming frames and calling commands
type ServerHandler interface {
// CommandAnnounce handles the initial announcement of a command.
CommandAnnounce(chan []byte) (*Command, error)
// CommandData handles the command data.
CommandData(chan []byte, *Command) error
// HandleCommand executes the command, generating a response.
HandleCommand(*Command) (*Response, error)
// Respond generates the response for a command.
Respond(*Response, chan []byte) error
}
type ClientHandler interface {
Send(*Command, chan []byte) error
ResponseAnnounce(chan []byte) (*Response, error)
ResponseData(chan []byte, *Response) error
HandleResponse(*Response) error
}
var (
errCommandExpected = errors.New("command must not be nil")
errResponseExpected = errors.New("response must not be nil")
ErrResponseAnnounceTimeoutExpired = errors.New("response announce timeout expired")
ErrResponseDataTimeoutExpired = errors.New("response data timeout expired")
)
type protocolState int8
const (
cmdAnnounce protocolState = iota
cmdData
handleCommand
respond
respAnnounce
respData
handleResponse
)
var protocolStateNames = map[protocolState]string{
cmdAnnounce: "CMD ANNOUNCE",
cmdData: "CMD DATA",
handleCommand: "HANDLE CMD",
respond: "RESPOND",
respAnnounce: "RESP ANNOUNCE",
respData: "RESP DATA",
handleResponse: "HANDLE RESP",
}
func (p protocolState) String() string {
if name, ok := protocolStateNames[p]; ok {
return name
}
return fmt.Sprintf("unknown %d", p)
}
type ServerProtocol struct {
handler ServerHandler
in, out chan []byte
logger *logrus.Logger
state protocolState
}
func (p *ServerProtocol) Handle() error {
var (
command *Command
response *Response
err error
)
for {
p.logger.Debugf("handling protocol state %s", p.state)
switch p.state {
case cmdAnnounce:
command, err = p.handler.CommandAnnounce(p.in)
if err != nil {
p.logger.WithError(err).Error("could not handle command announce")
break
}
p.state = cmdData
case cmdData:
if command == nil {
return errCommandExpected
}
err = p.handler.CommandData(p.in, command)
if err != nil {
p.logger.WithError(err).Error("could not handle command data")
p.state = cmdAnnounce
break
}
p.state = handleCommand
case handleCommand:
if command == nil {
return errCommandExpected
}
response, err = p.handler.HandleCommand(command)
if err != nil {
p.logger.WithError(err).Error("could not handle command")
p.state = cmdAnnounce
break
}
p.state = respond
case respond:
if response == nil {
return errResponseExpected
}
err = p.handler.Respond(response, p.out)
if err != nil {
p.logger.WithError(err).Error("could not respond")
p.state = cmdAnnounce
break
}
p.state = cmdAnnounce
default:
return fmt.Errorf("unknown protocol state %s", p.state)
}
}
}
func NewServer(handler ServerHandler, in, out chan []byte, logger *logrus.Logger) *ServerProtocol {
return &ServerProtocol{
handler: handler,
in: in,
out: out,
logger: logger,
state: cmdAnnounce,
}
}
// Framer handles bytes on the wire by adding or removing framing information.
type Framer interface {
// ReadFrames reads data frames and publishes unframed data to the channel.
ReadFrames(io.Reader, chan []byte) error
// WriteFrames takes data from the channel and writes framed data to the writer.
WriteFrames(io.Writer, chan []byte) error
}
type ClientProtocol struct {
handler ClientHandler
commands chan *Command
in, out chan []byte
logger *logrus.Logger
state protocolState
}
func (p *ClientProtocol) Handle() error {
var (
command *Command
response *Response
err error
)
for {
p.logger.Debugf("handling protocol state %s", p.state)
switch p.state {
case cmdAnnounce:
command = <-p.commands
if command == nil {
return errCommandExpected
}
err = p.handler.Send(command, p.out)
if err != nil {
p.logger.WithError(err).Error("could not send command announce")
break
}
p.state = respAnnounce
case respAnnounce:
response, err = p.handler.ResponseAnnounce(p.in)
if err != nil {
p.logger.WithError(err).Error("could not handle response announce")
p.state = cmdAnnounce
break
}
p.state = respData
case respData:
if response == nil {
return errResponseExpected
}
err = p.handler.ResponseData(p.in, response)
if err != nil {
p.logger.WithError(err).Error("could not handle response data")
if errors.Is(err, ErrResponseDataTimeoutExpired) {
p.state = cmdAnnounce
} else {
p.state = respAnnounce
}
break
}
p.state = handleResponse
case handleResponse:
if response == nil {
return errResponseExpected
}
err = p.handler.HandleResponse(response)
if err != nil {
p.logger.WithError(err).Error("could not handle response")
p.state = cmdAnnounce
break
}
p.state = cmdAnnounce
default:
return fmt.Errorf("unknown protocol state %s", p.state)
}
}
}
func NewClient(
handler ClientHandler,
commands chan *Command,
in, out chan []byte,
logger *logrus.Logger,
) *ClientProtocol {
return &ClientProtocol{
handler: handler,
commands: commands,
in: in,
out: out,
logger: logger,
state: cmdAnnounce,
}
}
const bufferSize = 1024
const readInterval = 50 * time.Millisecond
type COBSFramer struct {
config cobs.Config
logger *logrus.Logger
}
func NewCOBSFramer(logger *logrus.Logger) *COBSFramer {
return &COBSFramer{
config: cobs.Config{SpecialByte: CobsDelimiter, Delimiter: true, EndingSave: true},
logger: logger,
}
}
func (c *COBSFramer) ReadFrames(reader io.Reader, frameChan chan []byte) error {
var (
err error
raw, data, frame []byte
)
buffer := &bytes.Buffer{}
for {
raw, err = c.readRaw(reader)
if err != nil {
close(frameChan)
return err
}
if len(raw) == 0 {
time.Sleep(readInterval)
continue
}
c.logger.Tracef("read %d raw bytes", len(raw))
buffer.Write(raw)
for {
data, err = buffer.ReadBytes(c.config.SpecialByte)
if err != nil {
if errors.Is(err, io.EOF) {
buffer.Write(data)
break
}
return fmt.Errorf("could not read from buffer: %w", err)
}
if err = cobs.Verify(data, c.config); err != nil {
c.logger.WithError(err).Warnf("skipping invalid frame of %d bytes", len(data))
continue
}
frame = cobs.Decode(data, c.config)
c.logger.Tracef("frame decoded to length %d", len(frame))
frameChan <- frame
}
c.logger.Tracef("read buffer is now %d bytes long", buffer.Len())
}
}
func (c *COBSFramer) readRaw(reader io.Reader) ([]byte, error) {
buf := make([]byte, bufferSize)
count, err := reader.Read(buf)
if err != nil {
if errors.Is(err, io.EOF) {
return []byte{}, nil
}
return nil, fmt.Errorf("could not read data: %w", err)
}
raw := buf[:count]
return raw, nil
}
func (c *COBSFramer) WriteFrames(writer io.Writer, frameChan chan []byte) error {
for {
frame := <-frameChan
if frame == nil {
c.logger.Debug("channel closed")
return nil
}
encoded := cobs.Encode(frame, c.config)
n, err := io.Copy(writer, bytes.NewReader(encoded))
if err != nil {
return fmt.Errorf("cold not write data: %w", err)
}
c.logger.Tracef("wrote %d bytes", n)
}
}