net_util: Replace use of rand crate with libc::getrandom()

The rand crate provides a full cross platform true cryptographic random
number implementation. As such it brings it lots of othe dependencies
and increases our binary size and compile time. This is excessive for
generating a MAC address.

From the cargo tree output:

│   │   ├── rand v0.8.3
│   │   │   ├── libc v0.2.86
│   │   │   ├── rand_chacha v0.3.0
│   │   │   │   ├── ppv-lite86 v0.2.10
│   │   │   │   └── rand_core v0.6.0
│   │   │   │       └── getrandom v0.2.0
│   │   │   │           ├── cfg-if v0.1.10
│   │   │   │           └── libc v0.2.86
│   │   │   └── rand_core v0.6.0 (*)

And cargo bloat:

 0.0%   0.4% 40.4KiB rand_chacha rand_chacha::guts::refill_wide::impl_sse2
 0.0%   0.4% 40.0KiB rand_chacha rand_chacha::guts::refill_wide::impl_ssse3
 0.0%   0.3% 37.6KiB rand_chacha rand_chacha::guts::refill_wide::impl_avx
 0.0%   0.3% 37.2KiB rand_chacha rand_chacha::guts::refill_wide::impl_sse41
 0.0%   0.2% 26.1KiB rand_chacha rand_chacha::guts::refill_wide::impl_avx2

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
This commit is contained in:
Rob Bradford 2021-02-22 15:02:19 +00:00
parent d361fc1a36
commit c1be41bfbf
4 changed files with 16 additions and 5 deletions

1
Cargo.lock generated
View File

@ -702,7 +702,6 @@ dependencies = [
"log 0.4.14",
"net_gen",
"pnet",
"rand 0.8.3",
"serde",
"serde_json",
"virtio-bindings",

View File

@ -8,7 +8,6 @@ epoll = ">=4.0.1"
libc = "0.2.86"
log = "0.4.14"
net_gen = { path = "../net_gen" }
rand = "0.8.3"
serde = "1.0.123"
virtio-bindings = "0.1.0"
vm-memory = { version = "0.5.0", features = ["backend-mmap", "backend-atomic"] }

View File

@ -14,7 +14,6 @@ extern crate libc;
#[macro_use]
extern crate log;
extern crate net_gen;
extern crate rand;
extern crate serde;
extern crate virtio_bindings;
extern crate vm_memory;

View File

@ -5,7 +5,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use rand::Rng;
use std::fmt;
use std::io;
use std::result::Result;
@ -82,7 +81,22 @@ impl MacAddr {
pub fn local_random() -> MacAddr {
// Generate a fully random MAC
let mut random_bytes = rand::thread_rng().gen::<[u8; MAC_ADDR_LEN]>();
let mut random_bytes = [0u8; MAC_ADDR_LEN];
unsafe {
// Man page says this function will not be interrupted by a signal
// for requests less than 256 bytes
if libc::getrandom(
random_bytes.as_mut_ptr() as *mut _ as *mut libc::c_void,
MAC_ADDR_LEN,
0,
) < 0
{
error!(
"Error populating MAC address with random data: {}",
std::io::Error::last_os_error()
)
}
};
// Set the first byte to make the OUI a locally administered OUI
random_bytes[0] = 0x2e;