summaryrefslogtreecommitdiffstats
path: root/src/parse_args.c
blob: 5282cc3808cba0172c549157e2a7bac4384719cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
/*
 * SPDX-License-Identifier: ISC
 *
 * Copyright (c) 1993-1996, 1998-2022 Todd C. Miller <Todd.Miller@sudo.ws>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Sponsored in part by the Defense Advanced Research Projects
 * Agency (DARPA) and Air Force Research Laboratory, Air Force
 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
 */

/*
 * This is an open source non-commercial project. Dear PVS-Studio, please check it.
 * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#ifdef HAVE_GETOPT_LONG
# include <getopt.h>
# else
# include "compat/getopt.h"
#endif /* HAVE_GETOPT_LONG */

#include <sudo_usage.h>
#include "sudo.h"
#include "sudo_lbuf.h"

int tgetpass_flags;

/*
 * Local functions.
 */
sudo_noreturn static void help(void);
sudo_noreturn static void usage_excl(void);
sudo_noreturn static void usage_excl_ticket(void);

/*
 * Mapping of command line options to name/value settings.
 * Do not reorder, indexes must match ARG_ defines in sudo.h.
 */
static struct sudo_settings sudo_settings[] = {
    { "bsdauth_type" },
    { "login_class" },
    { "preserve_environment" },
    { "runas_group" },
    { "set_home" },
    { "run_shell" },
    { "login_shell" },
    { "ignore_ticket" },
    { "update_ticket" },
    { "prompt" },
    { "selinux_role" },
    { "selinux_type" },
    { "runas_user" },
    { "progname" },
    { "implied_shell" },
    { "preserve_groups" },
    { "noninteractive" },
    { "sudoedit" },
    { "closefrom" },
    { "network_addrs" },
    { "max_groups" },
    { "plugin_dir" },
    { "remote_host" },
    { "timeout" },
    { "cmnd_chroot" },
    { "cmnd_cwd" },
    { "askpass" },
    { "intercept_setid" },
    { "intercept_ptrace" },
    { "apparmor_profile" },
    { NULL }
};

struct environment {
    char **envp;		/* pointer to the new environment */
    size_t env_size;		/* size of new_environ in char **'s */
    size_t env_len;		/* number of slots used, not counting NULL */
};

/*
 * Default flags allowed when running a command.
 */
#define DEFAULT_VALID_FLAGS	(MODE_BACKGROUND|MODE_PRESERVE_ENV|MODE_RESET_HOME|MODE_LOGIN_SHELL|MODE_NONINTERACTIVE|MODE_PRESERVE_GROUPS|MODE_SHELL)
#define EDIT_VALID_FLAGS	MODE_NONINTERACTIVE
#define LIST_VALID_FLAGS	(MODE_NONINTERACTIVE|MODE_LONG_LIST)
#define VALIDATE_VALID_FLAGS	MODE_NONINTERACTIVE

/* Option number for the --host long option due to ambiguity of the -h flag. */
#define OPT_HOSTNAME	256

/*
 * Available command line options, both short and long.
 * Note that we must disable arg permutation to support setting environment
 * variables and to better support the optional arg of the -h flag.
 * There is a more limited set of options for sudoedit (the sudo-specific
 * long options are listed first).
 */
