Compare commits

..

1 Commits

Author SHA1 Message Date
94d31e829e
Prevent dice overflow
rand.Int() would panic when the max value is <= 0, which happens when
big.NewInt() was fed with a too large number. Avoid this by validating
the big.NewInt() return beforehand. Add error handling to all callers to
both gracefully return to IRC and to log an error message.

Signed-off-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
2024-10-10 02:33:42 +02:00

View File

@ -2,6 +2,7 @@ package wat
import ( import (
"crypto/rand" "crypto/rand"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"strconv" "strconv"
@ -121,11 +122,11 @@ func (g *WatGame) help() string {
return ret return ret
} }
func (g *WatGame) RandInt(maxx int64) (uint64, error) { func (g *WatGame) RandInt(max int64) (uint64, error) {
bi := big.NewInt(maxx) bi := big.NewInt(max)
// prevent panic of rand.Int on big numbers // prevent panic of rand.Int on big numbers
if bi.BitLen() < 2 { if bi.BitLen() < 2 {
return 0, fmt.Errorf("overflow, got %d", bi) return 0, errors.New("overflow")
} }
i, err := rand.Int(rand.Reader, bi) i, err := rand.Int(rand.Reader, bi)
if err != nil { if err != nil {