Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
main.go 2.42 KiB
package main

import (
	"flag"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"

	"code.fbi.h-da.de/danet/quant/quantumlayer"
	pb "code.fbi.h-da.de/danet/quipsec/gen/go/quipsec"
	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"gopkg.in/yaml.v3"
)

type Config struct {
	KMSAddr      string `yaml:"KMSAddr"`
	UDPAddr      string `yaml:"UDPAddr"`
	PeerUDPAddr  string `yaml:"PeerUDPAddr"`
	GenerateKeys bool   `yaml:"GenerateKeys"`
}

func main() {
	// TODO: flag validation
	configPath := flag.String("config", "", "path to the config file")
	logLevel := flag.String("log", "", "logrus lof level (debug, info, warn, error, fatal, panic)")
	flag.Parse()

	// parse string, this is built-in feature of logrus
	ll, err := logrus.ParseLevel(*logLevel)
	if err != nil {
		ll = logrus.InfoLevel
		logrus.Warn("Invalid log level, using default: ", ll)
	}

	// set global log level
	logrus.SetLevel(ll)
	logrus.Info("Setting log level to ", ll)

	// unmarshal config
	config := &Config{}
	file, err := os.ReadFile(*configPath)
	if err != nil {
		logrus.Fatal(err)
	}
	if err := yaml.Unmarshal(file, config); err != nil {
		logrus.Fatal(err)
	}

	const connectionRetries = 60

	// Connect to KMS
	logrus.Info("Connecting to KMS ", config.KMSAddr)
	var newPeerConn *grpc.ClientConn
	for i := 0; i < connectionRetries; i++ {
		newPeerConn, err = grpc.Dial(config.KMSAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
		if err == nil {
			logrus.Info("Connected to KMS")
			break
		}
		logrus.Errorf("Failed to connect to KMS, retrying in 2 seconds (attempt %d/%d)", i+1, connectionRetries)
		time.Sleep(2 * time.Second)
	}

	kmsClient := pb.NewKmsQkdmCommunicationServiceClient(newPeerConn)

	// Connect to peer quantumlayer
	logrus.Info("Connecting to KMS ", config.KMSAddr)
	var peerUDPAddr *net.UDPAddr
	for i := 0; i < connectionRetries; i++ {
		peerUDPAddr, err = net.ResolveUDPAddr("udp", config.PeerUDPAddr)
		if err == nil {
			logrus.Info("Connected to peer quantumlayer")
			break
		}
		logrus.Errorf("Failed to connect to peer quantumlayer with error: %s, retrying in 2 seconds", err.Error())
		time.Sleep(2 * time.Second)
	}

	stopChan := make(chan os.Signal, 1)
	signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)

	ql := quantumlayer.NewQuantumlayerEmuPRNG(kmsClient, os.Stdout, logrus.GetLevel(), false)
	ql.Configure(config.GenerateKeys, config.UDPAddr)
	ql.PowerOn()
	ql.AddPeer(peerUDPAddr)

	<-stopChan
}