static const char sudo_short_opts[] = "+Aa:BbC:c:D:Eeg:Hh::iKklNnPp:R:r:SsT:t:U:u:Vv";
static const char edit_short_opts[] = "+Aa:BC:c:D:g:h::KkNnp:R:r:ST:t:u:V";
static struct option sudo_long_opts[] = {
    /* sudo-specific long options */
    { "background",	no_argument,		NULL,	'b' },
    { "preserve-env",	optional_argument,	NULL,	'E' },
    { "edit",		no_argument,		NULL,	'e' },
    { "set-home",	no_argument,		NULL,	'H' },
    { "login",		no_argument,		NULL,	'i' },
    { "remove-timestamp", no_argument,		NULL,	'K' },
    { "list",		no_argument,		NULL,	'l' },
    { "preserve-groups", no_argument,		NULL,	'P' },
    { "shell",		no_argument,		NULL,	's' },
    { "other-user",	required_argument,	NULL,	'U' },
    { "validate",	no_argument,		NULL,	'v' },
    /* common long options */
    { "askpass",	no_argument,		NULL,	'A' },
    { "auth-type",	required_argument,	NULL,	'a' },
    { "bell",	        no_argument,		NULL,	'B' },
    { "close-from",	required_argument,	NULL,	'C' },
    { "login-class",	required_argument,	NULL,	'c' },
    { "chdir",		required_argument,	NULL,	'D' },
    { "group",		required_argument,	NULL,	'g' },
    { "help",		no_argument,		NULL,	'h' },
    { "host",		required_argument,	NULL,	OPT_HOSTNAME },
    { "reset-timestamp", no_argument,		NULL,	'k' },
    { "no-update",	no_argument,		NULL,	'N' },
    { "non-interactive", no_argument,		NULL,	'n' },
    { "prompt",		required_argument,	NULL,	'p' },
    { "chroot",		required_argument,	NULL,	'R' },
    { "role",		required_argument,	NULL,	'r' },
    { "stdin",		no_argument,		NULL,	'S' },
    { "command-timeout",required_argument,	NULL,	'T' },
    { "type",		required_argument,	NULL,	't' },
    { "user",		required_argument,	NULL,	'u' },
    { "version",	no_argument,		NULL,	'V' },
    { NULL,		no_argument,		NULL,	'\0' },
};
static struct option *edit_long_opts = &sudo_long_opts[11];

/*
 * Insert a key=value pair into the specified environment.
 */
static void
env_insert(struct environment *e, char *pair)
{
    debug_decl(env_insert, SUDO_DEBUG_ARGS);

    /* Make sure we have at least two slots free (one for NULL). */
    if (e->env_len + 1 >= e->env_size) {
	char **tmp;

	if (e->env_size == 0)
	    e->env_size = 16;
	tmp = reallocarray(e->envp, e->env_size, 2 * sizeof(char *));
	if (tmp == NULL)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	e->envp = tmp;
	e->env_size *= 2;
    }
    e->envp[e->env_len++] = pair;
    e->envp[e->env_len] = NULL;

    debug_return;
}

/*
 * Format as var=val and insert into the specified environment.
 */
static void
env_set(struct environment *e, char *var, char *val)
{
    char *pair;
    debug_decl(env_set, SUDO_DEBUG_ARGS);

    pair = sudo_new_key_val(var, val);
    if (pair == NULL) {
	sudo_fatalx(U_("%s: %s"),
	    __func__, U_("unable to allocate memory"));
    }
    env_insert(e, pair);

    debug_return;
}

/*
 * Parse a comma-separated list of env vars and add to the
 * specified environment.
 */
static void
parse_env_list(struct environment *e, char *list)
{
    char *cp, *last, *val;
    debug_decl(parse_env_list, SUDO_DEBUG_ARGS);

    for ((cp = strtok_r(list, ",", &last)); cp != NULL;
	(cp = strtok_r(NULL, ",", &last))) {
	if (strchr(cp, '=') != NULL) {
	    sudo_warnx(U_("invalid environment variable name: %s"), cp);
	    usage();
	}
	if ((val = getenv(cp)) != NULL)
	    env_set(e, cp, val);
    }
    debug_return;
}

/*
 * Command line argument parsing.
 * Sets nargc and nargv which corresponds to the argc/argv we'll use
 * for the command to be run (if we are running one).
 */
int
parse_args(int argc, char **argv, int *old_optind, int *nargc, char ***nargv,
    struct sudo_settings **settingsp, char ***env_addp)
{
    const char *progname, *short_opts = sudo_short_opts;
    struct option *long_opts = sudo_long_opts;
    struct environment extra_env;
    int mode = 0;		/* what mode is sudo to be run in? */
    int flags = 0;		/* mode flags */
    int valid_flags = DEFAULT_VALID_FLAGS;
    int ch, i;
    char *cp;
    debug_decl(parse_args, SUDO_DEBUG_ARGS);

    /* Is someone trying something funny? */
    if (argc <= 0)
	usage();

    /* The plugin API includes the program name (either sudo or sudoedit). */
    progname = getprogname();
    sudo_settings[ARG_PROGNAME].value = progname;

    /* First, check to see if we were invoked as "sudoedit". */
    if (strcmp(progname, "sudoedit") == 0) {
	mode = MODE_EDIT;
	sudo_settings[ARG_SUDOEDIT].value = "true";
	valid_flags = EDIT_VALID_FLAGS;
	short_opts = edit_short_opts;
	long_opts = edit_long_opts;
    }

