cacert-gosigner/cmd/clientsim/main.go
Jan Dittberner 2de592d30c Implement command type handling
This commit changes the wire protocol to split between command
announcement and command payload to allow proper typing of sent and
received msgpack messages.

CRL fetching has been implemented as second command after the existing
health check command.
2022-11-20 18:59:37 +01:00

311 lines
6.5 KiB
Go

/*
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.
*/
// client simulator
package main
import (
"bytes"
"context"
"fmt"
"os"
"sync"
"time"
"github.com/justincpresley/go-cobs"
"github.com/shamaton/msgpackgen/msgpack"
"github.com/sirupsen/logrus"
"git.cacert.org/cacert-gosigner/pkg/protocol"
"git.cacert.org/cacert-gosigner/pkg/messages"
)
const cobsDelimiter = 0x00
var cobsConfig = cobs.Config{SpecialByte: cobsDelimiter, Delimiter: true, EndingSave: true}
func main() {
logger := logrus.New()
logger.SetOutput(os.Stderr)
logger.SetLevel(logrus.InfoLevel)
sim := &clientSimulator{
logger: logger,
}
err := sim.Run()
if err != nil {
logger.WithError(err).Error("simulator returned an error")
}
}
type clientSimulator struct {
logger *logrus.Logger
commands chan *protocol.Command
responses chan [][]byte
}
func (c *clientSimulator) writeTestCommands(ctx context.Context) error {
messages.RegisterGeneratedResolver()
const healthInterval = 10 * time.Second
time.Sleep(healthInterval)
c.commands <- &protocol.Command{
Announce: messages.BuildCommandAnnounce(messages.CmdFetchCRL),
Command: &messages.FetchCRLCommand{IssuerID: "sub-ecc_person_2022"},
}
timer := time.NewTimer(healthInterval)
for {
select {
case <-ctx.Done():
_ = timer.Stop()
c.logger.Info("stopping health check loop")
return nil
case <-timer.C:
c.commands <- &protocol.Command{
Announce: messages.BuildCommandAnnounce(messages.CmdHealth),
Command: &messages.HealthCommand{},
}
}
timer.Reset(healthInterval)
}
}
func (c *clientSimulator) handleInput(ctx context.Context) error {
const (
bufferSize = 1024 * 1024
readInterval = 50 * time.Millisecond
)
buf := make([]byte, bufferSize)
type protocolState int8
const (
stAnn protocolState = iota
stResp
)
state := stAnn
var announce []byte
reading:
for {
select {
case <-ctx.Done():
return nil
default:
count, err := os.Stdin.Read(buf)
if err != nil {
return fmt.Errorf("reading input failed: %w", err)
}
if count == 0 {
time.Sleep(readInterval)
continue
}
data := buf[:count]
for _, frame := range bytes.SplitAfter(data, []byte{cobsConfig.SpecialByte}) {
if len(frame) == 0 {
continue reading
}
err = cobs.Verify(frame, cobsConfig)
if err != nil {
return fmt.Errorf("frame verification failed: %w", err)
}
if state == stAnn {
announce = cobs.Decode(frame, cobsConfig)
state = stResp
} else {
c.responses <- [][]byte{announce, cobs.Decode(frame, cobsConfig)}
state = stAnn
}
}
}
}
}
func (c *clientSimulator) handleCommands(ctx context.Context) error {
for {
select {
case command := <-c.commands:
if err := writeCommandAnnouncement(command); err != nil {
return err
}
if err := writeCommand(command); err != nil {
return err
}
respData := <-c.responses
c.logger.WithField("respdata", respData).Trace("read response data")
response := &protocol.Response{}
if err := msgpack.Unmarshal(respData[0], &response.Announce); err != nil {
return fmt.Errorf("could not unmarshal response announcement: %w", err)
}
if err := c.handleResponse(response, respData[1]); err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}
func (c *clientSimulator) handleResponse(response *protocol.Response, respBytes []byte) error {
switch response.Announce.Code {
case messages.RespHealth:
data := messages.HealthResponse{}
if err := msgpack.Unmarshal(respBytes, &data); err != nil {
return fmt.Errorf("could not unmarshal health data: %w", err)
}
c.logger.WithField(
"announce",
response.Announce,
).WithField(
"data",
&data,
).Infof("received response")
case messages.RespFetchCRL:
data := messages.FetchCRLResponse{}
if err := msgpack.Unmarshal(respBytes, &data); err != nil {
return fmt.Errorf("could not unmarshal fetch CRL data: %w", err)
}
c.logger.WithField(
"announce",
response.Announce,
).WithField(
"data",
&data,
).Infof("received response")
case messages.RespError:
data := messages.ErrorResponse{}
if err := msgpack.Unmarshal(respBytes, &data); err != nil {
return fmt.Errorf("could not unmarshal error data: %w", err)
}
c.logger.WithField(
"announce",
response.Announce,
).WithField(
"data",
&data,
).Infof("received response")
default:
if err := msgpack.Unmarshal(respBytes, &response.Response); err != nil {
return fmt.Errorf("could not unmarshal response: %w", err)
}
c.logger.WithField("response", response).Infof("received response")
}
return nil
}
func writeCommandAnnouncement(command *protocol.Command) error {
cmdAnnounceBytes, err := msgpack.Marshal(&command.Announce)
if err != nil {
return fmt.Errorf("could not marshal command announcement bytes: %w", err)
}
if _, err = os.Stdout.Write(cobs.Encode(cmdAnnounceBytes, cobsConfig)); err != nil {
return fmt.Errorf("command announcement write failed: %w", err)
}
return nil
}
func writeCommand(command *protocol.Command) error {
cmdBytes, err := msgpack.Marshal(&command.Command)
if err != nil {
return fmt.Errorf("could not marshal command bytes: %w", err)
}
if _, err = os.Stdout.Write(cobs.Encode(cmdBytes, cobsConfig)); err != nil {
return fmt.Errorf("command write failed: %w", err)
}
return nil
}
func (c *clientSimulator) Run() error {
ctx, cancel := context.WithCancel(context.Background())
c.commands = make(chan *protocol.Command)
c.responses = make(chan [][]byte)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
if err := c.handleInput(ctx); err != nil {
c.logger.WithError(err).Error("input handling failed")
}
cancel()
wg.Done()
}()
go func() {
if err := c.handleCommands(ctx); err != nil {
c.logger.WithError(err).Error("command handling failed")
}
cancel()
wg.Done()
}()
var result error
if err := c.writeTestCommands(ctx); err != nil {
c.logger.WithError(err).Error("test commands failed")
}
cancel()
wg.Wait()
return result
}