From 70b189d75188fb38ce389fa94e09fcbb1156916e Mon Sep 17 00:00:00 2001 From: Atakan Yenel Date: Tue, 30 Mar 2021 14:27:57 +0200 Subject: [PATCH] crypto: add custom errors to crypto lib (#9522) --- vlib/crypto/rand/rand.v | 7 ++++--- vlib/crypto/rand/rand_darwin.c.v | 4 ++-- vlib/crypto/rand/rand_linux.c.v | 2 +- vlib/crypto/rand/rand_solaris.c.v | 2 +- vlib/crypto/rand/rand_windows.c.v | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/vlib/crypto/rand/rand.v b/vlib/crypto/rand/rand.v index 9ad4602fc0..070355859d 100644 --- a/vlib/crypto/rand/rand.v +++ b/vlib/crypto/rand/rand.v @@ -4,6 +4,7 @@ module rand -const ( - read_error = error('crypto.rand.read() error reading random bytes') -) +struct ReadError { + msg string = 'crypto.rand.read() error reading random bytes' + code int +} diff --git a/vlib/crypto/rand/rand_darwin.c.v b/vlib/crypto/rand/rand_darwin.c.v index c642ee4b28..a53198b578 100644 --- a/vlib/crypto/rand/rand_darwin.c.v +++ b/vlib/crypto/rand/rand_darwin.c.v @@ -12,10 +12,10 @@ fn C.SecRandomCopyBytes(rnd C.SecRandomRef, count size_t, bytes voidptr) int // read returns an array of `bytes_needed` random bytes read from the OS. pub fn read(bytes_needed int) ?[]byte { - mut buffer := []byte{ len: bytes_needed } + mut buffer := []byte{len: bytes_needed} status := C.SecRandomCopyBytes(C.SecRandomRef(0), bytes_needed, buffer.data) if status != 0 { - return read_error + return IError(&ReadError{}) } return buffer } diff --git a/vlib/crypto/rand/rand_linux.c.v b/vlib/crypto/rand/rand_linux.c.v index 53ab02c5ac..d3da4e02a5 100644 --- a/vlib/crypto/rand/rand_linux.c.v +++ b/vlib/crypto/rand/rand_linux.c.v @@ -19,7 +19,7 @@ pub fn read(bytes_needed int) ?[]byte { rbytes := unsafe { getrandom(batch_size, buffer + bytes_read) } if rbytes == -1 { unsafe { free(buffer) } - return read_error + return IError(&ReadError{}) } bytes_read += rbytes } diff --git a/vlib/crypto/rand/rand_solaris.c.v b/vlib/crypto/rand/rand_solaris.c.v index 09f1e43061..d2e84faf3c 100644 --- a/vlib/crypto/rand/rand_solaris.c.v +++ b/vlib/crypto/rand/rand_solaris.c.v @@ -23,7 +23,7 @@ pub fn read(bytes_needed int) ?[]byte { rbytes := unsafe { getrandom(batch_size, buffer + bytes_read) } if rbytes == -1 { unsafe { free(buffer) } - return read_error + return IError(&ReadError{}) } bytes_read += rbytes } diff --git a/vlib/crypto/rand/rand_windows.c.v b/vlib/crypto/rand/rand_windows.c.v index 24ad4b9409..a64dfc5a40 100644 --- a/vlib/crypto/rand/rand_windows.c.v +++ b/vlib/crypto/rand/rand_windows.c.v @@ -19,7 +19,7 @@ pub fn read(bytes_needed int) ?[]byte { // use bcrypt_use_system_preferred_rng because we passed null as algo status := C.BCryptGenRandom(0, buffer.data, bytes_needed, bcrypt_use_system_preferred_rng) if status != status_success { - return read_error + return IError(&ReadError{}) } return buffer }