This shrinks the length of bg_setenv.c.

The resulting dependency graph is as follows:

- bg_envtools: depends on bg_envtools.h
- bg_printenv: depends on bg_envtools.h, bg_printenv.h
- bg_setenv: depends on bg_envtools.h, bg_printenv.h, bg_setenv.h
- main: depends on bg_printenv.h, bg_setenv.h

This makes it clear from the dependency graph what each tool does and
speeds up incremental compilation.

Co-authored-by: Jan Kiszka <[email protected]>
Signed-off-by: Michael Adler <[email protected]>
---
 Makefile.am         |   5 +-
 tools/bg_envtools.c | 158 +++++++++++++
 tools/bg_envtools.h |  58 +++++
 tools/bg_printenv.c | 369 +++++++++++++++++++++++++++++
 tools/bg_printenv.h |  38 +++
 tools/bg_setenv.c   | 557 ++------------------------------------------
 tools/bg_setenv.h   |  23 ++
 tools/main.c        |  26 +++
 8 files changed, 689 insertions(+), 545 deletions(-)
 create mode 100644 tools/bg_envtools.c
 create mode 100644 tools/bg_envtools.h
 create mode 100644 tools/bg_printenv.c
 create mode 100644 tools/bg_printenv.h
 create mode 100644 tools/bg_setenv.h
 create mode 100644 tools/main.c

diff --git a/Makefile.am b/Makefile.am
index 2a5f8f8..8081839 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -104,7 +104,10 @@ libebgenv_la_LDFLAGS = -release $(LIBEBGENV_SO_VERSION).0
 bin_PROGRAMS = bg_setenv
 
 bg_setenv_SOURCES = \
-       tools/bg_setenv.c
+       tools/bg_setenv.c \
+       tools/bg_printenv.c \
+       tools/bg_envtools.c \
+       tools/main.c
 
 bg_setenv_CFLAGS = \
        $(AM_CFLAGS) -static
