1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
/*
* Copyright (c) 2024 Mitchell Riedstra
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* Since `tr` on MacOS cannot handle the binary stream.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define BUF_SIZE 64
#define MAX_OUT_CHARS 65534
void
help() {
puts("genid [-d <rand device>] [-n <numchars]");
exit(1);
}
int
main(int argc, char **argv)
{
const char *rdev = "/dev/urandom";
int chars = 8;
char **a = argv+1;
int fd, n;
char c;
int written = 0;
for (;*a;a++) {
if (strcmp(*a, "-d") == 0 && *(++a)) {
rdev = *a;
} else if (strcmp(*a, "-n") == 0 && *(++a)) {
const char *errstr;
chars = (int)strtonum(*a, 1, MAX_OUT_CHARS, &errstr);
if (errstr != NULL) {
printf("strtonum: %s\n", errstr);
help();
}
} else {
if (*a)
printf("Unknown option: '%s'\n", *a);
help();
}
}
fd = open(rdev, O_RDONLY);
if (fd == -1) {
perror("opening random device");
exit(1);
}
char buf[BUF_SIZE];
for (int i=0; written<chars && i<1000; i++) {
n = read(fd, &buf, BUF_SIZE-1);
if (n == -1) {
perror("read");
exit(1);
}
for (int j = 0; j<n && j<BUF_SIZE && written<chars; j++) {
c = buf[j];
if (
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9')
) {
written++;
putc(c, stdout);
}
}
}
puts("");
close(fd);
}
|