Skip to content

Commit

Permalink
Augment rand argument parsing to allow scaling
Browse files Browse the repository at this point in the history
Instead of just accepting a number of bytes, allows openssl rand to
accept a k|m|g suffix to scale to kbytes/mbytes/gbytes

Fixes #22622
  • Loading branch information
nhorman committed Nov 5, 2023
1 parent 1aa0864 commit e168aeb
Showing 1 changed file with 42 additions and 4 deletions.
46 changes: 42 additions & 4 deletions apps/rand.c
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@ int rand_main(int argc, char **argv)
BIO *out = NULL;
char *outfile = NULL, *prog;
OPTION_CHOICE o;
int format = FORMAT_BINARY, r, i, ret = 1, buflen = 131072;
int format = FORMAT_BINARY, r, i, ret = 1;
size_t buflen = 131072;
long num = -1;
size_t scaled_num;
uint8_t *buf = NULL;

prog = opt_init(argc, argv, rand_options);
Expand Down Expand Up @@ -95,8 +97,44 @@ int rand_main(int argc, char **argv)
argc = opt_num_rest();
argv = opt_rest();
if (argc == 1) {
int factoridx = 0;
int scale = 0;
/*
* iterate over the value and check to see if there are
* any non-numerical chars
*/
while (argv[0][factoridx]) {
if (!isdigit(argv[0][factoridx])) {
switch(argv[0][factoridx]) {
case 'k':
scale = 1;
break;
case 'm':
scale = 2;
break;
case 'g':
scale = 3;
break;
default:
goto opthelp;
}
break;
}
factoridx++;
}
if (scale != 0)
argv[0][factoridx] = '\0';

if (!opt_long(argv[0], &num) || num <= 0)
goto opthelp;

if (scale != 0) {
scaled_num = num * (1 << (scale * 10));
if (scaled_num < num)
goto opthelp;
} else {
scaled_num = num;
}
} else if (!opt_check_rest_arg(NULL)) {
goto opthelp;
}
Expand All @@ -116,10 +154,10 @@ int rand_main(int argc, char **argv)
}

buf = app_malloc(buflen, "buffer for output file");
while (num > 0) {
while (scaled_num > 0) {
long chunk;

chunk = (num > buflen) ? buflen : num;
chunk = (scaled_num > buflen) ? buflen : scaled_num;
r = RAND_bytes(buf, chunk);
if (r <= 0)
goto end;
Expand All @@ -131,7 +169,7 @@ int rand_main(int argc, char **argv)
if (BIO_printf(out, "%02x", buf[i]) != 2)
goto end;
}
num -= chunk;
scaled_num -= chunk;
}
if (format == FORMAT_TEXT)
BIO_puts(out, "\n");
Expand Down

0 comments on commit e168aeb

Please sign in to comment.