    /* Load local IP addresses and masks. */
    if (get_net_ifs(&cp) > 0)
	sudo_settings[ARG_NET_ADDRS].value = cp;

    /* Set max_groups from sudo.conf. */
    i = sudo_conf_max_groups();
    if (i != -1) {
	if (asprintf(&cp, "%d", i) == -1)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	sudo_settings[ARG_MAX_GROUPS].value = cp;
    }

    /* Returns true if the last option string was "-h" */
#define got_host_flag	(optind > 1 && argv[optind - 1][0] == '-' && \
	    argv[optind - 1][1] == 'h' && argv[optind - 1][2] == '\0')

    /* Returns true if the last option string was "--" */
#define got_end_of_args	(optind > 1 && argv[optind - 1][0] == '-' && \
	    argv[optind - 1][1] == '-' && argv[optind - 1][2] == '\0')

    /* Returns true if next option is an environment variable */
#define is_envar (optind < argc && argv[optind][0] != '/' && \
	    argv[optind][0] != '=' && strchr(argv[optind], '=') != NULL)

    /* Space for environment variables is lazy allocated. */
    memset(&extra_env, 0, sizeof(extra_env));

    for (;;) {
	/*
	 * Some trickiness is required to allow environment variables
	 * to be interspersed with command line options.
	 */
	if ((ch = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
	    switch (ch) {
		case 'A':
		    SET(tgetpass_flags, TGP_ASKPASS);
		    sudo_settings[ARG_ASKPASS].value = "true";
		    break;
#ifdef HAVE_BSD_AUTH_H
		case 'a':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_BSDAUTH_TYPE].value != NULL)
			usage();
		    sudo_settings[ARG_BSDAUTH_TYPE].value = optarg;
		    break;
#endif
		case 'b':
		    SET(flags, MODE_BACKGROUND);
		    break;
		case 'B':
		    SET(tgetpass_flags, TGP_BELL);
		    break;
		case 'C':
		    assert(optarg != NULL);
		    if (sudo_strtonum(optarg, 3, INT_MAX, NULL) == 0) {
			sudo_warnx("%s",
			    U_("the argument to -C must be a number greater than or equal to 3"));
			usage();
		    }
		    if (sudo_settings[ARG_CLOSEFROM].value != NULL)
			usage();
		    sudo_settings[ARG_CLOSEFROM].value = optarg;
		    break;
#ifdef HAVE_LOGIN_CAP_H
		case 'c':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_LOGIN_CLASS].value != NULL)
			usage();
		    sudo_settings[ARG_LOGIN_CLASS].value = optarg;
		    break;
