+
+ base64_init(&b);
+ if (line) { b.indent = "\n"; b.maxline = line; }
+ else { b.indent = ""; b.maxline = 0; }
+ do_format(n, line, &b, do_base64, fix);
+}
+static void format_base64(size_t n, unsigned line)
+ { do_format_base64(n, line, 0); }
+
+static void do_base32(void *ctx, char *p, size_t sz, dstr *d)
+ { base32_encode(ctx, p, sz, d); }
+static void format_base32(size_t n, unsigned line)
+{
+ base32_ctx b;
+
+ base32_init(&b);
+ if (line) { b.indent = "\n"; b.maxline = line; }
+ else { b.indent = ""; b.maxline = 0; }
+ do_format(n, line, &b, do_base32, 0);
+}
+
+static void fix_file64(char *p, size_t n)
+{
+ while (n) {
+ if (*p == '/') *p = '%';
+ p++; n--;
+ }
+}
+static void format_file64(size_t n, unsigned line)
+ { do_format_base64(n, line, fix_file64); }
+
+static void fix_safe64(char *p, size_t n)
+{
+ while (n) {
+ if (*p == '+') *p = '-';
+ else if (*p == '/') *p = '_';
+ p++; n--;
+ }
+}
+static void format_safe64(size_t n, unsigned line)
+ { do_format_base64(n, line, fix_safe64); }
+
+static void do_hex(void *ctx, char *p, size_t sz, dstr *d)
+ { hex_encode(ctx, p, sz, d); }
+static void format_hex(size_t n, unsigned line)
+{
+ hex_ctx b;
+
+ hex_init(&b);
+ if (line) { b.indent = "\n"; b.maxline = line; }
+ else { b.indent = ""; b.maxline = 0; }
+ do_format(n, line, &b, do_hex, 0);
+}
+
+static void format_raw(size_t n, unsigned line)
+{
+ unsigned char buf[CHUNK];
+
+ while (n) {
+ size_t nn = CHUNK;
+ if (nn > n) nn = n;
+ rand_get(RAND_GLOBAL, buf, nn);
+ fwrite(buf, 1, nn, stdout);
+ n -= nn;
+ }
+}
+
+static const struct format fmt[] = {
+ { "base64", format_base64 },
+ { "file64", format_file64 },
+ { "safe64", format_safe64 },
+ { "base32", format_base32 },
+ { "hex", format_hex },
+ { "raw", format_raw },
+ { 0, 0 }
+};
+
+static int uarg(const char *p, const char *what)
+{
+ unsigned long x;
+ char *q;
+ errno = 0;
+ x = strtoul(p, &q, 0);
+ if (*q || errno || x > INT_MAX) die(EXIT_FAILURE, "bad %s", what);
+ return (x);
+}
+
+static void version(FILE *fp)
+{
+ pquis(stderr, "$, version " VERSION "\n");
+}
+
+static void usage(FILE *fp)
+{
+ pquis(stderr, "Usage: $ [-y] [-l LEN] [-f FORMAT] [BITS]\n");
+}
+
+static void help(FILE *fp)
+{
+ version(fp);
+ putc('\n', fp);
+ usage(fp);
+ fputs("\n\
+Generates a random string, and prints it to standard output.\n\
+\n\
+Options:\n\
+\n\
+-h, --help Print this help message.\n\
+-v, --version Print program version number.\n\
+-u, --usage Print short usage summary.\n\
+\n\
+-y, --bytes Output length is bytes, not bits.\n\
+-l, --line=LENGTH For textual output, limit line length to LENGTH.\n\
+-f, --format=FORMAT Select output format:\n\
+ base64, file64, safe64, base32, hex, raw.\n\
+", stdout);
+}
+
+int main(int argc, char *argv[])
+{