cacert-gosigner/pkg/seriallink/seriallink.go

218 lines
4.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 seriallink provides a handler for the serial connection of the signer machine.
package seriallink
import (
"bytes"
"fmt"
"time"
"github.com/justincpresley/go-cobs"
"github.com/tarm/serial"
"git.cacert.org/cacert-gosigner/pkg/config"
"git.cacert.org/cacert-gosigner/pkg/protocol"
)
type protocolState int8
const (
stAnnounce protocolState = iota
stCommand
)
type Handler struct {
protocolHandler protocol.Handler
protocolState protocolState
currentCommand *protocol.Command
config *serial.Config
port *serial.Port
}
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
}
const cobsDelimiter = 0x00
var cobsConfig = cobs.Config{SpecialByte: cobsDelimiter, Delimiter: true, EndingSave: true}
func (h *Handler) Run() error {
const (
bufferSize = 1024 * 1024
readInterval = 50 * time.Millisecond
)
errors := make(chan error)
h.protocolState = stAnnounce
go func() {
buf := make([]byte, bufferSize)
for {
count, err := h.port.Read(buf)
if err != nil {
errors <- err
return
}
if count == 0 {
time.Sleep(readInterval)
continue
}
frames := bytes.SplitAfter(buf[:count], []byte{cobsDelimiter})
if err := h.handleFrames(frames); err != nil {
errors <- err
return
}
}
}()
err := <-errors
if err != nil {
return fmt.Errorf("error from handler loop: %w", err)
}
return nil
}
func (h *Handler) handleFrames(frames [][]byte) error {
for _, frame := range frames {
if len(frame) == 0 {
return nil
}
if err := cobs.Verify(frame, cobsConfig); err != nil {
return fmt.Errorf("could not verify COBS frame: %w", err)
}
// perform COBS decoding
decoded := cobs.Decode(frame, cobsConfig)
if h.protocolState == stAnnounce {
if err := h.handleCommandAnnounce(decoded); err != nil {
return err
}
}
if h.protocolState == stCommand {
if err := h.handleCommandData(decoded); err != nil {
return err
}
}
if err := h.nextState(); err != nil {
return err
}
}
return nil
}
func (h *Handler) handleCommandData(decoded []byte) error {
respAnn, msg, err := h.protocolHandler.HandleCommand(h.currentCommand.Announce, decoded)
if err != nil {
return fmt.Errorf("command handler for %s failed: %w", h.currentCommand.Announce.Code, err)
}
if err := h.writeResponse(respAnn, msg, cobsConfig); err != nil {
return err
}
return nil
}
func (h *Handler) handleCommandAnnounce(decoded []byte) error {
announce, err := h.protocolHandler.HandleCommandAnnounce(decoded)
if err != nil {
return fmt.Errorf("command announce handling failed: %w", err)
}
h.currentCommand = &protocol.Command{Announce: announce}
return nil
}
func (h *Handler) writeResponse(ann, msg []byte, cobsConfig cobs.Config) error {
encoded := cobs.Encode(ann, cobsConfig)
if _, err := h.port.Write(encoded); err != nil {
return fmt.Errorf("could not write response announcement: %w", err)
}
encoded = cobs.Encode(msg, cobsConfig)
if _, err := h.port.Write(encoded); err != nil {
return fmt.Errorf("could not write response: %w", err)
}
return nil
}
func (h *Handler) nextState() error {
var next protocolState
switch h.protocolState {
case stAnnounce:
next = stCommand
case stCommand:
next = stAnnounce
default:
return fmt.Errorf("illegal protocol state %d", int(h.protocolState))
}
h.protocolState = next
return nil
}
func New(cfg *config.Serial, protocolHandler protocol.Handler) (*Handler, error) {
h := &Handler{protocolHandler: protocolHandler}
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
}