#endif
		case 'D':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_CWD].value != NULL)
			usage();
		    sudo_settings[ARG_CWD].value = optarg;
		    break;
		case 'E':
		    /*
		     * Optional argument is a comma-separated list of
		     * environment variables to preserve.
		     * If not present, preserve everything.
		     */
		    if (optarg == NULL) {
			sudo_settings[ARG_PRESERVE_ENVIRONMENT].value = "true";
			SET(flags, MODE_PRESERVE_ENV);
		    } else {
			parse_env_list(&extra_env, optarg);
		    }
		    break;
		case 'e':
		    if (mode && mode != MODE_EDIT)
			usage_excl();
		    mode = MODE_EDIT;
		    sudo_settings[ARG_SUDOEDIT].value = "true";
		    valid_flags = EDIT_VALID_FLAGS;
		    break;
		case 'g':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_RUNAS_GROUP].value != NULL)
			usage();
		    sudo_settings[ARG_RUNAS_GROUP].value = optarg;
		    break;
		case 'H':
		    sudo_settings[ARG_SET_HOME].value = "true";
		    SET(flags, MODE_RESET_HOME);
		    break;
		case 'h':
		    if (optarg == NULL) {
			/*
			 * Optional args support -hhostname, not -h hostname.
			 * If we see a non-option after the -h flag, treat as
			 * remote host and bump optind to skip over it.
			 */
			if (got_host_flag && argv[optind] != NULL &&
			    argv[optind][0] != '-' && !is_envar) {
			    if (sudo_settings[ARG_REMOTE_HOST].value != NULL)
				usage();
			    sudo_settings[ARG_REMOTE_HOST].value = argv[optind++];
			    continue;
			}
			if (mode && mode != MODE_HELP) {
			    if (strcmp(progname, "sudoedit") != 0)
				usage_excl();
			}
			mode = MODE_HELP;
			valid_flags = 0;
			break;
		    }
		    FALLTHROUGH;
		case OPT_HOSTNAME:
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_REMOTE_HOST].value != NULL)
			usage();
		    sudo_settings[ARG_REMOTE_HOST].value = optarg;
		    break;
		case 'i':
		    sudo_settings[ARG_LOGIN_SHELL].value = "true";
		    SET(flags, MODE_LOGIN_SHELL);
		    break;
		case 'K':
		    if (mode && mode != MODE_KILL)
			usage_excl();
		    mode = MODE_KILL;
		    valid_flags = 0;
		    FALLTHROUGH;
		case 'k':
		    if (sudo_settings[ARG_UPDATE_TICKET].value != NULL)
			usage_excl_ticket();
		    sudo_settings[ARG_IGNORE_TICKET].value = "true";
		    break;
		case 'l':
		    if (mode) {
			if (mode == MODE_LIST)
			    SET(flags, MODE_LONG_LIST);
			else
			    usage_excl();
		    }
		    mode = MODE_LIST;
		    valid_flags = LIST_VALID_FLAGS;
		    break;
		case 'N':
		    if (sudo_settings[ARG_IGNORE_TICKET].value != NULL)
			usage_excl_ticket();
		    sudo_settings[ARG_UPDATE_TICKET].value = "false";
		    break;
		case 'n':
		    SET(flags, MODE_NONINTERACTIVE);
		    sudo_settings[ARG_NONINTERACTIVE].value = "true";
		    break;
		case 'P':
		    sudo_settings[ARG_PRESERVE_GROUPS].value = "true";
		    SET(flags, MODE_PRESERVE_GROUPS);
		    break;
		case 'p':
		    /* An empty prompt is allowed. */
		    assert(optarg != NULL);
		    if (sudo_settings[ARG_PROMPT].value != NULL)
			usage();
		    sudo_settings[ARG_PROMPT].value = optarg;
		    break;
		case 'R':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_CHROOT].value != NULL)
			usage();
		    sudo_settings[ARG_CHROOT].value = optarg;
		    break;
#ifdef HAVE_SELINUX
		case 'r':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_SELINUX_ROLE].value != NULL)
			usage();
		    sudo_settings[ARG_SELINUX_ROLE].value = optarg;
		    break;
		case 't':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_SELINUX_TYPE].value != NULL)
			usage();
		    sudo_settings[ARG_SELINUX_TYPE].value = optarg;
		    break;
