Skip to content

Commit 87df0eb

Browse files
committed
Fix option parsing for unknown flags
mcd segfaulted on any unrecognised option (e.g. -V) because usage() called strlen(pid_file) before compose_paths() had initialised it. Fix by moving compose_paths() into usage() itself. mctl silently showed help and exited 0 for unknown options because '?' is also in the option string as a -? help alias, masking the error. Split case '?' to check optopt and add a default branch so unrecognised options exit with code 1. Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
1 parent 37a54d8 commit 87df0eb

2 files changed

Lines changed: 11 additions & 4 deletions

File tree

src/main.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,14 @@ static int compose_paths(void)
4949

5050
static int usage(int code)
5151
{
52-
char pidbuf[strlen(pid_file) + 10];
53-
char ipcbuf[strlen(_PATH_MCD_SOCK) + 42];
52+
char pidbuf[PATH_MAX];
53+
char ipcbuf[PATH_MAX];
5454
char *nm = PACKAGE_NAME;
5555
char *sockfn = ipcbuf;
5656
char *pidfn = pidbuf;
5757

58+
compose_paths();
59+
5860
if (pid_file[0] == '/')
5961
pidfn = pid_file;
6062
else
@@ -122,7 +124,6 @@ int main(int argc, char *argv[])
122124
break;
123125

124126
case 'h':
125-
compose_paths();
126127
return usage(0);
127128

128129
case 'i': /* --ident=NAME */

src/mctl.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -641,9 +641,12 @@ int main(int argc, char *argv[])
641641
break;
642642

643643
case 'h':
644-
case '?':
645644
return usage(0);
646645

646+
case '?':
647+
/* optopt is set for unrecognized options, clear for -? */
648+
return usage(optopt ? 1 : 0);
649+
647650
case 'i': /* --ident=NAME */
648651
ident = optarg;
649652
break;
@@ -666,6 +669,9 @@ int main(int argc, char *argv[])
666669

667670
case 'v':
668671
return version();
672+
673+
default:
674+
return usage(1);
669675
}
670676
}
671677

0 commit comments

Comments
 (0)