go-tunnel/cmd/client/main.go

66 lines
1.2 KiB
Go

package main
import (
"context"
"flag"
"math/rand"
"time"
"cdr.dev/slog"
"forge.cadoles.com/wpetit/go-tunnel"
"gitlab.com/wpetit/goweb/logger"
)
const sharedKey = "go-tunnel"
const salt = "go-tunnel"
func main() {
var (
clientID string
)
flag.StringVar(&clientID, "id", "", "Client ID")
flag.Parse()
ctx := context.Background()
ctx = logger.With(ctx, logger.F("clientID", clientID))
logger.SetLevel(slog.LevelDebug)
client := tunnel.NewClient(
tunnel.WithClientCredentials(clientID),
tunnel.WithClientAESBlockCrypt(sharedKey, salt),
)
defer client.Close()
initialBackoff := time.Second * 10
backoff := initialBackoff
sleep := func() {
backoff = backoff*2 + (time.Duration(rand.Intn(int(initialBackoff))))
logger.Info(ctx, "sleeping", logger.F("duration", backoff))
time.Sleep(backoff)
}
for {
logger.Info(ctx, "connecting")
if err := client.Connect(ctx); err != nil {
logger.Error(ctx, "could not connect", logger.E(err))
sleep()
continue
}
logger.Info(ctx, "waiting for instructions")
if err := client.Listen(ctx); err != nil {
logger.Error(ctx, "error while listening", logger.E(err))
}
logger.Info(ctx, "connection lost")
sleep()
}
}