From fba61279157763497d658b0cc62bd25d680fa9b4 Mon Sep 17 00:00:00 2001 From: Niclas Zeising Date: Sat, 9 Dec 2017 15:59:10 +0000 Subject: [PATCH] Improve options and error handling. Improve options handling and error out if multiple mutually exclusive options are passed to acpiconf. Switch from using atoi() to strtol() for argument parsing, and add error checking and handling, instead of blindly trusting that the integer conversion is OK. Cange err() to errx() in once case, the errno value was garbage there. Reviewed by: emaste Approved by: emaste Differential Revision: D13430 --- usr.sbin/acpi/acpiconf/acpiconf.c | 45 ++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/usr.sbin/acpi/acpiconf/acpiconf.c b/usr.sbin/acpi/acpiconf/acpiconf.c index da8272637472..4af4c73d4e15 100644 --- a/usr.sbin/acpi/acpiconf/acpiconf.c +++ b/usr.sbin/acpi/acpiconf/acpiconf.c @@ -92,7 +92,7 @@ acpi_battinfo(int num) uint32_t volt; if (num < 0 || num > 64) - err(EX_USAGE, "invalid battery %d", num); + errx(EX_USAGE, "invalid battery %d", num); /* Print battery design information. */ battio.unit = num; @@ -205,8 +205,9 @@ usage(const char* prog) int main(int argc, char *argv[]) { - char *prog; - int c, sleep_type; + char *prog, *end; + int c, sleep_type, battery, ack; + int iflag = 0, kflag = 0, sflag = 0; prog = argv[0]; if (argc < 2) @@ -218,16 +219,24 @@ main(int argc, char *argv[]) while ((c = getopt(argc, argv, "hi:k:s:")) != -1) { switch (c) { case 'i': - acpi_battinfo(atoi(optarg)); + iflag = 1; + battery = strtol(optarg, &end, 10); + if ((size_t)(end - optarg) != strlen(optarg)) + errx(EX_USAGE, "invalid battery"); break; case 'k': - acpi_sleep_ack(atoi(optarg)); + kflag = 1; + ack = strtol(optarg, &end, 10); + if ((size_t)(end - optarg) != strlen(optarg)) + errx(EX_USAGE, "invalid ack argument"); break; case 's': + sflag = 1; if (optarg[0] == 'S') - sleep_type = optarg[1] - '0'; - else - sleep_type = optarg[0] - '0'; + optarg++; + sleep_type = strtol(optarg, &end, 10); + if ((size_t)(end - optarg) != strlen(optarg)) + errx(EX_USAGE, "invalid sleep type"); if (sleep_type < 1 || sleep_type > 4) errx(EX_USAGE, "invalid sleep type (%d)", sleep_type); @@ -241,7 +250,25 @@ main(int argc, char *argv[]) argc -= optind; argv += optind; - if (sleep_type != -1) + if (iflag != 0 && kflag != 0 && sflag != 0) + errx(EX_USAGE, "-i, -k and -s are mutually exclusive"); + + if (iflag != 0) { + if (kflag != 0) + errx(EX_USAGE, "-i and -k are mutually exclusive"); + if (sflag != 0) + errx(EX_USAGE, "-i and -s are mutually exclusive"); + acpi_battinfo(battery); + } + + if (kflag != 0) { + if (sflag != 0) + errx(EX_USAGE, "-k and -s are mutually exclusive"); + acpi_sleep_ack(ack); + } + + + if (sflag != 0) acpi_sleep(sleep_type); close(acpifd);