diff --git a/tools/bg_envtools.c b/tools/bg_envtools.c
new file mode 100644
index 0000000..b81ffed
--- /dev/null
+++ b/tools/bg_envtools.c
@@ -0,0 +1,158 @@
+/*
+ * EFI Boot Guard
+ *
+ * Copyright (c) Siemens AG, 2017-2021
+ *
+ * Authors:
+ *  Andreas Reichel <[email protected]>
+ *  Michael Adler <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier:    GPL-2.0
+ */
+
+#include <sys/stat.h>
+#include "env_config_file.h"
+#include "version.h"
+
+#include "bg_envtools.h"
+
+static char *ustatemap[] = {"OK", "INSTALLED", "TESTING", "FAILED", "UNKNOWN"};
+
+char *ustate2str(uint8_t ustate)
+{
+       if (ustate > USTATE_MAX) {
+               ustate = USTATE_MAX;
+       }
+       return ustatemap[ustate];
+}
+
+uint8_t str2ustate(char *str)
+{
+       uint8_t i;
+
+       if (!str) {
+               return USTATE_UNKNOWN;
+       }
+       for (i = USTATE_MIN; i < USTATE_MAX; i++) {
+               if (strncasecmp(str, ustatemap[i], strlen(ustatemap[i])) == 0) {
+                       return i;
+               }
+       }
+       return USTATE_UNKNOWN;
+}
+
+int parse_int(char *arg)
+{
+       char *tmp;
+       long i;
+
+       errno = 0;
+       i = strtol(arg, &tmp, 10);
+       if (errno == ERANGE ||            /* out of range */
+           (errno != 0 && i == 0) ||     /* no conversion was performed */
+           tmp == arg || *tmp != '\0' || /* invalid input */
+           i < INT_MIN || i > INT_MAX) { /* not a valid int */
+               errno = EINVAL;
+               return -1;
+       }
+       return (int)i;
+}
+
+error_t parse_common_opt(int key, char *arg, bool compat_mode,
+                        struct arguments_common *arguments)
+{
+       bool found = false;
+       int i;
+       switch (key) {
+       case 'f':
+               found = true;
+               free(arguments->envfilepath);
+               arguments->envfilepath = NULL;
+
+               if (compat_mode) {
+                       /* compat mode, permitting "bg_setenv -f <dir>" */
+                       struct stat sb;
+
+                       int res = stat(arg, &sb);
+                       if (res == 0 && S_ISDIR(sb.st_mode)) {
+                               fprintf(stderr,
+                                       "WARNING: Using -f to specify only the "
+                                       "ouptut directory is deprecated.\n");
+                               res = asprintf(&arguments->envfilepath, "%s/%s",
+                                              arg, FAT_ENV_FILENAME);
+                               if (res == -1) {
+                                       return ENOMEM;
+                               }
+                       }
+               }
+
+               if (!arguments->envfilepath) {
+                       arguments->envfilepath = strdup(arg);
+                       if (!arguments->envfilepath) {
+                               return ENOMEM;
+                       }
+               }
+               break;
+       case 'p':
+               found = true;
+               i = parse_int(arg);
+               if (errno) {
+                       fprintf(stderr, "Invalid number specified for -p.\n");
+                       return 1;
+               }
+               if (i >= 0 && i < ENV_NUM_CONFIG_PARTS) {
+                       arguments->which_part = i;
+                       arguments->part_specified = true;
+               } else {
+                       fprintf(stderr,
+                               "Selected partition out of range. Valid range: "
+                               "0..%d.\n",
+                               ENV_NUM_CONFIG_PARTS - 1);
+                       return 1;
+               }
+               break;
+       case 'v':
+               found = true;
+               /* Set verbosity in this program */
+               arguments->verbosity = true;
+               /* Set verbosity in the library */
+               bgenv_be_verbose(true);
+               break;
+       case 'V':
+               found = true;
+               fprintf(stdout, "EFI Boot Guard %s\n", EFIBOOTGUARD_VERSION);
+               exit(0);
+       }
+       if (!found) {
+               return ARGP_ERR_UNKNOWN;
+       }
+       return 0;
+}
+
+bool get_env(char *configfilepath, BG_ENVDATA *data)
+{
+       FILE *config;
+       bool result = true;
+
+       if (!(config = open_config_file(configfilepath, "rb"))) {
+               return false;
+       }
+
+       if (!(fread(data, sizeof(BG_ENVDATA), 1, config) == 1)) {
+               VERBOSE(stderr, "Error reading environment data from %s\n",
+                       configfilepath);
+               if (feof(config)) {
+                       VERBOSE(stderr, "End of file encountered.\n");
+               }
+               result = false;
+       }
+
+       if (close_config_file(config)) {
+               VERBOSE(stderr,
+                       "Error closing environment file after reading.\n");
+       };
+       return result;
+}
diff --git a/tools/bg_envtools.h b/tools/bg_envtools.h
new file mode 100644
index 0000000..a397ca4
--- /dev/null
+++ b/tools/bg_envtools.h
@@ -0,0 +1,58 @@
+/*
+ * EFI Boot Guard
+ *
+ * Copyright (c) Siemens AG, 2017-2021
+ *
+ * Authors:
+ *  Andreas Reichel <[email protected]>
+ *  Michael Adler <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier:    GPL-2.0
+ */
+
+#ifndef __bg_envtools_h_
+#define __bg_envtools_h_
+
+#include "env_api.h"
+
+#define OPT(name, key, arg, flags, doc)                                        
\
+       {                                                                      \
+               name, key, arg, flags, doc                                     \
+       }
+
+#define BG_CLI_OPTIONS_COMMON                                                  
\
+       OPT("filepath", 'f', "ENVFILE", 0,                                     \
+           "Environment to use. Expects a file name, "                        \
+           "usually called BGENV.DAT.")                                       \
+       , OPT("part", 'p', "ENV_PART", 0,                                      \
+             "Set environment partition to update. If no partition is "       \
+             "specified, "                                                    \
+             "the one with the smallest revision value above zero is "        \
+             "updated.")                                                      \
+       , OPT("verbose", 'v', 0, 0, "Be verbose")                              \
+       , OPT("version", 'V', 0, 0, "Print version")
+
+/* Common arguments used by both bg_setenv and bg_printenv. */
+struct arguments_common {
+       char *envfilepath;
+       bool verbosity;
+       /* which partition to operate on; a negative value means no partition
+        * was specified. */
+       int which_part;
+       bool part_specified;
+};
+
+int parse_int(char *arg);
+
+char *ustate2str(uint8_t ustate);
+uint8_t str2ustate(char *str);
+
+error_t parse_common_opt(int key, char *arg, bool compat_mode,
+                        struct arguments_common *arguments);
+
+bool get_env(char *configfilepath, BG_ENVDATA *data);
+
+#endif
diff --git a/tools/bg_printenv.c b/tools/bg_printenv.c
new file mode 100644
index 0000000..61152dc
--- /dev/null
+++ b/tools/bg_printenv.c
@@ -0,0 +1,369 @@
+/*
+ * EFI Boot Guard
+ *
+ * Copyright (c) Siemens AG, 2017-2021
+ *
+ * Authors:
+ *  Andreas Reichel <[email protected]>
+ *  Michael Adler <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier:    GPL-2.0
+ */
+
+#include "uservars.h"
+
+#include "bg_envtools.h"
+#include "bg_printenv.h"
+
+static char tool_doc[] =
+       "bg_printenv - Environment tool for the EFI Boot Guard";
+
+static struct argp_option options_printenv[] = {
+       BG_CLI_OPTIONS_COMMON,
+       OPT("current", 'c', 0, 0,
+           "Only print values from the current environment"),
+       OPT("output", 'o', "LIST", 0,
+           "Comma-separated list of fields which are printed. "
+           "Available fields: in_progress, revision, kernel, kernelargs, "
+           "watchdog_timeout, ustate, user. "
+           "If omitted, all available fields are printed."),
+       OPT("raw", 'r', 0, 0, "Raw output mode, e.g. for shell scripting"),
+       {},
+};
+
+/* Arguments used by bg_printenv. */
+struct arguments_printenv {
+       struct arguments_common common;
+       bool current;
+       /* a bitset to decide which fields are printed */
+       struct fields output_fields;
+       bool raw;
+};
+
+const struct fields ALL_FIELDS = {1, 1, 1, 1, 1, 1, 1};
+
+static error_t parse_output_fields(char *fields, struct fields *output_fields)
+{
+       char *token;
+       memset(output_fields, 0, sizeof(struct fields));
+       while ((token = strsep(&fields, ","))) {
+               if (*token == '\0') continue;
+               if (strcmp(token, "in_progress") == 0) {
+                       output_fields->in_progress = true;
+               } else if (strcmp(token, "revision") == 0) {
+                       output_fields->revision = true;
+               } else if (strcmp(token, "kernel") == 0) {
+                       output_fields->kernel = true;
+               } else if (strcmp(token, "kernelargs") == 0) {
+                       output_fields->kernelargs = true;
+               } else if (strcmp(token, "watchdog_timeout") == 0) {
+                       output_fields->wdog_timeout = true;
+               } else if (strcmp(token, "ustate") == 0) {
+                       output_fields->ustate = true;
+               } else if (strcmp(token, "user") == 0) {
+                       output_fields->user = true;
+               } else {
+                       fprintf(stderr, "Unknown output field: %s\n", token);
+                       return 1;
+               }
+       }
+       return 0;
+}
+
+static void dump_uservars(uint8_t *udata, bool raw)
+{
+       char *key, *value;
+       uint64_t type;
+       uint32_t rsize, dsize;
+       uint64_t val_unum;
+       int64_t val_snum;
+
+       while (*udata) {
+               bgenv_map_uservar(udata, &key, &type, (uint8_t **)&value,
+                                 &rsize, &dsize);
+               fprintf(stdout, "%s", key);
+               type &= USERVAR_STANDARD_TYPE_MASK;
+               if (type == USERVAR_TYPE_STRING_ASCII) {
+                       fprintf(stdout, raw ? "=%s\n" : " = %s\n", value);
+               } else if (type >= USERVAR_TYPE_UINT8 &&
+                          type <= USERVAR_TYPE_UINT64) {
+                       switch(type) {
+                       case USERVAR_TYPE_UINT8:
+                               val_unum = *((uint8_t *) value);
+                               break;
+                       case USERVAR_TYPE_UINT16:
+                               val_unum = *((uint16_t *) value);
+                               break;
+                       case USERVAR_TYPE_UINT32:
+                               val_unum = *((uint32_t *) value);
+                               break;
+                       case USERVAR_TYPE_UINT64:
+                               val_unum = *((uint64_t *) value);
+                               break;
+                       }
+                       fprintf(stdout, raw ? "=%llu\n" : " = %llu\n",
+                               (long long unsigned int)val_unum);
+               } else if (type >= USERVAR_TYPE_SINT8 &&
+                          type <= USERVAR_TYPE_SINT64) {
+                       switch(type) {
+                       case USERVAR_TYPE_SINT8:
+                               val_snum = *((int8_t *) value);
+                               break;
+                       case USERVAR_TYPE_SINT16:
+                               val_snum = *((int16_t *) value);
+                               break;
+                       case USERVAR_TYPE_SINT32:
+                               val_snum = *((int32_t *) value);
+                               break;
+                       case USERVAR_TYPE_SINT64:
+                               val_snum = *((int64_t *) value);
+                               break;
+                       }
+                       fprintf(stdout, raw ? "=%lld\n" : " = %lld\n",
+                               (long long signed int)val_snum);
+               } else {
+                       switch(type) {
+                       case USERVAR_TYPE_CHAR:
+                               fprintf(stdout, raw ? "=%c\n" : " = %c\n",
+                                       (char)*value);
+                               break;
+                       case USERVAR_TYPE_BOOL:
+                               fprintf(stdout, raw ? "=%s\n" : " = %s\n",
+                                       (bool)*value ? "true" : "false");
+                               break;
+                       default:
+                               fprintf(stdout, " ( Type is not printable )\n");
+                       }
+               }
+
+               udata = bgenv_next_uservar(udata);
+       }
+}
+
+void dump_env(BG_ENVDATA *env, struct fields output_fields, bool raw)
+{
+       char buffer[ENV_STRING_LENGTH];
+       if (!raw) {
+               fprintf(stdout, "Values:\n");
+       }
+       if (output_fields.in_progress) {
+               if (raw) {
+                       fprintf(stdout, "IN_PROGRESS=%d\n", env->in_progress);
+               } else {
+                       fprintf(stdout, "in_progress:      %s\n",
+                               env->in_progress ? "yes" : "no");
+               }
+       }
+       if (output_fields.revision) {
+               if (raw) {
+                       fprintf(stdout, "REVISION=%u\n", env->revision);
+               } else {
+                       fprintf(stdout, "revision:         %u\n",
+                               env->revision);
+               }
+       }
+       if (output_fields.kernel) {
+               char *kernelfile = str16to8(buffer, env->kernelfile);
+               if (raw) {
+                       fprintf(stdout, "KERNEL=%s\n", kernelfile);
+               } else {
+                       fprintf(stdout, "kernel:           %s\n", kernelfile);
+               }
+       }
+       if (output_fields.kernelargs) {
+               char *kernelargs = str16to8(buffer, env->kernelparams);
+               if (raw) {
+                       fprintf(stdout, "KERNELARGS=%s\n", kernelargs);
+               } else {
+                       fprintf(stdout, "kernelargs:       %s\n", kernelargs);
+               }
+       }
+       if (output_fields.wdog_timeout) {
+               if (raw) {
+                       fprintf(stdout, "WATCHDOG_TIMEOUT=%u\n",
+                               env->watchdog_timeout_sec);
+               } else {
+                       fprintf(stdout, "watchdog timeout: %u seconds\n",
+                               env->watchdog_timeout_sec);
+               }
+       }
+       if (output_fields.ustate) {
+               if (raw) {
+                       fprintf(stdout, "USTATE=%u\n", env->ustate);
+               } else {
+                       fprintf(stdout, "ustate:           %u (%s)\n",
+                               (uint8_t)env->ustate, ustate2str(env->ustate));
+               }
+       }
+       if (output_fields.user) {
+               if (!raw) {
+                       fprintf(stdout, "\n");
+                       fprintf(stdout, "user variables:\n");
+               }
+               dump_uservars(env->userdata, raw);
+       }
+       if (!raw) {
+               fprintf(stdout, "\n\n");
+       }
+}
+
+void dump_envs(struct fields output_fields, bool raw)
+{
+       for (int i = 0; i < ENV_NUM_CONFIG_PARTS; i++) {
+               if (!raw) {
+                       fprintf(stdout, "\n----------------------------\n");
+                       fprintf(stdout, " Config Partition #%d ", i);
+               }
+               BGENV *env = bgenv_open_by_index(i);
+               if (!env) {
+                       fprintf(stderr, "Error, could not read environment "
+                                       "for index %d\n",
+                               i);
+                       return;
+               }
+               dump_env(env->data, output_fields, raw);
+               bgenv_close(env);
+       }
+}
+
+static void dump_latest_env(struct fields output_fields, bool raw)
+{
+       BGENV *env = bgenv_open_latest();
+       if (!env) {
+               fprintf(stderr, "Failed to retrieve latest environment.\n");
+               return;
+       }
+       dump_env(env->data, output_fields, raw);
+       bgenv_close(env);
+}
+
+static void dump_env_by_index(uint32_t index, struct fields output_fields,
+                             bool raw)
+{
+       BGENV *env = bgenv_open_by_index(index);
+       if (!env) {
+               fprintf(stderr, "Failed to retrieve latest environment.\n");
+               return;
+       }
+       dump_env(env->data, output_fields, raw);
+       bgenv_close(env);
+}
+
+static int printenv_from_file(char *envfilepath, struct fields output_fields,
+                             bool raw)
+{
+       int success = 0;
+       BG_ENVDATA data;
+
+       success = get_env(envfilepath, &data);
+       if (success) {
+               dump_env(&data, output_fields, raw);
+               return 0;
+       } else {
+               fprintf(stderr, "Error reading environment file.\n");
+               return 1;
+       }
+}
+
+static error_t parse_printenv_opt(int key, char *arg, struct argp_state *state)
+{
+       struct arguments_printenv *arguments = state->input;
+       error_t e = 0;
+
+       switch (key) {
+       case 'c':
+               arguments->current = true;
+               break;
+       case 'o':
+               e = parse_output_fields(arg, &arguments->output_fields);
+               break;
+       case 'r':
+               arguments->raw = true;
+               break;
+       case ARGP_KEY_ARG:
+               /* too many arguments - program terminates with call to
+                * argp_usage with non-zero return code */
+               argp_usage(state);
+               break;
+       default:
+               return parse_common_opt(key, arg, false, &arguments->common);
+       }
+
+       return e;
+}
+
+/* This is the entrypoint for the command bg_printenv. */
+error_t bg_printenv(int argc, char **argv)
+{
+       struct argp argp_printenv = {
+               .options = options_printenv,
+               .parser = parse_printenv_opt,
+               .doc = tool_doc,
+       };
+
+       struct arguments_printenv arguments = {
+               .output_fields = ALL_FIELDS,
+       };
+
+       error_t e = argp_parse(&argp_printenv, argc, argv, 0, 0, &arguments);
+       if (e) {
+               return e;
+       }
+
+       const struct arguments_common *common = &arguments.common;
+
+       /* count the number of arguments which result in bg_printenv
+        * operating on a single partition; to avoid ambiguity, we only
+        * allow one such argument. */
+       int counter = 0;
+       if (common->envfilepath) ++counter;
+       if (common->part_specified) ++counter;
+       if (arguments.current) ++counter;
+       if (counter > 1) {
+               fprintf(stderr, "Error, only one of -c/-f/-p can be set.\n");
+               return 1;
+       }
+       if (arguments.raw && counter != 1) {
+               /* raw mode makes only sense if applied to a single
+                * partition */
+               fprintf(stderr, "Error, raw is set but "
+                               "current/filepath/which_part is not set. "
+                               "Must use -r and -c/-f/-p simultaneously.\n");
+               return 1;
+       }
+
+       if (common->envfilepath) {
+               e = printenv_from_file(common->envfilepath,
+                                      arguments.output_fields, arguments.raw);
+               free(common->envfilepath);
+               return e;
+       }
+
+       /* not in file mode */
+       if (!bgenv_init()) {
+               fprintf(stderr, "Error initializing FAT environment.\n");
+               return 1;
+       }
+
+       if (arguments.current) {
+               if (!arguments.raw) {
+                       fprintf(stdout, "Using latest config partition\n");
+               }
+               dump_latest_env(arguments.output_fields, arguments.raw);
+       } else if (common->part_specified) {
+               if (!arguments.raw) {
+                       fprintf(stdout, "Using config partition #%d\n",
+                               arguments.common.which_part);
+               }
+               dump_env_by_index(common->which_part, arguments.output_fields,
+                                 arguments.raw);
+       } else {
+               dump_envs(arguments.output_fields, arguments.raw);
+       }
+
+       bgenv_finalize();
+       return 0;
+}
diff --git a/tools/bg_printenv.h b/tools/bg_printenv.h
new file mode 100644
index 0000000..309ff99
--- /dev/null
+++ b/tools/bg_printenv.h
@@ -0,0 +1,38 @@
+/*
+ * EFI Boot Guard
+ *
+ * Copyright (c) Siemens AG, 2017-2021
+ *
+ * Authors:
+ *  Andreas Reichel <[email protected]>
+ *  Michael Adler <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier:    GPL-2.0
+ */
+
+#ifndef __bg_printenv_h_
+#define __bg_printenv_h_
+
+#include "env_api.h"
+
+struct fields {
+       unsigned int in_progress : 1;
+       unsigned int revision : 1;
+       unsigned int kernel : 1;
+       unsigned int kernelargs : 1;
+       unsigned int wdog_timeout : 1;
+       unsigned int ustate : 1;
+       unsigned int user : 1;
+};
+
+extern const struct fields ALL_FIELDS;
+
+void dump_envs(struct fields output_fields, bool raw);
+void dump_env(BG_ENVDATA *env, struct fields output_fields, bool raw);
+
+error_t bg_printenv(int argc, char **argv);
+
+#endif
diff --git a/tools/bg_setenv.c b/tools/bg_setenv.c
index 593f562..ab9673e 100644
--- a/tools/bg_setenv.c
+++ b/tools/bg_setenv.c
@@ -16,31 +16,14 @@
 #include <sys/queue.h>
 #include <sys/stat.h>
 
