Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/lib/util/getopt_long.c
1532 views
1
/* $OpenBSD: getopt_long.c,v 1.26 2013/06/08 22:47:56 millert Exp $ */
2
/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
3
/* $FreeBSD: head/lib/libc/stdlib/getopt_long.c 236936 2012-06-11 22:25:20Z delphij $ */
4
5
/*
6
* SPDX-License-Identifier: ISC
7
*
8
* Copyright (c) 2002 Todd C. Miller <[email protected]>
9
*
10
* Permission to use, copy, modify, and distribute this software for any
11
* purpose with or without fee is hereby granted, provided that the above
12
* copyright notice and this permission notice appear in all copies.
13
*
14
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21
*
22
* Sponsored in part by the Defense Advanced Research Projects
23
* Agency (DARPA) and Air Force Research Laboratory, Air Force
24
* Materiel Command, USAF, under agreement number F39502-99-1-0512.
25
*/
26
27
/*-
28
* Copyright (c) 2000 The NetBSD Foundation, Inc.
29
* All rights reserved.
30
*
31
* This code is derived from software contributed to The NetBSD Foundation
32
* by Dieter Baron and Thomas Klausner.
33
*
34
* Redistribution and use in source and binary forms, with or without
35
* modification, are permitted provided that the following conditions
36
* are met:
37
* 1. Redistributions of source code must retain the above copyright
38
* notice, this list of conditions and the following disclaimer.
39
* 2. Redistributions in binary form must reproduce the above copyright
40
* notice, this list of conditions and the following disclaimer in the
41
* documentation and/or other materials provided with the distribution.
42
*
43
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
44
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
45
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
46
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
47
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
48
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
49
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
50
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
51
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
53
* POSSIBILITY OF SUCH DAMAGE.
54
*/
55
56
#include <config.h>
57
58
#include <stdlib.h>
59
#include <string.h>
60
61
#define SUDO_ERROR_WRAP 0
62
63
#include <sudo_compat.h>
64
#include <sudo_fatal.h>
65
#include <compat/getopt.h>
66
67
#define GNU_COMPATIBLE /* Be more compatible with GNU getopt. */
68
69
#ifdef REPLACE_GETOPT
70
int opterr = 1; /* if error message should be printed */
71
int optind = 1; /* index into parent argv vector */
72
int optopt = '?'; /* character checked for validity */
73
char *optarg; /* argument associated with option */
74
#else
75
extern int opterr; /* if error message should be printed */
76
extern int optind; /* index into parent argv vector */
77
extern int optopt; /* character checked for validity */
78
extern char *optarg; /* argument associated with option */
79
#endif
80
#if !defined(REPLACE_GETOPT) && !defined(HAVE_OPTRESET)
81
int optreset; /* reset getopt */
82
#endif
83
84
#define PRINT_ERROR ((opterr) && (*options != ':'))
85
86
#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
87
#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
88
#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
89
90
/* return values */
91
#define BADCH (int)'?'
92
#define BADARG ((*options == ':') ? (int)':' : (int)'?')
93
#define INORDER (int)1
94
95
#define EMSG (char *)""
96
97
#ifdef GNU_COMPATIBLE
98
#define NO_PREFIX (-1)
99
#define D_PREFIX 0
100
#define DD_PREFIX 1
101
#define W_PREFIX 2
102
#endif
103
104
static int getopt_internal(int, char * const *, const char *,
105
const struct option *, int *, int);
106
static int parse_long_options(char * const *, const char *,
107
const struct option *, int *, int, int);
108
static int gcd(int, int);
109
static void permute_args(int, int, int, char * const *);
110
111
static char *place = EMSG; /* option letter processing */
112
113
/* XXX: set optreset to 1 rather than these two */
114
static int nonopt_start = -1; /* first non option argument (for permute) */
115
static int nonopt_end = -1; /* first option after non options (for permute) */
116
117
/* Error messages */
118
static const char recargchar[] = "option requires an argument -- %c";
119
static const char illoptchar[] = "illegal option -- %c"; /* From P1003.2 */
120
#ifdef GNU_COMPATIBLE
121
static int dash_prefix = NO_PREFIX;
122
static const char gnuoptchar[] = "invalid option -- %c";
123
124
static const char recargstring[] = "option `%s%s' requires an argument";
125
static const char ambig[] = "option `%s%.*s' is ambiguous";
126
static const char noarg[] = "option `%s%.*s' doesn't allow an argument";
127
static const char illoptstring[] = "unrecognized option `%s%s'";
128
#else
129
static const char recargstring[] = "option requires an argument -- %s";
130
static const char ambig[] = "ambiguous option -- %.*s";
131
static const char noarg[] = "option doesn't take an argument -- %.*s";
132
static const char illoptstring[] = "unknown option -- %s";
133
#endif
134
135
/*
136
* Compute the greatest common divisor of a and b.
137
*/
138
static int
139
gcd(int a, int b)
140
{
141
int c;
142
143
c = a % b;
144
while (c != 0) {
145
a = b;
146
b = c;
147
c = a % b;
148
}
149
150
return (b);
151
}
152
153
/*
154
* Exchange the block from nonopt_start to nonopt_end with the block
155
* from nonopt_end to opt_end (keeping the same order of arguments
156
* in each block).
157
*/
158
static void
159
permute_args(int panonopt_start, int panonopt_end, int opt_end,
160
char * const *nargv)
161
{
162
int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
163
char *swap;
164
165
/*
166
* compute lengths of blocks and number and size of cycles
167
*/
168
nnonopts = panonopt_end - panonopt_start;
169
nopts = opt_end - panonopt_end;
170
ncycle = gcd(nnonopts, nopts);
171
cyclelen = (opt_end - panonopt_start) / ncycle;
172
173
for (i = 0; i < ncycle; i++) {
174
cstart = panonopt_end+i;
175
pos = cstart;
176
for (j = 0; j < cyclelen; j++) {
177
if (pos >= panonopt_end)
178
pos -= nnonopts;
179
else
180
pos += nopts;
181
swap = nargv[pos];
182
/* LINTED const cast */
183
((char **) nargv)[pos] = nargv[cstart];
184
/* LINTED const cast */
185
((char **)nargv)[cstart] = swap;
186
}
187
}
188
}
189
190
/*
191
* parse_long_options --
192
* Parse long options in argc/argv argument vector.
193
* Returns -1 if short_too is set and the option does not match long_options.
194
*/
195
static int
196
parse_long_options(char * const *nargv, const char *options,
197
const struct option *long_options, int *idx, int short_too, int flags)
198
{
199
char *current_argv, *has_equal;
200
#ifdef GNU_COMPATIBLE
201
const char *current_dash;
202
#endif
203
size_t current_argv_len;
204
int i, match, exact_match, second_partial_match;
205
206
current_argv = place;
207
#ifdef GNU_COMPATIBLE
208
switch (dash_prefix) {
209
case D_PREFIX:
210
current_dash = "-";
211
break;
212
case DD_PREFIX:
213
current_dash = "--";
214
break;
215
case W_PREFIX:
216
current_dash = "-W ";
217
break;
218
default:
219
current_dash = "";
220
break;
221
}
222
#endif
223
match = -1;
224
exact_match = 0;
225
second_partial_match = 0;
226
227
optind++;
228
229
if ((has_equal = strchr(current_argv, '=')) != NULL) {
230
/* argument found (--option=arg) */
231
current_argv_len = has_equal - current_argv;
232
has_equal++;
233
} else
234
current_argv_len = strlen(current_argv);
235
236
for (i = 0; long_options[i].name; i++) {
237
/* find matching long option */
238
if (strncmp(current_argv, long_options[i].name,
239
current_argv_len))
240
continue;
241
242
if (strlen(long_options[i].name) == current_argv_len) {
243
/* exact match */
244
match = i;
245
exact_match = 1;
246
break;
247
}
248
/*
249
* If this is a known short option, don't allow
250
* a partial match of a single character.
251
*/
252
if (short_too && current_argv_len == 1)
253
continue;
254
255
if (match == -1) /* first partial match */
256
match = i;
257
else if ((flags & FLAG_LONGONLY) ||
258
long_options[i].has_arg !=
259
long_options[match].has_arg ||
260
long_options[i].flag != long_options[match].flag ||
261
long_options[i].val != long_options[match].val)
262
second_partial_match = 1;
263
}
264
if (!exact_match && second_partial_match) {
265
/* ambiguous abbreviation */
266
if (PRINT_ERROR)
267
sudo_warnx(ambig,
268
#ifdef GNU_COMPATIBLE
269
current_dash,
270
#endif
271
(int)current_argv_len,
272
current_argv);
273
optopt = 0;
274
return (BADCH);
275
}
276
if (match != -1) { /* option found */
277
if (long_options[match].has_arg == no_argument
278
&& has_equal) {
279
if (PRINT_ERROR)
280
sudo_warnx(noarg,
281
#ifdef GNU_COMPATIBLE
282
current_dash,
283
#endif
284
(int)current_argv_len,
285
current_argv);
286
/*
287
* XXX: GNU sets optopt to val regardless of flag
288
*/
289
if (long_options[match].flag == NULL)
290
optopt = long_options[match].val;
291
else
292
optopt = 0;
293
#ifdef GNU_COMPATIBLE
294
return (BADCH);
295
#else
296
return (BADARG);
297
#endif
298
}
299
if (long_options[match].has_arg == required_argument ||
300
long_options[match].has_arg == optional_argument) {
301
if (has_equal)
302
optarg = has_equal;
303
else if (long_options[match].has_arg ==
304
required_argument) {
305
/*
306
* optional argument doesn't use next nargv
307
*/
308
optarg = nargv[optind++];
309
}
310
}
311
if ((long_options[match].has_arg == required_argument)
312
&& (optarg == NULL)) {
313
/*
314
* Missing argument; leading ':' indicates no error
315
* should be generated.
316
*/
317
if (PRINT_ERROR)
318
sudo_warnx(recargstring,
319
#ifdef GNU_COMPATIBLE
320
current_dash,
321
#endif
322
current_argv);
323
/*
324
* XXX: GNU sets optopt to val regardless of flag
325
*/
326
if (long_options[match].flag == NULL)
327
optopt = long_options[match].val;
328
else
329
optopt = 0;
330
--optind;
331
return (BADARG);
332
}
333
} else { /* unknown option */
334
if (short_too) {
335
--optind;
336
return (-1);
337
}
338
if (PRINT_ERROR)
339
sudo_warnx(illoptstring,
340
#ifdef GNU_COMPATIBLE
341
current_dash,
342
#endif
343
current_argv);
344
optopt = 0;
345
return (BADCH);
346
}
347
if (idx)
348
*idx = match;
349
if (long_options[match].flag) {
350
*long_options[match].flag = long_options[match].val;
351
return (0);
352
} else
353
return (long_options[match].val);
354
}
355
356
/*
357
* getopt_internal --
358
* Parse argc/argv argument vector. Called by user level routines.
359
*/
360
static int
361
getopt_internal(int nargc, char * const *nargv, const char *options,
362
const struct option *long_options, int *idx, int flags)
363
{
364
char *oli; /* option letter list index */
365
int optchar, short_too;
366
int posixly_correct; /* no static, can be changed on the fly */
367
368
if (options == NULL)
369
return (-1);
370
371
/*
372
* Disable GNU extensions if POSIXLY_CORRECT is set or options
373
* string begins with a '+'.
374
*/
375
posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
376
#ifdef GNU_COMPATIBLE
377
if (*options == '-')
378
flags |= FLAG_ALLARGS;
379
else if (posixly_correct || *options == '+')
380
flags &= ~FLAG_PERMUTE;
381
#else
382
if (posixly_correct || *options == '+')
383
flags &= ~FLAG_PERMUTE;
384
else if (*options == '-')
385
flags |= FLAG_ALLARGS;
386
#endif
387
if (*options == '+' || *options == '-')
388
options++;
389
390
/*
391
* XXX Some GNU programs (like cvs) set optind to 0 instead of
392
* XXX using optreset. Work around this braindamage.
393
*/
394
if (optind == 0)
395
optind = optreset = 1;
396
397
optarg = NULL;
398
if (optreset)
399
nonopt_start = nonopt_end = -1;
400
start:
401
if (optreset || !*place) { /* update scanning pointer */
402
optreset = 0;
403
if (optind >= nargc) { /* end of argument vector */
404
place = EMSG;
405
if (nonopt_end != -1) {
406
/* do permutation, if we have to */
407
permute_args(nonopt_start, nonopt_end,
408
optind, nargv);
409
optind -= nonopt_end - nonopt_start;
410
}
411
else if (nonopt_start != -1) {
412
/*
413
* If we skipped non-options, set optind
414
* to the first of them.
415
*/
416
optind = nonopt_start;
417
}
418
nonopt_start = nonopt_end = -1;
419
return (-1);
420
}
421
if (*(place = nargv[optind]) != '-' ||
422
#ifdef GNU_COMPATIBLE
423
place[1] == '\0') {
424
#else
425
(place[1] == '\0' && strchr(options, '-') == NULL)) {
426
#endif
427
place = EMSG; /* found non-option */
428
if (flags & FLAG_ALLARGS) {
429
/*
430
* GNU extension:
431
* return non-option as argument to option 1
432
*/
433
optarg = nargv[optind++];
434
return (INORDER);
435
}
436
if (!(flags & FLAG_PERMUTE)) {
437
/*
438
* If no permutation wanted, stop parsing
439
* at first non-option.
440
*/
441
return (-1);
442
}
443
/* do permutation */
444
if (nonopt_start == -1)
445
nonopt_start = optind;
446
else if (nonopt_end != -1) {
447
permute_args(nonopt_start, nonopt_end,
448
optind, nargv);
449
nonopt_start = optind -
450
(nonopt_end - nonopt_start);
451
nonopt_end = -1;
452
}
453
optind++;
454
/* process next argument */
455
goto start;
456
}
457
if (nonopt_start != -1 && nonopt_end == -1)
458
nonopt_end = optind;
459
460
/*
461
* If we have "-" do nothing, if "--" we are done.
462
*/
463
if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
464
optind++;
465
place = EMSG;
466
/*
467
* We found an option (--), so if we skipped
468
* non-options, we have to permute.
469
*/
470
if (nonopt_end != -1) {
471
permute_args(nonopt_start, nonopt_end,
472
optind, nargv);
473
optind -= nonopt_end - nonopt_start;
474
}
475
nonopt_start = nonopt_end = -1;
476
return (-1);
477
}
478
}
479
480
/*
481
* Check long options if:
482
* 1) we were passed some
483
* 2) the arg is not just "-"
484
* 3) either the arg starts with -- we are getopt_long_only()
485
*/
486
if (long_options != NULL && place != nargv[optind] &&
487
(*place == '-' || (flags & FLAG_LONGONLY))) {
488
short_too = 0;
489
#ifdef GNU_COMPATIBLE
490
dash_prefix = D_PREFIX;
491
#endif
492
if (*place == '-') {
493
place++; /* --foo long option */
494
#ifdef GNU_COMPATIBLE
495
dash_prefix = DD_PREFIX;
496
#endif
497
} else if (*place != ':' && strchr(options, *place) != NULL)
498
short_too = 1; /* could be short option too */
499
500
optchar = parse_long_options(nargv, options, long_options,
501
idx, short_too, flags);
502
if (optchar != -1) {
503
place = EMSG;
504
return (optchar);
505
}
506
}
507
508
if ((optchar = (int)*place++) == (int)':' ||
509
(optchar == (int)'-' && *place != '\0') ||
510
(oli = strchr(options, optchar)) == NULL) {
511
/*
512
* If the user specified "-" and '-' isn't listed in
513
* options, return -1 (non-option) as per POSIX.
514
* Otherwise, it is an unknown option character (or ':').
515
*/
516
if (optchar == (int)'-' && *place == '\0')
517
return (-1);
518
if (!*place)
519
++optind;
520
#ifdef GNU_COMPATIBLE
521
if (PRINT_ERROR)
522
sudo_warnx(posixly_correct ? illoptchar : gnuoptchar,
523
optchar);
524
#else
525
if (PRINT_ERROR)
526
sudo_warnx(illoptchar, optchar);
527
#endif
528
optopt = optchar;
529
return (BADCH);
530
}
531
if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
532
/* -W long-option */
533
if (*place) /* no space */
534
/* NOTHING */;
535
else if (++optind >= nargc) { /* no arg */
536
place = EMSG;
537
if (PRINT_ERROR)
538
sudo_warnx(recargchar, optchar);
539
optopt = optchar;
540
return (BADARG);
541
} else /* white space */
542
place = nargv[optind];
543
#ifdef GNU_COMPATIBLE
544
dash_prefix = W_PREFIX;
545
#endif
546
optchar = parse_long_options(nargv, options, long_options,
547
idx, 0, flags);
548
place = EMSG;
549
return (optchar);
550
}
551
if (*++oli != ':') { /* doesn't take argument */
552
if (!*place)
553
++optind;
554
} else { /* takes (optional) argument */
555
optarg = NULL;
556
if (*place) /* no white space */
557
optarg = place;
558
else if (oli[1] != ':') { /* arg not optional */
559
if (++optind >= nargc) { /* no arg */
560
place = EMSG;
561
if (PRINT_ERROR)
562
sudo_warnx(recargchar, optchar);
563
optopt = optchar;
564
return (BADARG);
565
} else
566
optarg = nargv[optind];
567
}
568
place = EMSG;
569
++optind;
570
}
571
/* dump back option letter */
572
return (optchar);
573
}
574
575
#ifdef REPLACE_GETOPT
576
/*
577
* getopt --
578
* Parse argc/argv argument vector.
579
*/
580
int
581
sudo_getopt(int nargc, char * const *nargv, const char *options)
582
{
583
584
/*
585
* We don't pass FLAG_PERMUTE to getopt_internal() since
586
* the BSD getopt(3) (unlike GNU) has never done this.
587
*
588
* Furthermore, since many privileged programs call getopt()
589
* before dropping privileges it makes sense to keep things
590
* as simple (and bug-free) as possible.
591
*/
592
return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
593
}
594
#endif /* REPLACE_GETOPT */
595
596
/*
597
* getopt_long --
598
* Parse argc/argv argument vector.
599
*/
600
int
601
sudo_getopt_long(int nargc, char * const *nargv, const char *options,
602
const struct option *long_options, int *idx)
603
{
604
605
return (getopt_internal(nargc, nargv, options, long_options, idx,
606
FLAG_PERMUTE));
607
}
608
609
/*
610
* getopt_long_only --
611
* Parse argc/argv argument vector.
612
*/
613
int
614
sudo_getopt_long_only(int nargc, char * const *nargv, const char *options,
615
const struct option *long_options, int *idx)
616
{
617
618
return (getopt_internal(nargc, nargv, options, long_options, idx,
619
FLAG_PERMUTE|FLAG_LONGONLY));
620
}
621
622