cacert-gosigner/internal/serial/seriallink.go

260 lines
5.1 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"
"fmt"
"sync"
"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
respAnnounce
respData
)
var validTransitions = map[protocolState]protocolState{
cmdAnnounce: cmdData,
cmdData: respAnnounce,
respAnnounce: respData,
respData: cmdAnnounce,
}
var protocolStateNames = map[protocolState]string{
cmdAnnounce: "CMD ANNOUNCE",
cmdData: "CMD DATA",
respAnnounce: "RESP ANNOUNCE",
respData: "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.Handler
protocolState protocolState
framer protocol.Framer
config *serial.Config
port *serial.Port
logger *logrus.Logger
lock sync.Mutex
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
errors := make(chan error)
go func() {
err := h.framer.ReadFrames(h.port, h.framesIn)
errors <- err
}()
go func() {
err := h.framer.WriteFrames(h.port, h.framesOut)
errors <- err
}()
for {
select {
case <-ctx.Done():
return nil
case err := <-errors:
if err != nil {
return fmt.Errorf("error from handler loop: %w", err)
}
return nil
default:
if err := h.handleProtocolState(); err != nil {
return err
}
}
}
}
func (h *Handler) nextState() error {
next, ok := validTransitions[h.protocolState]
if !ok {
return fmt.Errorf("illegal protocol state %s", h.protocolState)
}
h.protocolState = next
return nil
}
func (h *Handler) handleProtocolState() error {
h.logger.Tracef("handling protocol state %s", h.protocolState)
h.lock.Lock()
defer h.lock.Unlock()
switch h.protocolState {
case cmdAnnounce:
if err := h.handleCmdAnnounce(); err != nil {
return err
}
case cmdData:
if err := h.handleCmdData(); err != nil {
return err
}
case respAnnounce:
if err := h.handleRespAnnounce(); err != nil {
return err
}
case respData:
if err := h.handleRespData(); err != nil {
return err
}
default:
return fmt.Errorf("unknown protocol state %s", h.protocolState)
}
return nil
}
func (h *Handler) handleCmdAnnounce() error {
h.logger.Trace("waiting for command announce")
frame := <-h.framesIn
if frame == nil {
return nil
}
if err := h.protocolHandler.HandleCommandAnnounce(frame); err != nil {
return fmt.Errorf("command announce handling failed: %w", err)
}
if err := h.nextState(); err != nil {
return err
}
return nil
}
func (h *Handler) handleCmdData() error {
h.logger.Trace("waiting for command data")
frame := <-h.framesIn
if frame == nil {
return nil
}
if err := h.protocolHandler.HandleCommand(frame); err != nil {
return fmt.Errorf("command handler failed: %w", err)
}
if err := h.nextState(); err != nil {
return err
}
return nil
}
func (h *Handler) handleRespAnnounce() error {
frame, err := h.protocolHandler.ResponseAnnounce()
if err != nil {
return fmt.Errorf("could not get response announcement: %w", err)
}
h.framesOut <- frame
if err := h.nextState(); err != nil {
return err
}
return nil
}
func (h *Handler) handleRespData() error {
frame, err := h.protocolHandler.ResponseData()
if err != nil {
return fmt.Errorf("could not get response data: %w", err)
}
h.framesOut <- frame
if err := h.nextState(); err != nil {
return err
}
return nil
}
func New(cfg *config.Serial, logger *logrus.Logger, protocolHandler protocol.Handler) (*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
}