From 33fc6ed615959c241493d8079c07253ffcc7f245 Mon Sep 17 00:00:00 2001 From: mischa Date: Thu, 14 Apr 2022 23:51:45 +0000 Subject: vm/vmimpl: improve port selection Selecting the monitor port for qemu using an unseeded pseudo-random generator can lead to failed VM startups, as the code contains race conditions. This happens frequently if multiple instances are started with a script. Using real random ports provided by crypto/rand reduces the risk of failing VM starts. --- vm/vmimpl/vmimpl.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'vm/vmimpl/vmimpl.go') diff --git a/vm/vmimpl/vmimpl.go b/vm/vmimpl/vmimpl.go index 854bef0a0..5ec84b35d 100644 --- a/vm/vmimpl/vmimpl.go +++ b/vm/vmimpl/vmimpl.go @@ -8,10 +8,11 @@ package vmimpl import ( + "crypto/rand" "errors" "fmt" "io" - "math/rand" + "math/big" "net" "os/exec" "strings" @@ -169,7 +170,11 @@ func Multiplex(cmd *exec.Cmd, merger *OutputMerger, console io.Closer, timeout t } func RandomPort() int { - return rand.Intn(64<<10-1<<10) + 1<<10 + n, err := rand.Int(rand.Reader, big.NewInt(64<<10-1<<10)) + if err != nil { + panic(err) + } + return int(n.Int64()) + 1<<10 } func UnusedTCPPort() int { -- cgit mrf-deployment