cacert-gosigner/cmd/clientsim/main.go

302 lines
7 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 (
"context"
"crypto/rand"
"fmt"
"io"
"os"
"time"
"github.com/shamaton/msgpackgen/msgpack"
"github.com/sirupsen/logrus"
"git.cacert.org/cacert-gosigner/pkg/protocol"
"git.cacert.org/cacert-gosigner/pkg/messages"
)
type TestCommandGenerator struct {
logger *logrus.Logger
commands chan *protocol.Command
}
func (g *TestCommandGenerator) GenerateCommands(ctx context.Context) error {
var (
announce *messages.CommandAnnounce
err error
)
// write some leading garbage to test signer robustness
_, _ = io.CopyN(os.Stdout, rand.Reader, 50) //nolint:gomnd
announce, err = messages.BuildCommandAnnounce(messages.CmdHealth)
if err != nil {
return fmt.Errorf("build command announce failed: %w", err)
}
g.commands <- &protocol.Command{Announce: announce, Command: &messages.HealthCommand{}}
const (
healthInterval = 5 * time.Second
crlInterval = 15 * time.Minute
startPause = 3 * time.Second
)
g.logger.Info("start generating commands")
time.Sleep(startPause)
announce, err = messages.BuildCommandAnnounce(messages.CmdFetchCRL)
if err != nil {
return fmt.Errorf("build command announce failed: %w", err)
}
g.commands <- &protocol.Command{
Announce: announce,
Command: &messages.FetchCRLCommand{IssuerID: "sub-ecc_person_2022"},
}
healthTimer := time.NewTimer(healthInterval)
crlTimer := time.NewTimer(crlInterval)
for {
select {
case <-ctx.Done():
_ = healthTimer.Stop()
g.logger.Info("stopped health check loop")
_ = crlTimer.Stop()
g.logger.Info("stopped CRL fetch loop")
return nil
case <-healthTimer.C:
announce, err = messages.BuildCommandAnnounce(messages.CmdHealth)
if err != nil {
return fmt.Errorf("build command announce failed: %w", err)
}
g.commands <- &protocol.Command{
Announce: announce,
Command: &messages.HealthCommand{},
}
healthTimer.Reset(healthInterval)
case <-crlTimer.C:
g.commands <- &protocol.Command{
Announce: announce,
Command: &messages.FetchCRLCommand{IssuerID: "sub-ecc_person_2022"},
}
}
}
}
type clientSimulator struct {
clientHandler protocol.ClientHandler
framesIn chan []byte
framesOut chan []byte
framer protocol.Framer
commandGenerator *TestCommandGenerator
logger *logrus.Logger
}
const (
responseAnnounceTimeout = 30 * time.Second
responseDataTimeout = 2 * time.Second
)
func (c *clientSimulator) Run(ctx context.Context) error {
framerErrors := make(chan error)
protocolErrors := make(chan error)
generatorErrors := make(chan error)
go func() {
err := c.framer.ReadFrames(os.Stdin, c.framesIn)
framerErrors <- err
}()
go func() {
err := c.framer.WriteFrames(os.Stdout, c.framesOut)
framerErrors <- err
}()
go func() {
clientProtocol := protocol.NewClient(c.clientHandler, c.commandGenerator.commands, c.framesIn, c.framesOut, c.logger)
err := clientProtocol.Handle()
protocolErrors <- err
}()
go func() {
err := c.commandGenerator.GenerateCommands(ctx)
generatorErrors <- 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 := <-generatorErrors:
if err != nil {
return fmt.Errorf("error from command generator: %w", err)
}
return nil
case err := <-protocolErrors:
if err != nil {
return fmt.Errorf("error from protocol handler: %w", err)
}
return nil
}
}
}
type ClientHandler struct {
logger *logrus.Logger
}
func (c *ClientHandler) Send(command *protocol.Command, out chan []byte) error {
var (
frame []byte
err error
)
frame, err = msgpack.Marshal(command.Announce)
if err != nil {
return fmt.Errorf("could not marshal command annoucement: %w", err)
}
c.logger.WithField("announcement", command.Announce).Info("write command announcement")
c.logger.Trace("writing command announcement")
out <- frame
frame, err = msgpack.Marshal(command.Command)
if err != nil {
return fmt.Errorf("could not marshal command data: %w", err)
}
c.logger.WithField("command", command.Command).Info("write command data")
out <- frame
return nil
}
func (c *ClientHandler) ResponseAnnounce(in chan []byte) (*protocol.Response, error) {
response := &protocol.Response{}
var announce messages.ResponseAnnounce
select {
case frame := <-in:
if err := msgpack.Unmarshal(frame, &announce); err != nil {
return nil, fmt.Errorf("could not unmarshal response announcement: %w", err)
}
response.Announce = &announce
c.logger.WithField("announcement", response.Announce).Debug("received response announcement")
return response, nil
case <-time.After(responseAnnounceTimeout):
return nil, protocol.ErrResponseAnnounceTimeoutExpired
}
}
func (c *ClientHandler) ResponseData(in chan []byte, response *protocol.Response) error {
select {
case frame := <-in:
switch response.Announce.Code {
case messages.RespHealth:
var resp messages.HealthResponse
if err := msgpack.Unmarshal(frame, &resp); err != nil {
return fmt.Errorf("could not unmarshal health response data: %w", err)
}
response.Response = &resp
case messages.RespFetchCRL:
var resp messages.FetchCRLResponse
if err := msgpack.Unmarshal(frame, &resp); err != nil {
return fmt.Errorf("could not unmarshal fetch CRL response data: %w", err)
}
response.Response = &resp
default:
return fmt.Errorf("unhandled response code %s", response.Announce.Code)
}
case <-time.After(responseDataTimeout):
return protocol.ErrResponseDataTimeoutExpired
}
return nil
}
func (c *ClientHandler) HandleResponse(response *protocol.Response) error {
c.logger.WithField("response", response.Announce).Info("handled response")
c.logger.WithField("response", response).Debug("full response")
return nil
}
func newClientHandler(logger *logrus.Logger) *ClientHandler {
return &ClientHandler{logger: logger}
}
func main() {
logger := logrus.New()
logger.SetOutput(os.Stderr)
logger.SetLevel(logrus.DebugLevel)
messages.RegisterGeneratedResolver()
sim := &clientSimulator{
commandGenerator: &TestCommandGenerator{
logger: logger,
commands: make(chan *protocol.Command),
},
logger: logger,
framesIn: make(chan []byte),
framesOut: make(chan []byte),
framer: protocol.NewCOBSFramer(logger),
clientHandler: newClientHandler(logger),
}
err := sim.Run(context.Background())
if err != nil {
logger.WithError(err).Error("simulator returned an error")
}
}