#endif
		case 'T':
		    /* Plugin determines whether empty timeout is allowed. */
		    assert(optarg != NULL);
		    if (sudo_settings[ARG_TIMEOUT].value != NULL)
			usage();
		    sudo_settings[ARG_TIMEOUT].value = optarg;
		    break;
		case 'S':
		    SET(tgetpass_flags, TGP_STDIN);
		    break;
		case 's':
		    sudo_settings[ARG_USER_SHELL].value = "true";
		    SET(flags, MODE_SHELL);
		    break;
		case 'U':
		    assert(optarg != NULL);
		    if (list_user != NULL || *optarg == '\0')
			usage();
		    list_user = optarg;
		    break;
		case 'u':
		    assert(optarg != NULL);
		    if (*optarg == '\0')
			usage();
		    if (sudo_settings[ARG_RUNAS_USER].value != NULL)
			usage();
		    sudo_settings[ARG_RUNAS_USER].value = optarg;
		    break;
		case 'v':
		    if (mode && mode != MODE_VALIDATE)
			usage_excl();
		    mode = MODE_VALIDATE;
		    valid_flags = VALIDATE_VALID_FLAGS;
		    break;
		case 'V':
		    if (mode && mode != MODE_VERSION) {
			if (strcmp(progname, "sudoedit") != 0)
			    usage_excl();
		    }
		    mode = MODE_VERSION;
		    valid_flags = 0;
		    break;
		default:
		    usage();
	    }
	} else if (!got_end_of_args && is_envar) {
	    /* Insert key=value pair, crank optind and resume getopt. */
	    env_insert(&extra_env, argv[optind]);
	    optind++;
	} else {
	    /* Not an option or an environment variable -- we're done. */
	    break;
	}
    }

    argc -= optind;
    argv += optind;
    *old_optind = optind;

    if (!mode) {
	/* Defer -k mode setting until we know whether it is a flag or not */
	if (sudo_settings[ARG_IGNORE_TICKET].value != NULL) {
	    if (argc == 0 && !ISSET(flags, MODE_SHELL|MODE_LOGIN_SHELL)) {
		mode = MODE_INVALIDATE;	/* -k by itself */
		sudo_settings[ARG_IGNORE_TICKET].value = NULL;
		valid_flags = 0;
	    }
	}
	if (!mode)
	    mode = MODE_RUN;		/* running a command */
    }

    if (argc > 0 && mode == MODE_LIST)
	mode = MODE_CHECK;

    if (ISSET(flags, MODE_LOGIN_SHELL)) {
	if (ISSET(flags, MODE_SHELL)) {
	    sudo_warnx("%s",
		U_("you may not specify both the -i and -s options"));
	    usage();
	}
	if (ISSET(flags, MODE_PRESERVE_ENV)) {
	    sudo_warnx("%s",
		U_("you may not specify both the -i and -E options"));
	    usage();
	}
	SET(flags, MODE_SHELL);
    }
    if ((flags & valid_flags) != flags)
	usage();
    if (mode == MODE_EDIT &&
       (ISSET(flags, MODE_PRESERVE_ENV) || extra_env.env_len != 0)) {
	if (ISSET(mode, MODE_PRESERVE_ENV))
	    sudo_warnx("%s", U_("the -E option is not valid in edit mode"));
	if (extra_env.env_len != 0)
	    sudo_warnx("%s",
		U_("you may not specify environment variables in edit mode"));
	usage();
    }
    if ((sudo_settings[ARG_RUNAS_USER].value != NULL ||
	 sudo_settings[ARG_RUNAS_GROUP].value != NULL) &&
	!ISSET(mode, MODE_EDIT | MODE_RUN | MODE_CHECK | MODE_VALIDATE)) {
	usage();
    }
    if (list_user != NULL && mode != MODE_LIST && mode != MODE_CHECK) {
	sudo_warnx("%s",
	    U_("the -U option may only be used with the -l option"));
	usage();
    }
    if (ISSET(tgetpass_flags, TGP_STDIN) && ISSET(tgetpass_flags, TGP_ASKPASS)) {
	sudo_warnx("%s", U_("the -A and -S options may not be used together"));
	usage();
    }
    if ((argc == 0 && mode == MODE_EDIT) ||
	(argc > 0 && !ISSET(mode, MODE_RUN | MODE_EDIT | MODE_CHECK)))
	usage();
    if (argc == 0 && mode == MODE_RUN && !ISSET(flags, MODE_SHELL)) {
	SET(flags, (MODE_IMPLIED_SHELL | MODE_SHELL));
	sudo_settings[ARG_IMPLIED_SHELL].value = "true";
    }
#ifdef ENABLE_SUDO_PLUGIN_API
    sudo_settings[ARG_PLUGIN_DIR].value = sudo_conf_plugin_dir_path();
#endif
    if (exec_ptrace_intercept_supported())
	sudo_settings[ARG_INTERCEPT_SETID].value = "true";
    if (exec_ptrace_subcmds_supported())
	sudo_settings[ARG_INTERCEPT_PTRACE].value = "true";

    if (mode == MODE_HELP)
	help();

    /*
     * For shell mode we need to rewrite argv
     * TODO: move this to the policy plugin and make escaping configurable
     */
    if (ISSET(flags, MODE_SHELL|MODE_LOGIN_SHELL) && ISSET(mode, MODE_RUN)) {
	char **av, *cmnd = NULL;
	int ac = 1;

	if (argc != 0) {
	    /* shell -c "command" */
	    char *src, *dst;
	    size_t size = 0;

	    for (av = argv; *av != NULL; av++)
		size += strlen(*av) + 1;
	    if (size == 0 || (cmnd = reallocarray(NULL, size, 2)) == NULL)
		sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	    if (!gc_add(GC_PTR, cmnd))
		exit(EXIT_FAILURE);

	    for (dst = cmnd, av = argv; *av != NULL; av++) {
		for (src = *av; *src != '\0'; src++) {
		    /* quote potential meta characters */
		    if (!isalnum((unsigned char)*src) && *src != '_' && *src != '-' && *src != '$')
			*dst++ = '\\';
		    *dst++ = *src;
		}
		*dst++ = ' ';
	    }
	    if (cmnd != dst)
		dst--;  /* replace last space with a NUL */
	    *dst = '\0';

	    ac += 2; /* -c cmnd */
	}

	av = reallocarray(NULL, ac + 1, sizeof(char *));
	if (av == NULL)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	if (!gc_add(GC_PTR, av))
	    exit(EXIT_FAILURE);

	av[0] = (char *)user_details.shell; /* plugin may override shell */
	if (cmnd != NULL) {
	    av[1] = (char *)"-c";
	    av[2] = cmnd;
	}
	av[ac] = NULL;

	argv = av;
	argc = ac;
    }

    /*
     * For sudoedit we need to rewrite argv
     */
    if (mode == MODE_EDIT) {
#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID)
	char **av;
	int ac;

	av = reallocarray(NULL, argc + 2, sizeof(char *));
	if (av == NULL)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	if (!gc_add(GC_PTR, av))
	    exit(EXIT_FAILURE);

	/* Must have the command in argv[0]. */
	av[0] = (char *)"sudoedit";
	for (ac = 0; argv[ac] != NULL; ac++) {
	    av[ac + 1] = argv[ac];
	}
	av[++ac] = NULL;

	argv = av;
	argc = ac;
#else
	sudo_fatalx("%s", U_("sudoedit is not supported on this platform"));
#endif
    }

    *settingsp = sudo_settings;
    *env_addp = extra_env.envp;
    *nargc = argc;
    *nargv = argv;
    debug_return_int(mode | flags);
}

