/* 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 handler import ( "context" "errors" "fmt" "math/big" "time" "github.com/shamaton/msgpackgen/msgpack" "github.com/sirupsen/logrus" "git.cacert.org/cacert-gosigner/pkg/protocol" "git.cacert.org/cacert-gosigner/internal/health" "git.cacert.org/cacert-gosigner/internal/x509/revoking" "git.cacert.org/cacert-gosigner/pkg/messages" ) const readCommandTimeOut = 5 * time.Second var errReadCommandTimeout = errors.New("read command timeout expired") // MsgPackHandler is a ServerHandler implementation for the msgpack serialization format. type MsgPackHandler struct { logger *logrus.Logger healthHandler *health.Handler fetchCRLHandler *revoking.FetchCRLHandler } func (m *MsgPackHandler) CommandAnnounce(ctx context.Context, frames chan []byte) (*protocol.Command, error) { select { case <-ctx.Done(): return nil, nil case frame := <-frames: var ann messages.CommandAnnounce if err := msgpack.Unmarshal(frame, &ann); err != nil { return nil, fmt.Errorf("could not unmarshal command announcement: %w", err) } if ann.Code == messages.CmdUndef { return nil, fmt.Errorf("received undefined command announcement: %s", ann) } m.logger.WithField("announcement", &ann).Debug("received command announcement") return &protocol.Command{Announce: &ann}, nil } } func (m *MsgPackHandler) CommandData(ctx context.Context, frames chan []byte, command *protocol.Command) error { select { case <-ctx.Done(): return nil case frame := <-frames: err := m.parseCommand(frame, command) if err != nil { return err } return nil case <-time.After(readCommandTimeOut): return errReadCommandTimeout } } func (m *MsgPackHandler) HandleCommand(_ context.Context, command *protocol.Command) (*protocol.Response, error) { var ( response *protocol.Response err error ) response, err = m.handleCommand(command) if err != nil { m.logger.WithError(err).Error("command handling failed") response = m.buildErrorResponse(command.Announce.ID, "command handling failed") } m.logCommandResponse(command, response) return response, nil } func (m *MsgPackHandler) logCommandResponse(command *protocol.Command, response *protocol.Response) { m.logger.WithField("command", command.Announce).Info("handled command") m.logger.WithField("command", command).WithField("response", response).Debug("command and response") } func (m *MsgPackHandler) Respond(ctx context.Context, response *protocol.Response, out chan []byte) error { announce, err := msgpack.Marshal(response.Announce) if err != nil { return fmt.Errorf("could not marshal response announcement: %w", err) } m.logger.WithField("length", len(announce)).Debug("write response announcement") select { case <-ctx.Done(): return nil case out <- announce: break } data, err := msgpack.Marshal(response.Response) if err != nil { return fmt.Errorf("could not marshal response: %w", err) } m.logger.WithField("length", len(data)).Debug("write response") select { case <-ctx.Done(): return nil case out <- data: break } return nil } func (m *MsgPackHandler) parseHealthCommand(frame []byte) (*messages.HealthCommand, error) { var command messages.HealthCommand if err := msgpack.Unmarshal(frame, &command); err != nil { m.logger.WithError(err).Error("unmarshal failed") return nil, errors.New("could not unmarshal health command") } return &command, nil } func (m *MsgPackHandler) parseFetchCRLCommand(frame []byte) (*messages.FetchCRLCommand, error) { var command messages.FetchCRLCommand if err := msgpack.Unmarshal(frame, &command); err != nil { m.logger.WithError(err).Error("unmarshal failed") return nil, errors.New("could not unmarshal fetch crl command") } return &command, nil } func (m *MsgPackHandler) handleCommand(command *protocol.Command) (*protocol.Response, error) { var ( responseCode messages.ResponseCode responseData interface{} ) switch cmd := command.Command.(type) { case *messages.HealthCommand: response, err := m.handleHealthCommand() if err != nil { return nil, err } responseCode, responseData = messages.RespHealth, response case *messages.FetchCRLCommand: response, err := m.handleFetchCRLCommand(cmd) if err != nil { return nil, err } responseCode, responseData = messages.RespFetchCRL, response default: return nil, fmt.Errorf("unhandled command %s", command.Announce) } return &protocol.Response{ Announce: messages.BuildResponseAnnounce(responseCode, command.Announce.ID), Response: responseData, }, nil } func (m *MsgPackHandler) buildErrorResponse(commandID string, errMsg string) *protocol.Response { return &protocol.Response{ Announce: messages.BuildResponseAnnounce(messages.RespError, commandID), Response: &messages.ErrorResponse{Message: errMsg}, } } func (m *MsgPackHandler) parseCommand(frame []byte, command *protocol.Command) error { switch command.Announce.Code { case messages.CmdHealth: healthCommand, err := m.parseHealthCommand(frame) if err != nil { return err } command.Command = healthCommand case messages.CmdFetchCRL: fetchCRLCommand, err := m.parseFetchCRLCommand(frame) if err != nil { return err } command.Command = fetchCRLCommand default: return fmt.Errorf("unhandled command code %s", command.Announce.Code) } return nil } func (m *MsgPackHandler) handleHealthCommand() (*messages.HealthResponse, error) { res, err := m.healthHandler.CheckHealth() if err != nil { return nil, fmt.Errorf("could not check health: %w", err) } response := &messages.HealthResponse{ Version: res.Version, Healthy: res.Healthy, } for _, info := range res.Info { response.Info = append(response.Info, &messages.HealthInfo{ Source: info.Source, Healthy: info.Healthy, MoreInfo: info.MoreInfo, }) } return response, nil } func (m *MsgPackHandler) handleFetchCRLCommand(command *messages.FetchCRLCommand) (*messages.FetchCRLResponse, error) { var crlNumber *big.Int if command.LastKnownID != nil { crlNumber = new(big.Int).SetBytes(command.LastKnownID) } res, err := m.fetchCRLHandler.FetchCRL(command.IssuerID, crlNumber) if err != nil { return nil, fmt.Errorf("could not fetch CRL: %w", err) } unchanged := crlNumber != nil && crlNumber.Cmp(res.Number) == 0 response := &messages.FetchCRLResponse{ IssuerID: command.IssuerID, IsDelta: res.IsDelta, UnChanged: unchanged, CRLNumber: res.Number.Bytes(), } if !unchanged { response.CRLData = res.CRLData } return response, nil } func New(logger *logrus.Logger, handlers ...RegisterHandler) (protocol.ServerHandler, error) { messages.RegisterGeneratedResolver() h := &MsgPackHandler{ logger: logger, } for _, reg := range handlers { reg(h) } return h, nil } type RegisterHandler func(handler *MsgPackHandler) func RegisterHealthHandler(healthHandler *health.Handler) func(*MsgPackHandler) { return func(h *MsgPackHandler) { h.healthHandler = healthHandler } } func RegisterFetchCRLHandler(fetchCRLHandler *revoking.FetchCRLHandler) func(handler *MsgPackHandler) { return func(h *MsgPackHandler) { h.fetchCRLHandler = fetchCRLHandler } }