-#include "env_api.h"
 #include "ebgenv.h"
-#include "uservars.h"
-#include "version.h"
-#include "env_config_file.h"
 
-static char doc[] =
-       "bg_setenv/bg_printenv - Environment tool for the EFI Boot Guard";
+#include "bg_envtools.h"
+#include "bg_setenv.h"
+#include "bg_printenv.h"
 
-#define OPT(name, key, arg, flags, doc)                                        
\
-       {                                                                      \
-               name, key, arg, flags, doc                                     \
-       }
-
-#define BG_CLI_OPTIONS_COMMON                                                  
\
-       OPT("filepath", 'f', "ENVFILE", 0,                                     \
-           "Environment to use. Expects a file name, "                        \
-           "usually called BGENV.DAT.")                                       \
-       , OPT("part", 'p', "ENV_PART", 0,                                      \
-             "Set environment partition to update. If no partition is "       \
-             "specified, "                                                    \
-             "the one with the smallest revision value above zero is "        \
-             "updated.")                                                      \
-       , OPT("verbose", 'v', 0, 0, "Be verbose")                              \
-       , OPT("version", 'V', 0, 0, "Print version")
+static char tool_doc[] =
+       "bg_setenv - Environment tool for the EFI Boot Guard";
 
 static struct argp_option options_setenv[] = {
        BG_CLI_OPTIONS_COMMON,
@@ -61,29 +44,6 @@ static struct argp_option options_setenv[] = {
        {},
 };
 
-static struct argp_option options_printenv[] = {
-       BG_CLI_OPTIONS_COMMON,
-       OPT("current", 'c', 0, 0,
-           "Only print values from the current environment"),
-       OPT("output", 'o', "LIST", 0,
-           "Comma-separated list of fields which are printed. "
-           "Available fields: in_progress, revision, kernel, kernelargs, "
-           "watchdog_timeout, ustate, user. "
-           "If omitted, all available fields are printed."),
-       OPT("raw", 'r', 0, 0, "Raw output mode, e.g. for shell scripting"),
-       {},
-};
-
-/* Common arguments used by both bg_setenv and bg_printenv. */
-struct arguments_common {
-       char *envfilepath;
-       bool verbosity;
-       /* which partition to operate on; a negative value means no partition
-        * was specified. */
-       int which_part;
-       bool part_specified;
-};
-
 /* Arguments used by bg_setenv. */
 struct arguments_setenv {
        struct arguments_common common;
@@ -95,27 +55,6 @@ struct arguments_setenv {
        bool preserve_env;
 };
 
-struct fields {
-       unsigned int in_progress : 1;
-       unsigned int revision : 1;
-       unsigned int kernel : 1;
-       unsigned int kernelargs : 1;
-       unsigned int wdog_timeout : 1;
-       unsigned int ustate : 1;
-       unsigned int user : 1;
-};
-
-static const struct fields ALL_FIELDS = {1, 1, 1, 1, 1, 1, 1};
-
-/* Arguments used by bg_printenv. */
-struct arguments_printenv {
-       struct arguments_common common;
-       bool current;
-       /* a bitset to decide which fields are printed */
-       struct fields output_fields;
-       bool raw;
-};
-
 typedef enum { ENV_TASK_SET, ENV_TASK_DEL } BGENV_TASK;
 
 struct stailhead *headp;
@@ -216,31 +155,6 @@ static void journal_process_action(BGENV *env, struct 
env_action *action)
        }
 }
 
