cacert-gosigner/pkg/seriallink/seriallink.go

135 lines
2.6 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 (
"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 Handler struct {
protocolHandler protocol.Handler
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
func (h *Handler) Run() error {
const (
bufferSize = 1024 * 1024
readInterval = 50 * time.Millisecond
)
errors := make(chan error)
cobsConfig := cobs.Config{SpecialByte: cobsDelimiter, Delimiter: true, EndingSave: true}
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
}
err = cobs.Verify(buf[:count], cobsConfig)
if err != nil {
errors <- err
return
}
// perform COBS decoding
decoded := cobs.Decode(buf[:count], cobsConfig)
msg, err := h.protocolHandler.HandleFrame(decoded)
if err != nil {
errors <- err
return
}
// perform COBS encoding
encoded := cobs.Encode(msg, cobsConfig)
_, err = h.port.Write(encoded)
if err != nil {
errors <- err
return
}
}
}()
err := <-errors
if err != nil {
return fmt.Errorf("error from handler loop: %w", err)
}
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
}