From b32f59619c32ed6cd136194d92c649b74926c6f2 Mon Sep 17 00:00:00 2001
From: Lee Duncan <lduncan@suse.com>
Date: Wed, 25 Mar 2020 18:00:50 -0700
Subject: [PATCH] Fix issue where "iscsi-iname -p" core dumps.

While I was at it, I made the usage message a function
and made it print to stderr insted of stdout.
---
 utils/Makefile      |  2 +-
 utils/iscsi-iname.c | 17 +++++++++++++----
 2 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/utils/Makefile b/utils/Makefile
index f65f1e79..aed3bb0a 100644
--- a/utils/Makefile
+++ b/utils/Makefile
@@ -1,7 +1,7 @@
 # This Makefile will work only with GNU make.
 
 CFLAGS ?= -O2 -fno-inline -g
-CFLAGS += -Wall -Wstrict-prototypes
+CFLAGS += -Wall -Wextra -Wstrict-prototypes
 PROGRAMS = iscsi-iname
 
 all: $(PROGRAMS)
diff --git a/utils/iscsi-iname.c b/utils/iscsi-iname.c
index da850dca..0f587e1e 100644
--- a/utils/iscsi-iname.c
+++ b/utils/iscsi-iname.c
@@ -40,6 +40,13 @@
  * a seperator and 12 characters (6 random bytes in hex representation) */
 #define PREFIX_MAX_LEN 210
 
+static void usage(void)
+{
+	fprintf(stderr, "Usage: iscsi-iname [-h | --help | -p <prefix>]\n");
+	fprintf(stderr, "where <prefix> has max length of %d\n",
+		PREFIX_MAX_LEN);
+}
+
 int
 main(int argc, char *argv[])
 {
@@ -68,15 +75,17 @@ main(int argc, char *argv[])
 			       "on every invocation.\n");
 			exit(0);
 		} else if ( strcmp(prefix, "-p") == 0 ) {
+			if (argc != 3) {
+				usage();
+				exit(1);
+			}
 			prefix = argv[2];
 			if (strnlen(prefix, PREFIX_MAX_LEN + 1) > PREFIX_MAX_LEN) {
-				printf("Error: Prefix cannot exceed %d "
-				       "characters.\n", PREFIX_MAX_LEN);
+				usage();
 				exit(1);
 			}
 		} else {
-			printf("\nUsage: iscsi-iname [-h | --help | "
-			       "-p <prefix>]\n");
+			usage();
 			exit(0);
 		}
 	} else {