-static char *ustatemap[] = {"OK", "INSTALLED", "TESTING", "FAILED", "UNKNOWN"};
-
-static uint8_t str2ustate(char *str)
-{
-       uint8_t i;
-
-       if (!str) {
-               return USTATE_UNKNOWN;
-       }
-       for (i = USTATE_MIN; i < USTATE_MAX; i++) {
-               if (strncasecmp(str, ustatemap[i], strlen(ustatemap[i])) == 0) {
-                       return i;
-               }
-       }
-       return USTATE_UNKNOWN;
-}
-
-static char *ustate2str(uint8_t ustate)
-{
-       if (ustate > USTATE_MAX) {
-               ustate = USTATE_MAX;
-       }
-       return ustatemap[ustate];
-}
-
 static error_t set_uservars(char *arg)
 {
        char *key, *value;
@@ -261,94 +175,6 @@ static error_t set_uservars(char *arg)
                                  (uint8_t *)value, strlen(value) + 1);
 }
 
-static int parse_int(char *arg)
-{
-       char *tmp;
-       long i;
-
-       errno = 0;
-       i = strtol(arg, &tmp, 10);
-       if (errno == ERANGE ||             /* out of range */
-           (errno != 0 && i == 0) ||      /* no conversion was performed */
-           tmp == arg || *tmp != '\0' ||  /* invalid input */
-           i < INT_MIN || i > INT_MAX) {  /* not a valid int */
-               errno = EINVAL;
-               return -1;
-       }
-       return (int) i;
-}
-
-static error_t parse_common_opt(int key, char *arg, bool compat_mode,
-                               struct arguments_common *arguments)
-{
-       bool found = false;
-       int i;
-       switch (key) {
-       case 'f':
-               found = true;
-               free(arguments->envfilepath);
-               arguments->envfilepath = NULL;
-
-               if (compat_mode) {
-                       /* compat mode, permitting "bg_setenv -f <dir>" */
-                       struct stat sb;
-
-                       int res = stat(arg, &sb);
-                       if (res == 0 && S_ISDIR(sb.st_mode)) {
-                               fprintf(stderr,
-                                       "WARNING: Using -f to specify only the "
-                                       "ouptut directory is deprecated.\n");
-                               res = asprintf(&arguments->envfilepath, "%s/%s",
-                                              arg, FAT_ENV_FILENAME);
-                               if (res == -1) {
-                                       return ENOMEM;
-                               }
-                       }
-               }
-
-               if (!arguments->envfilepath) {
-                       arguments->envfilepath = strdup(arg);
-                       if (!arguments->envfilepath) {
-                               return ENOMEM;
-                       }
-               }
-               break;
-       case 'p':
-               found = true;
-               i = parse_int(arg);
-               if (errno) {
-                       fprintf(stderr, "Invalid number specified for -p.\n");
-                       return 1;
-               }
-               if (i >= 0 && i < ENV_NUM_CONFIG_PARTS) {
-                       arguments->which_part = i;
-                       arguments->part_specified = true;
-               } else {
-                       fprintf(stderr,
-                               "Selected partition out of range. Valid range: "
-                               "0..%d.\n",
-                               ENV_NUM_CONFIG_PARTS - 1);
-                       return 1;
-               }
-               break;
-       case 'v':
-               found = true;
-               /* Set verbosity in this program */
-               arguments->verbosity = true;
-               /* Set verbosity in the library */
-               bgenv_be_verbose(true);
-               break;
-       case 'V':
-               found = true;
-               fprintf(stdout, "EFI Boot Guard %s\n", EFIBOOTGUARD_VERSION);
-               exit(0);
-       }
-       if (!found) {
-               return ARGP_ERR_UNKNOWN;
-       }
-       return 0;
-}
-
 static error_t parse_setenv_opt(int key, char *arg, struct argp_state *state)
 {
        struct arguments_setenv *arguments = state->input;
@@ -390,12 +216,12 @@ static error_t parse_setenv_opt(int key, char *arg, 
struct argp_state *state)
                        }
                }
                if (i < 0 || i > 3) {
-                       fprintf(
-                           stderr,
-                           "Invalid ustate value specified. Possible values: "
-                           "0 (%s), 1 (%s), 2 (%s), 3 (%s)\n",
-                           ustatemap[0], ustatemap[1], ustatemap[2],
-                           ustatemap[3]);
+                       fprintf(stderr,
+                               "Invalid ustate value specified. Possible "
+                               "values: "
+                               "0 (%s), 1 (%s), 2 (%s), 3 (%s)\n",
+                               ustate2str(0), ustate2str(1), ustate2str(2),
+                               ustate2str(3));
                        return 1;
                } else {
                        res = asprintf(&tmp, "%u", i);
@@ -486,198 +312,6 @@ static error_t parse_setenv_opt(int key, char *arg, 
struct argp_state *state)
        return e;
 }
 
