aboutsummaryrefslogtreecommitdiff
path: root/pm-genid.c
diff options
context:
space:
mode:
Diffstat (limited to 'pm-genid.c')
-rw-r--r--pm-genid.c95
1 files changed, 95 insertions, 0 deletions
diff --git a/pm-genid.c b/pm-genid.c
new file mode 100644
index 0000000..5a481ce
--- /dev/null
+++ b/pm-genid.c
@@ -0,0 +1,95 @@
+/*
+ * 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>
+
+#if __linux__
+ #include "compat/strtonum.c"
+#endif
+
+#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);
+}