cacert-gosigner/internal/serial/seriallink.go

229 lines
4.7 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 serial provides a handler for the serial connection of the signer machine.
package serial
import (
"context"
"errors"
"fmt"
"github.com/sirupsen/logrus"
"github.com/tarm/serial"
"git.cacert.org/cacert-gosigner/internal/config"
"git.cacert.org/cacert-gosigner/pkg/protocol"
)
type protocolState int8
const (
cmdAnnounce protocolState = iota
cmdData
handleCommand
respond
)
var protocolStateNames = map[protocolState]string{
cmdAnnounce: "CMD ANNOUNCE",
cmdData: "CMD DATA",
handleCommand: "RESP ANNOUNCE",
respond: "RESP DATA",
}
func (p protocolState) String() string {
if name, ok := protocolStateNames[p]; ok {
return name
}
return fmt.Sprintf("unknown %d", p)
}
type Handler struct {
protocolHandler protocol.ServerHandler
protocolState protocolState
framer protocol.Framer
config *serial.Config
port *serial.Port
logger *logrus.Logger
framesIn chan []byte
framesOut chan []byte
}
func (h *Handler) setupConnection() error {
s, err := serial.OpenPort(h.config)
if err != nil {
return fmt.Errorf("could not open serial port: %w", err)
}
h.port = s
return nil
}
func (h *Handler) Close() error {
err := h.port.Close()
if err != nil {
return fmt.Errorf("could not close serial port: %w", err)
}
return nil
}
func (h *Handler) Run(ctx context.Context) error {
h.protocolState = cmdAnnounce
protocolErrors, framerErrors := make(chan error), make(chan error)
go func() {
err := h.framer.ReadFrames(h.port, h.framesIn)
framerErrors <- err
}()
go func() {
err := h.framer.WriteFrames(h.port, h.framesOut)
framerErrors <- err
}()
go func() {
err := h.handleProtocolState()
protocolErrors <- err
}()
for {
select {
case <-ctx.Done():
return nil
case err := <-framerErrors:
if err != nil {
return fmt.Errorf("error from framer: %w", err)
}
return nil
case err := <-protocolErrors:
if err != nil {
return fmt.Errorf("error from protocol handler: %w", err)
}
return nil
}
}
}
var errCommandExpected = errors.New("command must not be nil")
var errResponseExpected = errors.New("response must not be nil")
func (h *Handler) handleProtocolState() error {
var (
command *protocol.Command
response *protocol.Response
err error
)
for {
h.logger.Debugf("handling protocol state %s", h.protocolState)
switch h.protocolState {
case cmdAnnounce:
command, err = h.protocolHandler.CommandAnnounce(h.framesIn)
if err != nil {
h.logger.WithError(err).Error("could not handle command announce")
break
}
h.protocolState = cmdData
case cmdData:
if command == nil {
return errCommandExpected
}
err = h.protocolHandler.CommandData(h.framesIn, command)
if err != nil {
h.logger.WithError(err).Error("could not handle command data")
h.protocolState = cmdAnnounce
break
}
h.protocolState = handleCommand
case handleCommand:
if command == nil {
return errCommandExpected
}
response, err = h.protocolHandler.HandleCommand(command)
if err != nil {
h.logger.WithError(err).Error("could not handle command")
h.protocolState = cmdAnnounce
break
}
command = nil
h.protocolState = respond
case respond:
if response == nil {
return errResponseExpected
}
err = h.protocolHandler.Respond(response, h.framesOut)
if err != nil {
h.logger.WithError(err).Error("could not respond")
h.protocolState = cmdAnnounce
break
}
response = nil
h.protocolState = cmdAnnounce
default:
return fmt.Errorf("unknown protocol state %s", h.protocolState)
}
}
}
func New(
cfg *config.Serial,
logger *logrus.Logger,
protocolHandler protocol.ServerHandler,
) (*Handler, error) {
h := &Handler{
protocolHandler: protocolHandler,
logger: logger,
framesIn: make(chan []byte),
framesOut: make(chan []byte),
framer: protocol.NewCOBSFramer(logger),
}
h.config = &serial.Config{Name: cfg.Device, Baud: cfg.Baud, ReadTimeout: cfg.Timeout}
err := h.setupConnection()
if err != nil {
return nil, err
}
return h, nil
}