-static error_t parse_output_fields(char *fields, struct fields *output_fields)
-{
-       char *token;
-       memset(output_fields, 0, sizeof(struct fields));
-       while ((token = strsep(&fields, ","))) {
-               if (*token == '\0') continue;
-               if (strcmp(token, "in_progress") == 0) {
-                       output_fields->in_progress = true;
-               } else if (strcmp(token, "revision") == 0) {
-                       output_fields->revision = true;
-               } else if (strcmp(token, "kernel") == 0) {
-                       output_fields->kernel = true;
-               } else if (strcmp(token, "kernelargs") == 0) {
-                       output_fields->kernelargs = true;
-               } else if (strcmp(token, "watchdog_timeout") == 0) {
-                       output_fields->wdog_timeout = true;
-               } else if (strcmp(token, "ustate") == 0) {
-                       output_fields->ustate = true;
-               } else if (strcmp(token, "user") == 0) {
-                       output_fields->user = true;
-               } else {
-                       fprintf(stderr, "Unknown output field: %s\n", token);
-                       return 1;
-               }
-       }
-       return 0;
-}
-
-static error_t parse_printenv_opt(int key, char *arg, struct argp_state *state)
-{
-       struct arguments_printenv *arguments = state->input;
-       error_t e = 0;
-
-       switch (key) {
-       case 'c':
-               arguments->current = true;
-               break;
-       case 'o':
-               e = parse_output_fields(arg, &arguments->output_fields);
-               break;
-       case 'r':
-               arguments->raw = true;
-               break;
-       case ARGP_KEY_ARG:
-               /* too many arguments - program terminates with call to
-                * argp_usage with non-zero return code */
-               argp_usage(state);
-               break;
-       default:
-               return parse_common_opt(key, arg, false, &arguments->common);
-       }
-
-       return e;
-}
-
-static void dump_uservars(uint8_t *udata, bool raw)
-{
-       char *key, *value;
-       uint64_t type;
-       uint32_t rsize, dsize;
-       uint64_t val_unum;
-       int64_t val_snum;
-
-       while (*udata) {
-               bgenv_map_uservar(udata, &key, &type, (uint8_t **)&value,
-                                 &rsize, &dsize);
-               fprintf(stdout, "%s", key);
-               type &= USERVAR_STANDARD_TYPE_MASK;
-               if (type == USERVAR_TYPE_STRING_ASCII) {
-                       fprintf(stdout, raw ? "=%s\n" : " = %s\n", value);
-               } else if (type >= USERVAR_TYPE_UINT8 &&
-                          type <= USERVAR_TYPE_UINT64) {
-                       switch(type) {
-                       case USERVAR_TYPE_UINT8:
-                               val_unum = *((uint8_t *) value);
-                               break;
-                       case USERVAR_TYPE_UINT16:
-                               val_unum = *((uint16_t *) value);
-                               break;
-                       case USERVAR_TYPE_UINT32:
-                               val_unum = *((uint32_t *) value);
-                               break;
-                       case USERVAR_TYPE_UINT64:
-                               val_unum = *((uint64_t *) value);
-                               break;
-                       }
-                       fprintf(stdout, raw ? "=%llu\n" : " = %llu\n",
-                               (long long unsigned int)val_unum);
-               } else if (type >= USERVAR_TYPE_SINT8 &&
-                          type <= USERVAR_TYPE_SINT64) {
-                       switch(type) {
-                       case USERVAR_TYPE_SINT8:
-                               val_snum = *((int8_t *) value);
-                               break;
-                       case USERVAR_TYPE_SINT16:
-                               val_snum = *((int16_t *) value);
-                               break;
-                       case USERVAR_TYPE_SINT32:
-                               val_snum = *((int32_t *) value);
-                               break;
-                       case USERVAR_TYPE_SINT64:
-                               val_snum = *((int64_t *) value);
-                               break;
-                       }
-                       fprintf(stdout, raw ? "=%lld\n" : " = %lld\n",
-                               (long long signed int)val_snum);
-               } else {
-                       switch(type) {
-                       case USERVAR_TYPE_CHAR:
-                               fprintf(stdout, raw ? "=%c\n" : " = %c\n",
-                                       (char)*value);
-                               break;
-                       case USERVAR_TYPE_BOOL:
-                               fprintf(stdout, raw ? "=%s\n" : " = %s\n",
-                                       (bool)*value ? "true" : "false");
-                               break;
-                       default:
-                               fprintf(stdout, " ( Type is not printable )\n");
-                       }
-               }
-
-               udata = bgenv_next_uservar(udata);
-       }
-}
-
-static void dump_env(BG_ENVDATA *env, struct fields output_fields, bool raw)
-{
-       char buffer[ENV_STRING_LENGTH];
-       if (!raw) {
-               fprintf(stdout, "Values:\n");
-       }
-       if (output_fields.in_progress) {
-               if (raw) {
-                       fprintf(stdout, "IN_PROGRESS=%d\n", env->in_progress);
-               } else {
-                       fprintf(stdout, "in_progress:      %s\n",
-                               env->in_progress ? "yes" : "no");
-               }
-       }
-       if (output_fields.revision) {
-               if (raw) {
-                       fprintf(stdout, "REVISION=%u\n", env->revision);
-               } else {
-                       fprintf(stdout, "revision:         %u\n",
-                               env->revision);
-               }
-       }
-       if (output_fields.kernel) {
-               char *kernelfile = str16to8(buffer, env->kernelfile);
-               if (raw) {
-                       fprintf(stdout, "KERNEL=%s\n", kernelfile);
-               } else {
-                       fprintf(stdout, "kernel:           %s\n", kernelfile);
-               }
-       }
-       if (output_fields.kernelargs) {
-               char *kernelargs = str16to8(buffer, env->kernelparams);
-               if (raw) {
-                       fprintf(stdout, "KERNELARGS=%s\n", kernelargs);
-               } else {
-                       fprintf(stdout, "kernelargs:       %s\n", kernelargs);
-               }
-       }
-       if (output_fields.wdog_timeout) {
-               if (raw) {
-                       fprintf(stdout, "WATCHDOG_TIMEOUT=%u\n",
-                               env->watchdog_timeout_sec);
-               } else {
-                       fprintf(stdout, "watchdog timeout: %u seconds\n",
-                               env->watchdog_timeout_sec);
-               }
-       }
-       if (output_fields.ustate) {
-               if (raw) {
-                       fprintf(stdout, "USTATE=%u\n", env->ustate);
-               } else {
-                       fprintf(stdout, "ustate:           %u (%s)\n",
-                               (uint8_t)env->ustate, ustate2str(env->ustate));
-               }
-       }
-       if (output_fields.user) {
-               if (!raw) {
-                       fprintf(stdout, "\n");
-                       fprintf(stdout, "user variables:\n");
-               }
-               dump_uservars(env->userdata, raw);
-       }
-       if (!raw) {
-               fprintf(stdout, "\n\n");
-       }
-}
-
 static void update_environment(BGENV *env, bool verbosity)
 {
        if (verbosity) {
@@ -697,89 +331,6 @@ static void update_environment(BGENV *env, bool verbosity)
 
 }
 
-static void dump_envs(struct fields output_fields, bool raw)
-{
-       for (int i = 0; i < ENV_NUM_CONFIG_PARTS; i++) {
-               if (!raw) {
-                       fprintf(stdout, "\n----------------------------\n");
-                       fprintf(stdout, " Config Partition #%d ", i);
-               }
-               BGENV *env = bgenv_open_by_index(i);
-               if (!env) {
-                       fprintf(stderr, "Error, could not read environment "
-                                       "for index %d\n",
-                               i);
-                       return;
-               }
-               dump_env(env->data, output_fields, raw);
-               bgenv_close(env);
-       }
-}
-
-static void dump_latest_env(struct fields output_fields, bool raw)
-{
-       BGENV *env = bgenv_open_latest();
-       if (!env) {
-               fprintf(stderr, "Failed to retrieve latest environment.\n");
-               return;
-       }
-       dump_env(env->data, output_fields, raw);
-       bgenv_close(env);
-}
-
-static void dump_env_by_index(uint32_t index, struct fields output_fields,
-                             bool raw)
-{
-       BGENV *env = bgenv_open_by_index(index);
-       if (!env) {
-               fprintf(stderr, "Failed to retrieve latest environment.\n");
-               return;
-       }
-       dump_env(env->data, output_fields, raw);
-       bgenv_close(env);
-}
-
-static bool get_env(char *configfilepath, BG_ENVDATA *data)
-{
-       FILE *config;
-       bool result = true;
-
-       if (!(config = open_config_file(configfilepath, "rb"))) {
-               return false;
-       }
-
-       if (!(fread(data, sizeof(BG_ENVDATA), 1, config) == 1)) {
-               VERBOSE(stderr, "Error reading environment data from %s\n",
-                       configfilepath);
-               if (feof(config)) {
-                       VERBOSE(stderr, "End of file encountered.\n");
-               }
-               result = false;
-       }
-
-       if (close_config_file(config)) {
-               VERBOSE(stderr,
-                       "Error closing environment file after reading.\n");
-       };
-       return result;
-}
-
-static int printenv_from_file(char *envfilepath, struct fields output_fields,
-                             bool raw)
-{
-       int success = 0;
-       BG_ENVDATA data;
-
-       success = get_env(envfilepath, &data);
-       if (success) {
-               dump_env(&data, output_fields, raw);
-               return 0;
-       } else {
-               fprintf(stderr, "Error reading environment file.\n");
-               return 1;
-       }
-}
-
 static int dumpenv_to_file(char *envfilepath, bool verbosity, bool 
preserve_env)
 {
        /* execute journal and write to file */
@@ -822,81 +373,8 @@ static int dumpenv_to_file(char *envfilepath, bool 
verbosity, bool preserve_env)
        return result;
 }
 
-/* This is the entrypoint for the command bg_printenv. */
-static error_t bg_printenv(int argc, char **argv)
-{
-       struct argp argp_printenv = {
-               .options = options_printenv,
-               .parser = parse_printenv_opt,
-               .doc = doc,
-       };
-
-       struct arguments_printenv arguments = {
-               .output_fields = ALL_FIELDS,
-       };
-
-       error_t e = argp_parse(&argp_printenv, argc, argv, 0, 0, &arguments);
-       if (e) {
-               return e;
-       }
-
-       const struct arguments_common *common = &arguments.common;
-
-       /* count the number of arguments which result in bg_printenv
-        * operating on a single partition; to avoid ambiguity, we only
-        * allow one such argument. */
-       int counter = 0;
-       if (common->envfilepath) ++counter;
-       if (common->part_specified) ++counter;
-       if (arguments.current) ++counter;
-       if (counter > 1) {
-               fprintf(stderr, "Error, only one of -c/-f/-p can be set.\n");
-               return 1;
-       }
-       if (arguments.raw && counter != 1) {
-               /* raw mode makes only sense if applied to a single
-                * partition */
-               fprintf(stderr, "Error, raw is set but "
-                               "current/filepath/which_part is not set. "
-                               "Must use -r and -c/-f/-p simultaneously.\n");
-               return 1;
-       }
-
-       if (common->envfilepath) {
-               e = printenv_from_file(common->envfilepath,
-                                      arguments.output_fields, arguments.raw);
-               free(common->envfilepath);
-               return e;
-       }
-
-       /* not in file mode */
-       if (!bgenv_init()) {
-               fprintf(stderr, "Error initializing FAT environment.\n");
-               return 1;
-       }
-
-       if (arguments.current) {
-               if (!arguments.raw) {
-                       fprintf(stdout, "Using latest config partition\n");
-               }
-               dump_latest_env(arguments.output_fields, arguments.raw);
-       } else if (common->part_specified) {
-               if (!arguments.raw) {
-                       fprintf(stdout, "Using config partition #%d\n",
-                               arguments.common.which_part);
-               }
-               dump_env_by_index(common->which_part, arguments.output_fields,
-                                 arguments.raw);
-       } else {
-               dump_envs(arguments.output_fields, arguments.raw);
-       }
-
-       bgenv_finalize();
-       return 0;
-}
-
 /* This is the entrypoint for the command bg_setenv. */
-static error_t bg_setenv(int argc, char **argv)
+error_t bg_setenv(int argc, char **argv)
 {
        if (argc < 2) {
                printf("No task to perform. Please specify at least one"
@@ -908,7 +386,7 @@ static error_t bg_setenv(int argc, char **argv)
        struct argp argp_setenv = {
                .options = options_setenv,
                .parser = parse_setenv_opt,
-               .doc = doc,
+               .doc = tool_doc,
        };
 
        struct arguments_setenv arguments;
@@ -1027,12 +505,3 @@ cleanup:
        bgenv_finalize();
        return result;
 }
-
-int main(int argc, char **argv)
-{
-       if (strstr(argv[0], "bg_setenv")) {
-               return bg_setenv(argc, argv);
-       } else {
-               return bg_printenv(argc, argv);
-       }
-}
diff --git a/tools/bg_setenv.h b/tools/bg_setenv.h
new file mode 100644
index 0000000..82a8023
--- /dev/null
+++ b/tools/bg_setenv.h
@@ -0,0 +1,23 @@
+/*
+ * EFI Boot Guard
+ *
+ * Copyright (c) Siemens AG, 2017-2021
+ *
+ * Authors:
+ *  Andreas Reichel <[email protected]>
+ *  Michael Adler <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier:    GPL-2.0
+ */
+
+#ifndef __bg_setenv_h_
+#define __bg_setenv_h_
+
+#include <errno.h>
+
+error_t bg_setenv(int argc, char **argv);
+
+#endif
diff --git a/tools/main.c b/tools/main.c
new file mode 100644
index 0000000..42e7755
--- /dev/null
+++ b/tools/main.c
@@ -0,0 +1,26 @@
+/*
+ * EFI Boot Guard
+ *
+ * Copyright (c) Siemens AG, 2017-2021
+ *
+ * Authors:
+ *  Andreas Reichel <[email protected]>
+ *  Michael Adler <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.  See
+ * the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier:    GPL-2.0
+ */
+
+#include "bg_printenv.h"
+#include "bg_setenv.h"
+
+int main(int argc, char **argv)
+{
+       if (strstr(argv[0], "bg_setenv")) {
+               return bg_setenv(argc, argv);
+       } else {
+               return bg_printenv(argc, argv);
+       }
+}
-- 
2.33.1

-- 
You received this message because you are subscribed to the Google Groups "EFI 
Boot Guard" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/efibootguard-dev/20211108095104.611379-1-michael.adler%40siemens.com.

Reply via email to