1 /* $NetBSD: genrandom.c,v 1.7 2014/12/10 04:37:54 christos Exp $ */
4 * Copyright (C) 2004, 2005, 2007, 2009, 2010, 2012, 2014 Internet Systems Consortium, Inc. ("ISC")
5 * Copyright (C) 2000-2003 Internet Software Consortium.
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17 * PERFORMANCE OF THIS SOFTWARE.
20 /* Id: genrandom.c,v 1.7 2010/05/17 23:51:04 tbox Exp */
25 #include <isc/commandline.h>
26 #include <isc/print.h>
27 #include <isc/stdlib.h>
33 const char *program
= "genrandom";
35 ISC_PLATFORM_NORETURN_PRE
static void
36 usage(void) ISC_PLATFORM_NORETURN_POST
;
40 fprintf(stderr
, "usage: %s [-n 2..9] k file\n", program
);
45 generate(char *filename
, unsigned int bytes
) {
48 fp
= fopen(filename
, "w");
50 printf("failed to open %s\n", filename
);
55 #ifndef HAVE_ARC4RANDOM
56 unsigned short int x
= (rand() & 0xFFFF);
58 unsigned short int x
= (arc4random() & 0xFFFF);
60 unsigned char c
= x
& 0xFF;
61 if (putc(c
, fp
) == EOF
) {
62 printf("error writing to %s\n", filename
);
66 if (putc(c
, fp
) == EOF
) {
67 printf("error writing to %s\n", filename
);
76 main(int argc
, char **argv
) {
84 isc_commandline_errprint
= ISC_FALSE
;
86 while ((c
= isc_commandline_parse(argc
, argv
, "hn:")) != EOF
) {
89 n
= strtol(isc_commandline_argument
, &endp
, 10);
90 if ((*endp
!= 0) || (n
<= 1) || (n
> 9))
95 if (isc_commandline_option
!= '?')
96 fprintf(stderr
, "%s: invalid argument -%c\n",
97 program
, isc_commandline_option
);
103 fprintf(stderr
, "%s: unhandled option -%c\n",
104 program
, isc_commandline_option
);
109 if (isc_commandline_index
+ 2 != argc
)
112 k
= strtoul(argv
[isc_commandline_index
++], &endp
, 10);
117 #ifndef HAVE_ARC4RANDOM
121 generate(argv
[isc_commandline_index
], bytes
);
125 len
= strlen(argv
[isc_commandline_index
]);
126 INSIST((len
+ 2) > len
);
128 name
= (char *) malloc(len
);
134 for (i
= 1; i
<= n
; i
++) {
135 snprintf(name
, len
, "%s%d", argv
[isc_commandline_index
], i
);
136 generate(name
, bytes
);