seed.c (1961B)
1 #include <cofyc/argparse.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 #include "common.h" 6 #include "registry.h" 7 #include "sfinx.h" 8 #include "util/file.h" 9 10 static int cmd_seed(int argc, const char **argv) { 11 const char *out_file = NULL; 12 int force = 0; 13 size_t length = CLI_SEED_LEN_DEFAULT; 14 uint8_t *seed = NULL; 15 sfinx_status status; 16 int rc = 0; 17 18 static const char *const usages[] = { 19 "sfinx seed [length] [-o file]", 20 NULL, 21 }; 22 struct argparse_option options[] = { 23 OPT_HELP(), 24 OPT_STRING('o', "out", &out_file, "write the seed to a file", NULL, 0, 0), 25 OPT_BOOLEAN(0, "force", &force, "overwrite an existing file", NULL, 0, 0), 26 OPT_END(), 27 }; 28 struct argparse argparse; 29 argparse_init(&argparse, options, usages, 0); 30 argparse_describe(&argparse, "\nGenerate a random seed", NULL); 31 argc = argparse_parse(&argparse, argc, argv); 32 33 if (argc > 1) { 34 fprintf(stderr, "sfinx: seed: too many arguments\n"); 35 return 1; 36 } 37 if (cli_seed_length(argc == 1 ? argv[0] : NULL, &length) != 0) { 38 fprintf(stderr, "sfinx: seed: invalid length: %s\n", argv[0]); 39 return 1; 40 } 41 42 status = cli_seed_random(length, &seed); 43 if (status != SFINX_OK) { 44 fprintf(stderr, "sfinx: seed: %s\n", sfinx_strerror(status)); 45 return 1; 46 } 47 48 if (out_file) { 49 if (util_file_write(out_file, seed, length, 0600, force) != 0) { 50 fprintf(stderr, "sfinx: seed: cannot write %s\n", out_file); 51 rc = 1; 52 } 53 } else if (fwrite(seed, 1, length, stdout) != length) { 54 rc = 1; 55 } 56 free(seed); 57 return rc; 58 } 59 60 static struct cli_command seed_command = { 61 .names = (const char *const[]){"seed", NULL}, 62 .display = "seed", 63 .description = "Generate a random seed", 64 .help = "sfinx seed [length] [-o file]", 65 .fn = cmd_seed, 66 }; 67 68 __attribute__((constructor)) static void seed_register(void) { 69 cli_command_register(&seed_command); 70 }