2 * random bit generation for scripts, control files, etc.
3 * Copyright (C) 1998, 1999, 2000 Henry Spencer.
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * RCSID $Id: ranbits.c,v 1.9 2002/03/08 00:46:57 henry Exp $
18 #include <sys/types.h>
26 #include <netinet/in.h>
30 #define DEVICE "/dev/random"
33 #define QDEVICE "/dev/urandom"
39 char usage[] = "Usage: ranbits [--quick] [--continuous] [--bytes] nbits";
40 struct option opts[] = {
41 "quick", 0, NULL, 'q',
42 "continuous", 0, NULL, 'c',
43 "bytes", 0, NULL, 'b',
45 "version", 0, NULL, 'v',
48 int quick = 0; /* quick and dirty? */
49 char format = 'h'; /* datatot() format code */
50 int isbytes = 0; /* byte count rather than bits? */
52 char me[] = "ipsec ranbits"; /* for messages */
53 char cop[] = "See `ipsec --copyright' for copyright information.";
55 char buf[MAXBITS/CHAR_BIT];
56 char outbuf[3*sizeof(buf)];
73 while ((opt = getopt_long(argc, argv, "", opts, NULL)) != EOF)
75 case 'q': /* quick and dirty randomness */
78 case 'c': /* continuous hex, no underscores */
81 case 'b': /* byte count, not bit count */
85 printf("%s\n", usage);
88 case 'v': /* version */
89 printf("%s %s\n", me, ipsec_version_code());
98 if (errflg || optind != argc-1) {
99 fprintf(stderr, "%s\n", usage);
103 nbits = atoi(argv[optind]);
107 fprintf(stderr, "%s: invalid bit count (%d)\n", me, nbits);
110 if (nbits > MAXBITS) {
111 fprintf(stderr, "%s: overlarge bit count (max %d)\n", me,
115 nbytes = (size_t)(nbits + CHAR_BIT - 1) / CHAR_BIT;
117 devname = (quick) ? QDEVICE : DEVICE;
118 dev = open(devname, 0);
120 fprintf(stderr, "%s: could not open %s (%s)\n", me,
121 devname, strerror(errno));
126 while (ndone < nbytes) {
127 got = read(dev, buf + ndone, nbytes - ndone);
129 fprintf(stderr, "%s: read error on %s (%s)\n", me,
130 devname, strerror(errno));
134 fprintf(stderr, "%s: eof on %s!?!\n", me, devname);
140 nneeded = datatot(buf, nbytes, format, outbuf, sizeof(outbuf));
141 if (nneeded > sizeof(outbuf)) {
142 fprintf(stderr, "%s: buffer overflow (need %ld bytes)?!?\n",
146 printf("%s\n", outbuf);