cacert-gosigner/cmd/clientsim/main.go

193 lines
3.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"
"fmt"
"log"
"os"
"sync"
"time"
"git.cacert.org/cacert-gosigner/pkg/messages"
"github.com/justincpresley/go-cobs"
"github.com/shamaton/msgpackgen/msgpack"
)
const cobsDelimiter = 0x00
var cobsConfig = cobs.Config{SpecialByte: cobsDelimiter, Delimiter: true, EndingSave: true}
func main() {
errorLog := log.New(os.Stderr, "", log.LstdFlags)
sim := &clientSimulator{
errorLog: errorLog,
}
err := sim.Run()
if err != nil {
errorLog.Printf("simulator returned an error: %v", err)
}
}
type clientSimulator struct {
errorLog *log.Logger
commands chan messages.Command
responses chan []byte
}
func (c *clientSimulator) writeTestCommands(ctx context.Context) error {
messages.RegisterGeneratedResolver()
const healthInterval = 10 * time.Second
timer := time.NewTimer(healthInterval)
for {
select {
case <-ctx.Done():
_ = timer.Stop()
return nil
case <-timer.C:
c.commands <- messages.Command{
Code: messages.CmdHealth,
TimeStamp: time.Now().UTC(),
}
timer.Reset(healthInterval)
}
}
}
func (c *clientSimulator) handleInput(ctx context.Context) error {
const (
bufferSize = 1024 * 1024
readInterval = 50 * time.Millisecond
)
buf := make([]byte, bufferSize)
for {
select {
case <-ctx.Done():
return nil
default:
count, err := os.Stdin.Read(buf)
if err != nil {
return err
}
if count == 0 {
time.Sleep(readInterval)
continue
}
data := buf[:count]
err = cobs.Verify(data, cobsConfig)
if err != nil {
return err
}
c.responses <- cobs.Decode(data, cobsConfig)
}
}
}
func (c *clientSimulator) handleCommands(ctx context.Context) error {
for {
select {
case command := <-c.commands:
commandBytes, err := msgpack.Marshal(command)
if err != nil {
return fmt.Errorf("could not marshal command bytes: %w", err)
}
_, err = os.Stdout.Write(cobs.Encode(commandBytes, cobsConfig))
if err != nil {
return fmt.Errorf("write failed: %w", err)
}
responseBytes := <-c.responses
var response messages.Response
err = msgpack.Unmarshal(responseBytes, &response)
if err != nil {
return fmt.Errorf("could not unmarshal msgpack data: %w", err)
}
c.errorLog.Printf("received response: %+v", response)
case <-ctx.Done():
return nil
}
}
}
func (c *clientSimulator) Run() error {
ctx, cancel := context.WithCancel(context.Background())
c.commands = make(chan messages.Command)
c.responses = make(chan []byte)
wg := sync.WaitGroup{}
wg.Add(2)
var inputError, commandError error
go func(inputErr error) {
inputError = c.handleInput(ctx)
cancel()
wg.Done()
}(inputError)
go func(commandErr error) {
commandErr = c.handleCommands(ctx)
cancel()
wg.Done()
}(commandError)
var result error
if err := c.writeTestCommands(ctx); err != nil {
c.errorLog.Printf("test commands failed: %v", err)
}
cancel()
wg.Wait()
if inputError != nil {
c.errorLog.Printf("reading input failed: %v", inputError)
}
if commandError != nil {
c.errorLog.Printf("sending commands failed: %v", commandError)
}
return result
}