static int
usage_err(const char *buf)
{
    return fputs(buf, stderr);
}

static int
usage_out(const char *buf)
{
    return fputs(buf, stdout);
}

/*
 * Display usage message.
 * The actual usage strings are in sudo_usage.h for configure substitution.
 */
static void
display_usage(int (*output)(const char *))
{
    struct sudo_lbuf lbuf;
    const char *uvec[6];
    int i, ulen;

    /*
     * Use usage vectors appropriate to the progname.
     */
    if (strcmp(getprogname(), "sudoedit") == 0) {
	uvec[0] = SUDO_USAGE0;
	uvec[1] = &SUDO_USAGE5[3];	/* skip the leading "-e " */
	uvec[2] = NULL;
    } else {
	uvec[0] = SUDO_USAGE1;
	uvec[1] = SUDO_USAGE2;
	uvec[2] = SUDO_USAGE3;
	uvec[3] = SUDO_USAGE4;
	uvec[4] = SUDO_USAGE5;
	uvec[5] = NULL;
    }

    /*
     * Print usage and wrap lines as needed, depending on the
     * tty width.
     */
    ulen = (int)strlen(getprogname()) + 8;
    sudo_lbuf_init(&lbuf, output, ulen, NULL,
	user_details.ts_cols);
    for (i = 0; uvec[i] != NULL; i++) {
	sudo_lbuf_append(&lbuf, "usage: %s%s", getprogname(), uvec[i]);
	sudo_lbuf_print(&lbuf);
    }
    sudo_lbuf_destroy(&lbuf);
}

/*
 * Display usage message and exit.
 */
void
usage(void)
{
    display_usage(usage_err);
    exit(EXIT_FAILURE);
}

/*
 * Tell which options are mutually exclusive and exit.
 */
static void
usage_excl(void)
{
    debug_decl(usage_excl, SUDO_DEBUG_ARGS);

    sudo_warnx("%s",
	U_("Only one of the -e, -h, -i, -K, -l, -s, -v or -V options may be specified"));
    usage();
}

/*
 * Tell which options are mutually exclusive and exit.
 */
static void
usage_excl_ticket(void)
{
    debug_decl(usage_excl_ticket, SUDO_DEBUG_ARGS);

    sudo_warnx("%s",
	U_("Only one of the -K, -k or -N options may be specified"));
    usage();
}

