util: Don't stop on unrelated values when looking for --fd in close_open_files()

Seen with krun: we get a file descriptor via --fd, but we close it and
happily use the same number for TCP files.

The issue is that if we also get other options before --fd, with
arguments, getopt_long() stops parsing them because it sees them as
non-option values.

Use the - modifier at the beginning of optstring (before :, which is
needed to avoid printing errors) instead of +, which means we'll
continue parsing after finding unrelated option values, but
getopt_long() won't reorder them anyway: they'll be passed with option
value '1', which we can ignore.

By the way, we also need to add : after F in the optstring, so that
we're able to parse the option when given as short name as well.

Now that we change the parsing mode between close_open_files() and
conf(), we need to reset optind to 0, not to 1, whenever we call
getopt_long() again in conf(), so that the internal initialisation
of getopt_long() evaluating GNU extensions is re-triggered.

Link: https://github.com/slp/krun/issues/17#issuecomment-2294943828
Fixes: baccfb95ce ("conf: Stop parsing options at first non-option argument")
Fixes: 09603cab28 ("passt, util: Close any open file that the parent might have leaked")
Signed-off-by: Stefano Brivio <sbrivio@redhat.com>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
This commit is contained in:
Stefano Brivio 2024-08-20 22:39:44 +02:00
parent 05453ea590
commit f00ebda369
2 changed files with 4 additions and 4 deletions

6
conf.c
View file

@ -1312,7 +1312,7 @@ void conf(struct ctx *c, int argc, char **argv)
c->udp.fwd_in.mode = c->udp.fwd_out.mode = FWD_UNSET; c->udp.fwd_in.mode = c->udp.fwd_out.mode = FWD_UNSET;
memcpy(c->our_tap_mac, MAC_OUR_LAA, ETH_ALEN); memcpy(c->our_tap_mac, MAC_OUR_LAA, ETH_ALEN);
optind = 1; optind = 0;
do { do {
name = getopt_long(argc, argv, optstring, options, NULL); name = getopt_long(argc, argv, optstring, options, NULL);
@ -1712,7 +1712,7 @@ void conf(struct ctx *c, int argc, char **argv)
* settings) * settings)
*/ */
udp_portmap_clear(); udp_portmap_clear();
optind = 1; optind = 0;
do { do {
name = getopt_long(argc, argv, optstring, options, NULL); name = getopt_long(argc, argv, optstring, options, NULL);
@ -1782,7 +1782,7 @@ void conf(struct ctx *c, int argc, char **argv)
nl_sock_init(c, true); nl_sock_init(c, true);
/* ...and outbound port options now that namespaces are set up. */ /* ...and outbound port options now that namespaces are set up. */
optind = 1; optind = 0;
do { do {
name = getopt_long(argc, argv, optstring, options, NULL); name = getopt_long(argc, argv, optstring, options, NULL);

2
util.c
View file

@ -728,7 +728,7 @@ void close_open_files(int argc, char **argv)
int name, rc; int name, rc;
do { do {
name = getopt_long(argc, argv, "+:F", optfd, NULL); name = getopt_long(argc, argv, "-:F:", optfd, NULL);
if (name == 'F') { if (name == 'F') {
errno = 0; errno = 0;