Bug 11040 - getopt mistakenly allows '-;' as short option
Summary: getopt mistakenly allows '-;' as short option
Status: RESOLVED FIXED
Alias: None
Product: glibc
Classification: Unclassified
Component: libc (show other bugs)
Version: 2.11
: P2 normal
Target Milestone: ---
Assignee: Ulrich Drepper
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2009-12-01 16:50 UTC by Eric Blake
Modified: 2014-06-30 20:36 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Last reconfirmed:
fweimer: security-


Attachments
patch (420 bytes, patch)
2009-12-01 16:54 UTC, Eric Blake
Details | Diff

Note You need to log in before you can comment on or make changes to this bug.
Description Eric Blake 2009-12-01 16:50:53 UTC
getopt_long is documented as accepting an optstring of "W;" as an extension that
parses '-W longopt=value' the same as '--longopt=value'.  However, using this
extension also makes apps mistakenly accept '-;' as a valid short option.

In practice, encountering '-;' as a short option will be rare (since it requires
shell quoting).  Furthermore, if ';' appears in optstring outside of the
documented "W;" extension, there is no reason to forbid it from being a valid
short option as an extension permitted by POSIX.  However, if the only ';' in
optstring immediately follows 'W', it makes more sense to reject ';', the same
way that ':' is rejected.  And coding-wise, it is easier to forbid all use of
';', rather than making the code more complicated to determine whether ';' in
optstring immediately follows 'W'.

$ cat foo.c
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>

static const struct option opts[] =
  {
    { "alpha",    no_argument,       NULL, 'a' },
    { "beta",     required_argument, NULL, 'b' },
    { NULL,       0,                 NULL, 0 }
  };

int
main (int argc, char **argv)
{
  int c = getopt_long (argc, argv, "ab:W;", opts, NULL);
  if (c == -1)
    puts ("got -1");
  else
    printf ("got %c\n", c);
  c = getopt_long (argc, argv, "ab:W;", opts, NULL);
  if (c == -1)
    puts ("got -1");
  else
    printf ("got %c\n", c);
  return 0;
}
$ ./foo '-a;'
got a
got ;
$ ./foo2 '-a:'
got a
./foo2: invalid option -- :
got ?

Workaround: code using the "W;" extension must be prepared to deal with a return
value of ';' and manually handle it as an invalid option.

Expected results: '-a;' should have errored out like '-a:'.
Comment 1 Eric Blake 2009-12-01 16:54:16 UTC
Created attachment 4436 [details]
patch

2009-12-01  Eric Blake	<ebb9@byu.net>

	* posix/getopt.c (_getopt_internal_r): Reject '-;' as short
	option, since it conflicts with "W;" optstring extension.
Comment 2 Ulrich Drepper 2010-04-08 00:31:00 UTC
Fixed in git.