static void
help(void)
{
    struct sudo_lbuf lbuf;
    const int indent = 32;
    const char *pname = getprogname();
    bool sudoedit = false;
    debug_decl(help, SUDO_DEBUG_ARGS);

    sudo_lbuf_init(&lbuf, usage_out, indent, NULL, user_details.ts_cols);
    if (strcmp(pname, "sudoedit") == 0) {
	sudoedit = true;
	sudo_lbuf_append(&lbuf, _("%s - edit files as another user\n\n"), pname);
    } else {
	sudo_lbuf_append(&lbuf, _("%s - execute a command as another user\n\n"), pname);
    }
    sudo_lbuf_print(&lbuf);

    display_usage(usage_out);

    sudo_lbuf_append(&lbuf, "%s", _("\nOptions:\n"));
    sudo_lbuf_append(&lbuf, "  -A, --askpass                 %s\n",
	_("use a helper program for password prompting"));
#ifdef HAVE_BSD_AUTH_H
    sudo_lbuf_append(&lbuf, "  -a, --auth-type=type          %s\n",
	_("use specified BSD authentication type"));
#endif
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -b, --background              %s\n",
	    _("run command in the background"));
    }
    sudo_lbuf_append(&lbuf, "  -B, --bell                    %s\n",
	_("ring bell when prompting"));
    sudo_lbuf_append(&lbuf, "  -C, --close-from=num          %s\n",
	_("close all file descriptors >= num"));
#ifdef HAVE_LOGIN_CAP_H
    sudo_lbuf_append(&lbuf, "  -c, --login-class=class       %s\n",
	_("run command with the specified BSD login class"));
#endif
    sudo_lbuf_append(&lbuf, "  -D, --chdir=directory         %s\n",
	_("change the working directory before running command"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -E, --preserve-env            %s\n",
	    _("preserve user environment when running command"));
	sudo_lbuf_append(&lbuf, "      --preserve-env=list       %s\n",
	    _("preserve specific environment variables"));
	sudo_lbuf_append(&lbuf, "  -e, --edit                    %s\n",
	    _("edit files instead of running a command"));
    }
    sudo_lbuf_append(&lbuf, "  -g, --group=group             %s\n",
	_("run command as the specified group name or ID"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -H, --set-home                %s\n",
	    _("set HOME variable to target user's home dir"));
    }
    sudo_lbuf_append(&lbuf, "  -h, --help                    %s\n",
	_("display help message and exit"));
    sudo_lbuf_append(&lbuf, "  -h, --host=host               %s\n",
	_("run command on host (if supported by plugin)"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -i, --login                   %s\n",
	    _("run login shell as the target user; a command may also be specified"));
	sudo_lbuf_append(&lbuf, "  -K, --remove-timestamp        %s\n",
	    _("remove timestamp file completely"));
    }
    sudo_lbuf_append(&lbuf, "  -k, --reset-timestamp         %s\n",
	_("invalidate timestamp file"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -l, --list                    %s\n",
	    _("list user's privileges or check a specific command; use twice for longer format"));
    }
    sudo_lbuf_append(&lbuf, "  -n, --non-interactive         %s\n",
	_("non-interactive mode, no prompts are used"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -P, --preserve-groups         %s\n",
	    _("preserve group vector instead of setting to target's"));
    }
    sudo_lbuf_append(&lbuf, "  -p, --prompt=prompt           %s\n",
	_("use the specified password prompt"));
    sudo_lbuf_append(&lbuf, "  -R, --chroot=directory        %s\n",
	_("change the root directory before running command"));
#ifdef HAVE_SELINUX
    sudo_lbuf_append(&lbuf, "  -r, --role=role               %s\n",
	_("create SELinux security context with specified role"));
#endif
    sudo_lbuf_append(&lbuf, "  -S, --stdin                   %s\n",
	_("read password from standard input"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -s, --shell                   %s\n",
	    _("run shell as the target user; a command may also be specified"));
    }
#ifdef HAVE_SELINUX
    sudo_lbuf_append(&lbuf, "  -t, --type=type               %s\n",
	_("create SELinux security context with specified type"));
#endif
    sudo_lbuf_append(&lbuf, "  -T, --command-timeout=timeout %s\n",
	_("terminate command after the specified time limit"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -U, --other-user=user         %s\n",
	    _("in list mode, display privileges for user"));
    }
    sudo_lbuf_append(&lbuf, "  -u, --user=user               %s\n",
	_("run command (or edit file) as specified user name or ID"));
    sudo_lbuf_append(&lbuf, "  -V, --version                 %s\n",
	_("display version information and exit"));
    if (!sudoedit) {
	sudo_lbuf_append(&lbuf, "  -v, --validate                %s\n",
	    _("update user's timestamp without running a command"));
    }
    sudo_lbuf_append(&lbuf, "  --                            %s\n",
	_("stop processing command line arguments"));
    sudo_lbuf_print(&lbuf);
    sudo_lbuf_destroy(&lbuf);
    sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, 0);
    exit(EXIT_SUCCESS);
}