/* 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" "github.com/sirupsen/logrus" "github.com/tarm/serial" "git.cacert.org/cacert-gosigner/internal/config" "git.cacert.org/cacert-gosigner/pkg/protocol" ) type Handler struct { serverHandler protocol.ServerHandler 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 { 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() { serverProtocol := protocol.NewServer(h.serverHandler, h.framesIn, h.framesOut, h.logger) err := serverProtocol.Handle() 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 } } } func New( cfg *config.Serial, logger *logrus.Logger, protocolHandler protocol.ServerHandler, ) (*Handler, error) { h := &Handler{ serverHandler: 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 }