Imported Upstream version 1.6.9p16
[debian/sudo] / sudo.c
1 /*
2  * Copyright (c) 1993-1996,1998-2007 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  *
16  * Sponsored in part by the Defense Advanced Research Projects
17  * Agency (DARPA) and Air Force Research Laboratory, Air Force
18  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
19  *
20  * For a brief history of sudo, please see the HISTORY file included
21  * with this distribution.
22  */
23
24 #define _SUDO_MAIN
25
26 #ifdef __TANDEM
27 # include <floss.h>
28 #endif
29
30 #include <config.h>
31
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #ifdef HAVE_SETRLIMIT
37 # include <sys/time.h>
38 # include <sys/resource.h>
39 #endif
40 #include <stdio.h>
41 #ifdef STDC_HEADERS
42 # include <stdlib.h>
43 # include <stddef.h>
44 #else
45 # ifdef HAVE_STDLIB_H
46 #  include <stdlib.h>
47 # endif
48 #endif /* STDC_HEADERS */
49 #ifdef HAVE_STRING_H
50 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
51 #  include <memory.h>
52 # endif
53 # include <string.h>
54 #else
55 # ifdef HAVE_STRINGS_H
56 #  include <strings.h>
57 # endif
58 #endif /* HAVE_STRING_H */
59 #ifdef HAVE_UNISTD_H
60 # include <unistd.h>
61 #endif /* HAVE_UNISTD_H */
62 #ifdef HAVE_ERR_H
63 # include <err.h>
64 #else
65 # include "emul/err.h"
66 #endif /* HAVE_ERR_H */
67 #include <pwd.h>
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <signal.h>
71 #include <grp.h>
72 #if TIME_WITH_SYS_TIME
73 # include <time.h>
74 #endif
75 #ifdef HAVE_SETLOCALE
76 # include <locale.h>
77 #endif
78 #include <netinet/in.h>
79 #include <netdb.h>
80 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
81 # ifdef __hpux
82 #  undef MAXINT
83 #  include <hpsecurity.h>
84 # else
85 #  include <sys/security.h>
86 # endif /* __hpux */
87 # include <prot.h>
88 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
89 #ifdef HAVE_LOGIN_CAP_H
90 # include <login_cap.h>
91 # ifndef LOGIN_DEFROOTCLASS
92 #  define LOGIN_DEFROOTCLASS    "daemon"
93 # endif
94 #endif
95 #ifdef HAVE_PROJECT_H
96 # include <project.h>
97 # include <sys/task.h>
98 #endif
99 #ifdef HAVE_SELINUX
100 # include <selinux/selinux.h>
101 #endif
102
103 #include "sudo.h"
104 #include "interfaces.h"
105 #include "version.h"
106
107 #ifndef lint
108 __unused __unused static const char rcsid[] = "$Sudo: sudo.c,v 1.369.2.39 2008/04/10 17:56:05 millert Exp $";
109 #endif /* lint */
110
111 /*
112  * Prototypes
113  */
114 static int init_vars                    __P((int, char **));
115 static int parse_args                   __P((int, char **));
116 static void check_sudoers               __P((void));
117 static void initial_setup               __P((void));
118 static void set_loginclass              __P((struct passwd *));
119 static void set_project                 __P((struct passwd *));
120 static void usage                       __P((int))
121                                             __attribute__((__noreturn__));
122 static void usage_excl                  __P((int))
123                                             __attribute__((__noreturn__));
124 static void usage_excl                  __P((int));
125 static struct passwd *get_authpw        __P((void));
126 extern int sudo_edit                    __P((int, char **, char **));
127 extern void list_matches                __P((void));
128 extern char **rebuild_env               __P((char **, int, int));
129 extern void validate_env_vars           __P((struct list_member *));
130 extern char **insert_env_vars           __P((char **, struct list_member *));
131 extern struct passwd *sudo_getpwnam     __P((const char *));
132 extern struct passwd *sudo_getpwuid     __P((uid_t));
133 extern struct passwd *sudo_pwdup        __P((const struct passwd *));
134
135 /*
136  * Globals
137  */
138 int Argc, NewArgc;
139 char **Argv, **NewArgv;
140 char *prev_user;
141 struct sudo_user sudo_user;
142 struct passwd *auth_pw;
143 FILE *sudoers_fp;
144 struct interface *interfaces;
145 int num_interfaces;
146 int tgetpass_flags;
147 uid_t timestamp_uid;
148 extern int errorlineno;
149 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
150 static struct rlimit corelimit;
151 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
152 #ifdef HAVE_LOGIN_CAP_H
153 login_cap_t *lc;
154 #endif /* HAVE_LOGIN_CAP_H */
155 #ifdef HAVE_BSD_AUTH_H
156 char *login_style;
157 #endif /* HAVE_BSD_AUTH_H */
158 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp, saved_sa_chld;
159
160
161 int
162 main(argc, argv, envp)
163     int argc;
164     char **argv;
165     char **envp;
166 {
167     int validated;
168     int fd;
169     int cmnd_status;
170     int sudo_mode;
171     int pwflag;
172     sigaction_t sa;
173     extern int printmatches;
174     extern char **environ;
175
176 #ifdef HAVE_SETLOCALE
177     setlocale(LC_ALL, "");
178 #endif
179
180     Argv = argv;
181     if ((Argc = argc) < 1)
182         usage(1);
183
184     /* Must be done as the first thing... */
185 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
186     (void) set_auth_parameters(Argc, Argv);
187 # ifdef HAVE_INITPRIVS
188     initprivs();
189 # endif
190 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
191
192     if (geteuid() != 0)
193         errx(1, "must be setuid root");
194
195     /*
196      * Signal setup:
197      *  Ignore keyboard-generated signals so the user cannot interrupt
198      *  us at some point and avoid the logging.
199      *  Install handler to wait for children when they exit.
200      */
201     sigemptyset(&sa.sa_mask);
202     sa.sa_flags = SA_RESTART;
203     sa.sa_handler = SIG_IGN;
204     (void) sigaction(SIGINT, &sa, &saved_sa_int);
205     (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
206     (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
207     sa.sa_handler = reapchild;
208     (void) sigaction(SIGCHLD, &sa, &saved_sa_chld);
209
210     /*
211      * Turn off core dumps and close open files.
212      */
213     initial_setup();
214     setpwent();
215
216     /* Parse our arguments. */
217     sudo_mode = parse_args(Argc, Argv);
218
219     /* Setup defaults data structures. */
220     init_defaults();
221
222     /* Load the list of local ip addresses and netmasks.  */
223     load_interfaces();
224
225     pwflag = 0;
226     if (ISSET(sudo_mode, MODE_SHELL))
227         user_cmnd = "shell";
228     else if (ISSET(sudo_mode, MODE_EDIT))
229         user_cmnd = "sudoedit";
230     else
231         switch (sudo_mode) {
232             case MODE_VERSION:
233                 (void) printf("Sudo version %s\n", version);
234                 if (getuid() == 0) {
235                     putchar('\n');
236                     (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
237                     dump_auth_methods();
238                     dump_defaults();
239                     dump_interfaces();
240                 }
241                 exit(0);
242                 break;
243             case MODE_HELP:
244                 usage(0);
245                 break;
246             case MODE_VALIDATE:
247                 user_cmnd = "validate";
248                 pwflag = I_VERIFYPW;
249                 break;
250             case MODE_KILL:
251             case MODE_INVALIDATE:
252                 user_cmnd = "kill";
253                 pwflag = -1;
254                 break;
255             case MODE_LISTDEFS:
256                 list_options();
257                 exit(0);
258                 break;
259             case MODE_LIST:
260                 user_cmnd = "list";
261                 pwflag = I_LISTPW;
262                 printmatches = 1;
263                 break;
264         }
265
266     /* Must have a command to run... */
267     if (user_cmnd == NULL && NewArgc == 0)
268         usage(1);
269
270     cmnd_status = init_vars(sudo_mode, environ);
271
272 #ifdef HAVE_LDAP
273     validated = sudo_ldap_check(pwflag);
274
275     /* Skip reading /etc/sudoers if LDAP told us to */
276     if (!def_ignore_local_sudoers) {
277         int v;
278
279         check_sudoers();        /* check mode/owner on _PATH_SUDOERS */
280
281         /* Local sudoers file overrides LDAP if we have a match. */
282         v = sudoers_lookup(pwflag);
283         if (validated == VALIDATE_ERROR || ISSET(v, VALIDATE_OK))
284             validated = v;
285     }
286 #else
287     check_sudoers();    /* check mode/owner on _PATH_SUDOERS */
288
289     /* Validate the user but don't search for pseudo-commands. */
290     validated = sudoers_lookup(pwflag);
291 #endif
292     if (safe_cmnd == NULL)
293         safe_cmnd = estrdup(user_cmnd);
294
295     /*
296      * Look up the timestamp dir owner if one is specified.
297      */
298     if (def_timestampowner) {
299         struct passwd *pw;
300
301         if (*def_timestampowner == '#')
302             pw = getpwuid(atoi(def_timestampowner + 1));
303         else
304             pw = getpwnam(def_timestampowner);
305         if (!pw)
306             log_error(0, "timestamp owner (%s): No such user",
307                 def_timestampowner);
308         timestamp_uid = pw->pw_uid;
309     }
310
311     /* This goes after the sudoers parse since we honor sudoers options. */
312     if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
313         remove_timestamp((sudo_mode == MODE_KILL));
314         exit(0);
315     }
316
317     if (ISSET(validated, VALIDATE_ERROR))
318         log_error(0, "parse error in %s near line %d", _PATH_SUDOERS,
319             errorlineno);
320
321     /* Is root even allowed to run sudo? */
322     if (user_uid == 0 && !def_root_sudo) {
323         (void) fprintf(stderr,
324             "Sorry, %s has been configured to not allow root to run it.\n",
325             getprogname());
326         exit(1);
327     }
328
329     /* If given the -P option, set the "preserve_groups" flag. */
330     if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
331         def_preserve_groups = TRUE;
332
333     /* If no command line args and "set_home" is not set, error out. */
334     if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
335         usage(1);
336
337     /* Bail if a tty is required and we don't have one.  */
338     if (def_requiretty) {
339         if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1)
340             log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
341         else
342             (void) close(fd);
343     }
344
345     /* User may have overriden environment resetting via the -E flag. */
346     if (ISSET(sudo_mode, MODE_PRESERVE_ENV) && ISSET(validated, FLAG_SETENV))
347         def_env_reset = FALSE;
348
349     /* Build a new environment that avoids any nasty bits. */
350     environ = rebuild_env(environ, sudo_mode, ISSET(validated, FLAG_NOEXEC));
351
352     /* Fill in passwd struct based on user we are authenticating as.  */
353     auth_pw = get_authpw();
354
355     /* Require a password if sudoers says so.  */
356     if (!ISSET(validated, FLAG_NOPASS))
357         check_user(validated);
358
359     /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
360     if (user_uid == 0 && prev_user != NULL && strcmp(prev_user, "root") != 0) {
361             struct passwd *pw;
362
363             if ((pw = sudo_getpwnam(prev_user)) != NULL) {
364                     efree(sudo_user.pw);
365                     sudo_user.pw = pw;
366             }
367     }
368
369     if (ISSET(validated, VALIDATE_OK)) {
370         /* Finally tell the user if the command did not exist. */
371         if (cmnd_status == NOT_FOUND_DOT) {
372             warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
373             exit(1);
374         } else if (cmnd_status == NOT_FOUND) {
375             warnx("%s: command not found", user_cmnd);
376             exit(1);
377         }
378
379         /* If user specified env vars make sure sudoers allows it. */
380         if (ISSET(sudo_mode, MODE_RUN) && !ISSET(validated, FLAG_SETENV)) {
381             if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
382                 log_error(NO_MAIL,
383                     "sorry, you are not allowed to preserve the environment");
384             else
385                 validate_env_vars(sudo_user.env_vars);
386         }
387
388         log_auth(validated, 1);
389         if (sudo_mode == MODE_VALIDATE)
390             exit(0);
391         else if (sudo_mode == MODE_LIST) {
392             list_matches();
393 #ifdef HAVE_LDAP
394             sudo_ldap_list_matches();
395 #endif
396             exit(0);
397         }
398
399         /* Override user's umask if configured to do so. */
400         if (def_umask != 0777)
401             (void) umask(def_umask);
402
403         /* Restore coredumpsize resource limit. */
404 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
405         (void) setrlimit(RLIMIT_CORE, &corelimit);
406 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
407
408         /* Become specified user or root if executing a command. */
409         if (ISSET(sudo_mode, MODE_RUN))
410             set_perms(PERM_FULL_RUNAS);
411
412         /* Close the password and group files */
413         endpwent();
414         endgrent();
415
416         if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
417             char *p;
418
419             /* Convert /bin/sh -> -sh so shell knows it is a login shell */
420             if ((p = strrchr(NewArgv[0], '/')) == NULL)
421                 p = NewArgv[0];
422             *p = '-';
423             NewArgv[0] = p;
424
425             /* Change to target user's homedir. */
426             if (chdir(runas_pw->pw_dir) == -1)
427                 warn("unable to change directory to %s", runas_pw->pw_dir);
428         }
429
430         if (ISSET(sudo_mode, MODE_EDIT))
431             exit(sudo_edit(NewArgc, NewArgv, envp));
432
433         /* Insert user-specified environment variables. */
434         environ = insert_env_vars(environ, sudo_user.env_vars);
435
436         /* Restore signal handlers before we exec. */
437         (void) sigaction(SIGINT, &saved_sa_int, NULL);
438         (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
439         (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
440         (void) sigaction(SIGCHLD, &saved_sa_chld, NULL);
441
442 #ifndef PROFILING
443         if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0)
444             exit(0);
445         else {
446 #ifdef HAVE_SELINUX
447             if (is_selinux_enabled() > 0 && user_role != NULL)
448                 selinux_exec(user_role, user_type, NewArgv, environ,
449                     ISSET(sudo_mode, MODE_LOGIN_SHELL));
450 #endif
451             execve(safe_cmnd, NewArgv, environ);
452         }
453 #else
454         exit(0);
455 #endif /* PROFILING */
456         /*
457          * If we got here then the exec() failed...
458          */
459         if (errno == ENOEXEC) {
460             NewArgv--;                  /* at least one extra slot... */
461             NewArgv[0] = "sh";
462             NewArgv[1] = safe_cmnd;
463             execve(_PATH_BSHELL, NewArgv, environ);
464         }
465         warn("unable to execute %s", safe_cmnd);
466         exit(127);
467     } else if (ISSET(validated, FLAG_NO_USER) || (validated & FLAG_NO_HOST)) {
468         log_auth(validated, 1);
469         exit(1);
470     } else if (ISSET(validated, VALIDATE_NOT_OK)) {
471         if (def_path_info) {
472             /*
473              * We'd like to not leak path info at all here, but that can
474              * *really* confuse the users.  To really close the leak we'd
475              * have to say "not allowed to run foo" even when the problem
476              * is just "no foo in path" since the user can trivially set
477              * their path to just contain a single dir.
478              */
479             log_auth(validated,
480                 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
481             if (cmnd_status == NOT_FOUND)
482                 warnx("%s: command not found", user_cmnd);
483             else if (cmnd_status == NOT_FOUND_DOT)
484                 warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
485         } else {
486             /* Just tell the user they are not allowed to run foo. */
487             log_auth(validated, 1);
488         }
489         exit(1);
490     } else {
491         /* should never get here */
492         log_auth(validated, 1);
493         exit(1);
494     }
495     exit(0);    /* not reached */
496 }
497
498 /*
499  * Initialize timezone, set umask, fill in ``sudo_user'' struct and
500  * load the ``interfaces'' array.
501  */
502 static int
503 init_vars(sudo_mode, envp)
504     int sudo_mode;
505     char **envp;
506 {
507     char *p, **ep, thost[MAXHOSTNAMELEN];
508     int nohostname, rval;
509
510     /* Sanity check command from user. */
511     if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
512         errx(1, "%s: File name too long", NewArgv[0]);
513
514 #ifdef HAVE_TZSET
515     (void) tzset();             /* set the timezone if applicable */
516 #endif /* HAVE_TZSET */
517
518     /* Default value for cmnd and cwd, overridden later. */
519     if (user_cmnd == NULL)
520         user_cmnd = NewArgv[0];
521     (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
522
523     /*
524      * We avoid gethostbyname() if possible since we don't want
525      * sudo to block if DNS or NIS is hosed.
526      * "host" is the (possibly fully-qualified) hostname and
527      * "shost" is the unqualified form of the hostname.
528      */
529     nohostname = gethostname(thost, sizeof(thost));
530     if (nohostname)
531         user_host = user_shost = "localhost";
532     else {
533         user_host = estrdup(thost);
534         if (def_fqdn) {
535             /* Defer call to set_fqdn() until log_error() is safe. */
536             user_shost = user_host;
537         } else {
538             if ((p = strchr(user_host, '.'))) {
539                 *p = '\0';
540                 user_shost = estrdup(user_host);
541                 *p = '.';
542             } else {
543                 user_shost = user_host;
544             }
545         }
546     }
547
548     if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
549         user_tty = user_ttypath = estrdup(p);
550         if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
551             user_tty += sizeof(_PATH_DEV) - 1;
552     } else
553         user_tty = "unknown";
554
555     for (ep = envp; *ep; ep++) {
556         switch (**ep) {
557             case 'P':
558                 if (strncmp("PATH=", *ep, 5) == 0)
559                     user_path = *ep + 5;
560                 break;
561             case 'S':
562                 if (strncmp("SHELL=", *ep, 6) == 0)
563                     user_shell = *ep + 6;
564                 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
565                     user_prompt = *ep + 12;
566                 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
567                     prev_user = *ep + 10;
568                 break;
569
570             }
571     }
572
573     /*
574      * Get a local copy of the user's struct passwd with the shadow password
575      * if necessary.  It is assumed that euid is 0 at this point so we
576      * can read the shadow passwd file if necessary.
577      */
578     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
579         /* Need to make a fake struct passwd for logging to work. */
580         struct passwd pw;
581         char pw_name[MAX_UID_T_LEN + 1];
582
583         pw.pw_uid = getuid();
584         (void) snprintf(pw_name, sizeof(pw_name), "%lu",
585             (unsigned long) pw.pw_uid);
586         pw.pw_name = pw_name;
587         sudo_user.pw = &pw;
588
589         /*
590          * If we are in -k/-K mode, just spew to stderr.  It is not unusual for
591          * users to place "sudo -k" in a .logout file which can cause sudo to
592          * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
593          */
594         if (sudo_mode & (MODE_INVALIDATE|MODE_KILL))
595             errx(1, "uid %s does not exist in the passwd file!", pw_name);
596         log_error(0, "uid %s does not exist in the passwd file!", pw_name);
597     }
598     if (user_shell == NULL || *user_shell == '\0')
599         user_shell = sudo_user.pw->pw_shell;
600
601     /* It is now safe to use log_error() and set_perms() */
602
603 #ifdef HAVE_GETGROUPS
604     if ((user_ngroups = getgroups(0, NULL)) > 0) {
605         user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
606         if (getgroups(user_ngroups, user_groups) < 0)
607             log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
608     } else
609         user_ngroups = 0;
610 #endif
611
612     if (def_fqdn)
613         set_fqdn();                     /* may call log_error() */
614
615     if (nohostname)
616         log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
617
618     set_runaspw(*user_runas);           /* may call log_error() */
619     if (*user_runas[0] == '#' && runas_pw->pw_name && runas_pw->pw_name[0])
620         *user_runas = estrdup(runas_pw->pw_name);
621
622     /*
623      * Get current working directory.  Try as user, fall back to root.
624      */
625     set_perms(PERM_USER);
626     if (!getcwd(user_cwd, sizeof(user_cwd))) {
627         set_perms(PERM_ROOT);
628         if (!getcwd(user_cwd, sizeof(user_cwd))) {
629             warnx("cannot get working directory");
630             (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
631         }
632     } else
633         set_perms(PERM_ROOT);
634
635     /*
636      * If we were given the '-e', '-i' or '-s' options we need to redo
637      * NewArgv and NewArgc.
638      */
639     if ((sudo_mode & (MODE_SHELL | MODE_EDIT))) {
640         char **dst, **src = NewArgv;
641
642         /* Allocate an extra slot for execve() failure (ENOEXEC). */
643         NewArgv = (char **) emalloc2((++NewArgc + 2), sizeof(char *));
644         NewArgv++;
645         if (ISSET(sudo_mode, MODE_EDIT))
646             NewArgv[0] = "sudoedit";
647         else if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
648             NewArgv[0] = runas_pw->pw_shell;
649         else if (user_shell && *user_shell)
650             NewArgv[0] = user_shell;
651         else
652             errx(1, "unable to determine shell");
653
654         /* copy the args from NewArgv */
655         for (dst = NewArgv + 1; (*dst = *src) != NULL; ++src, ++dst)
656             continue;
657     }
658
659     /* Set login class if applicable. */
660     set_loginclass(sudo_user.pw);
661
662     /* Set project if applicable. */
663     set_project(runas_pw);
664
665     /* Resolve the path and return. */
666     rval = FOUND;
667     user_stat = emalloc(sizeof(struct stat));
668     if (sudo_mode & (MODE_RUN | MODE_EDIT)) {
669         if (ISSET(sudo_mode, MODE_RUN)) {
670             /* XXX - default_runas may be modified during parsing of sudoers */
671             set_perms(PERM_RUNAS);
672             rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
673             set_perms(PERM_ROOT);
674             if (rval != FOUND) {
675                 /* Failed as root, try as invoking user. */
676                 set_perms(PERM_USER);
677                 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
678                 set_perms(PERM_ROOT);
679             }
680         }
681
682         /* set user_args */
683         if (NewArgc > 1) {
684             char *to, **from;
685             size_t size, n;
686
687             /* If we didn't realloc NewArgv it is contiguous so just count. */
688             if (!(sudo_mode & (MODE_SHELL | MODE_EDIT))) {
689                 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
690                         strlen(NewArgv[NewArgc-1]) + 1;
691             } else {
692                 for (size = 0, from = NewArgv + 1; *from; from++)
693                     size += strlen(*from) + 1;
694             }
695
696             /* Alloc and build up user_args. */
697             user_args = (char *) emalloc(size);
698             for (to = user_args, from = NewArgv + 1; *from; from++) {
699                 n = strlcpy(to, *from, size - (to - user_args));
700                 if (n >= size - (to - user_args))
701                     errx(1, "internal error, init_vars() overflow");
702                 to += n;
703                 *to++ = ' ';
704             }
705             *--to = '\0';
706         }
707     }
708     if ((user_base = strrchr(user_cmnd, '/')) != NULL)
709         user_base++;
710     else
711         user_base = user_cmnd;
712
713     return(rval);
714 }
715
716 /*
717  * Command line argument parsing, can't use getopt(3).
718  */
719 static int
720 parse_args(argc, argv)
721     int argc;
722     char **argv;
723 {
724     int rval = MODE_RUN;                /* what mode is sudo to be run in? */
725     int excl = 0;                       /* exclusive arg, no others allowed */
726
727     NewArgv = argv + 1;
728     NewArgc = argc - 1;
729
730     /* First, check to see if we were invoked as "sudoedit". */
731     if (strcmp(getprogname(), "sudoedit") == 0) {
732         rval = MODE_EDIT;
733         excl = 'e';
734     } else
735         rval = MODE_RUN;
736
737     while (NewArgc > 0) {
738         if (NewArgv[0][0] == '-') {
739             if (NewArgv[0][1] != '\0' && NewArgv[0][2] != '\0') {
740                 warnx("please use single character options");
741                 usage(1);
742             }
743
744             switch (NewArgv[0][1]) {
745                 case 'p':
746                     /* Must have an associated prompt. */
747                     if (NewArgv[1] == NULL)
748                         usage(1);
749
750                     user_prompt = NewArgv[1];
751                     def_passprompt_override = TRUE;
752
753                     NewArgc--;
754                     NewArgv++;
755                     break;
756                 case 'u':
757                     /* Must have an associated runas user. */
758                     if (NewArgv[1] == NULL)
759                         usage(1);
760
761                     user_runas = &NewArgv[1];
762
763                     NewArgc--;
764                     NewArgv++;
765                     break;
766 #ifdef HAVE_BSD_AUTH_H
767                 case 'a':
768                     /* Must have an associated authentication style. */
769                     if (NewArgv[1] == NULL)
770                         usage(1);
771
772                     login_style = NewArgv[1];
773
774                     NewArgc--;
775                     NewArgv++;
776                     break;
777 #endif
778 #ifdef HAVE_LOGIN_CAP_H
779                 case 'c':
780                     /* Must have an associated login class. */
781                     if (NewArgv[1] == NULL)
782                         usage(1);
783
784                     login_class = NewArgv[1];
785                     def_use_loginclass = TRUE;
786
787                     NewArgc--;
788                     NewArgv++;
789                     break;
790 #endif
791                 case 'b':
792                     SET(rval, MODE_BACKGROUND);
793                     break;
794                 case 'e':
795                     rval = MODE_EDIT;
796                     if (excl && excl != 'e')
797                         usage_excl(1);
798                     excl = 'e';
799                     break;
800                 case 'v':
801                     rval = MODE_VALIDATE;
802                     if (excl && excl != 'v')
803                         usage_excl(1);
804                     excl = 'v';
805                     break;
806                 case 'i':
807                     SET(rval, (MODE_LOGIN_SHELL | MODE_SHELL));
808                     def_env_reset = TRUE;
809                     if (excl && excl != 'i')
810                         usage_excl(1);
811                     excl = 'i';
812                     break;
813                 case 'k':
814                     rval = MODE_INVALIDATE;
815                     if (excl && excl != 'k')
816                         usage_excl(1);
817                     excl = 'k';
818                     break;
819                 case 'K':
820                     rval = MODE_KILL;
821                     if (excl && excl != 'K')
822                         usage_excl(1);
823                     excl = 'K';
824                     break;
825                 case 'L':
826                     rval = MODE_LISTDEFS;
827                     if (excl && excl != 'L')
828                         usage_excl(1);
829                     excl = 'L';
830                     break;
831                 case 'l':
832                     rval = MODE_LIST;
833                     if (excl && excl != 'l')
834                         usage_excl(1);
835                     excl = 'l';
836                     break;
837                 case 'V':
838                     rval = MODE_VERSION;
839                     if (excl && excl != 'V')
840                         usage_excl(1);
841                     excl = 'V';
842                     break;
843                 case 'h':
844                     rval = MODE_HELP;
845                     if (excl && excl != 'h')
846                         usage_excl(1);
847                     excl = 'h';
848                     break;
849                 case 's':
850                     SET(rval, MODE_SHELL);
851                     if (excl && excl != 's')
852                         usage_excl(1);
853                     excl = 's';
854                     break;
855                 case 'H':
856                     SET(rval, MODE_RESET_HOME);
857                     break;
858                 case 'P':
859                     SET(rval, MODE_PRESERVE_GROUPS);
860                     break;
861                 case 'S':
862                     SET(tgetpass_flags, TGP_STDIN);
863                     break;
864                 case 'E':
865                     SET(rval, MODE_PRESERVE_ENV);
866                     break;
867 #ifdef HAVE_SELINUX
868                 case 'r':
869                     /* Must have an associated SELinux role. */
870                     if (NewArgv[1] == NULL)
871                         usage(1);
872
873                     user_role = NewArgv[1];
874
875                     NewArgc--;
876                     NewArgv++;
877                     break;
878                 case 't':
879                     /* Must have an associated SELinux type. */
880                     if (NewArgv[1] == NULL)
881                         usage(1);
882
883                     user_type = NewArgv[1];
884
885                     NewArgc--;
886                     NewArgv++;
887                     break;
888 #endif
889                 case '-':
890                     NewArgc--;
891                     NewArgv++;
892                     goto args_done;
893                 case '\0':
894                     warnx("'-' requires an argument");
895                     usage(1);
896                 default:
897                     warnx("illegal option `%s'", NewArgv[0]);
898                     usage(1);
899             }
900         } else if (NewArgv[0][0] != '/' && strchr(NewArgv[0], '=') != NULL) {
901             /* Could be an environment variable. */
902             struct list_member *ev;
903             ev = emalloc(sizeof(*ev));
904             ev->value = NewArgv[0];
905             ev->next = sudo_user.env_vars;
906             sudo_user.env_vars = ev;
907         } else {
908             /* Not an arg */
909             break;
910         }
911         NewArgc--;
912         NewArgv++;
913     }
914 args_done:
915
916     if (ISSET(rval, MODE_EDIT) &&
917         (ISSET(rval, MODE_PRESERVE_ENV) || sudo_user.env_vars != NULL)) {
918         if (ISSET(rval, MODE_PRESERVE_ENV))
919             warnx("the `-E' option is not valid in edit mode");
920         if (sudo_user.env_vars != NULL)
921             warnx("you may not specify environment variables in edit mode");
922         usage(1);
923     }
924
925     if (user_runas != NULL && !ISSET(rval, (MODE_EDIT|MODE_RUN))) {
926         if (excl != '\0')
927             warnx("the `-u' and '-%c' options may not be used together", excl);
928         usage(1);
929     }
930     if ((NewArgc == 0 && (rval & MODE_EDIT)) ||
931         (NewArgc > 0 && !(rval & (MODE_RUN | MODE_EDIT))))
932         usage(1);
933     if (NewArgc == 0 && rval == MODE_RUN)
934         SET(rval, (MODE_IMPLIED_SHELL | MODE_SHELL));
935
936     return(rval);
937 }
938
939 /*
940  * Sanity check sudoers mode/owner/type.
941  * Leaves a file pointer to the sudoers file open in ``fp''.
942  */
943 static void
944 check_sudoers()
945 {
946     struct stat statbuf;
947     int rootstat, i;
948
949     /*
950      * Fix the mode and group on sudoers file from old default.
951      * Only works if file system is readable/writable by root.
952      */
953     if ((rootstat = stat_sudoers(_PATH_SUDOERS, &statbuf)) == 0 &&
954         SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
955         (statbuf.st_mode & 0007777) == 0400) {
956
957         if (chmod(_PATH_SUDOERS, SUDOERS_MODE) == 0) {
958             warnx("fixed mode on %s", _PATH_SUDOERS);
959             SET(statbuf.st_mode, SUDOERS_MODE);
960             if (statbuf.st_gid != SUDOERS_GID) {
961                 if (!chown(_PATH_SUDOERS,(uid_t) -1,SUDOERS_GID)) {
962                     warnx("set group on %s", _PATH_SUDOERS);
963                     statbuf.st_gid = SUDOERS_GID;
964                 } else
965                     warn("unable to set group on %s", _PATH_SUDOERS);
966             }
967         } else
968             warn("unable to fix mode on %s", _PATH_SUDOERS);
969     }
970
971     /*
972      * Sanity checks on sudoers file.  Must be done as sudoers
973      * file owner.  We already did a stat as root, so use that
974      * data if we can't stat as sudoers file owner.
975      */
976     set_perms(PERM_SUDOERS);
977
978     if (rootstat != 0 && stat_sudoers(_PATH_SUDOERS, &statbuf) != 0)
979         log_error(USE_ERRNO, "can't stat %s", _PATH_SUDOERS);
980     else if (!S_ISREG(statbuf.st_mode))
981         log_error(0, "%s is not a regular file", _PATH_SUDOERS);
982     else if (statbuf.st_size == 0)
983         log_error(0, "%s is zero length", _PATH_SUDOERS);
984     else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
985         log_error(0, "%s is mode 0%o, should be 0%o", _PATH_SUDOERS,
986             (unsigned int) (statbuf.st_mode & 07777),
987             (unsigned int) SUDOERS_MODE);
988     else if (statbuf.st_uid != SUDOERS_UID)
989         log_error(0, "%s is owned by uid %lu, should be %lu", _PATH_SUDOERS,
990             (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
991     else if (statbuf.st_gid != SUDOERS_GID)
992         log_error(0, "%s is owned by gid %lu, should be %lu", _PATH_SUDOERS,
993             (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
994     else {
995         /* Solaris sometimes returns EAGAIN so try 10 times */
996         for (i = 0; i < 10 ; i++) {
997             errno = 0;
998             if ((sudoers_fp = fopen(_PATH_SUDOERS, "r")) == NULL ||
999                 fgetc(sudoers_fp) == EOF) {
1000                 if (sudoers_fp != NULL)
1001                     fclose(sudoers_fp);
1002                 sudoers_fp = NULL;
1003                 if (errno != EAGAIN && errno != EWOULDBLOCK)
1004                     break;
1005             } else
1006                 break;
1007             sleep(1);
1008         }
1009         if (sudoers_fp == NULL)
1010             log_error(USE_ERRNO, "can't open %s", _PATH_SUDOERS);
1011     }
1012
1013     set_perms(PERM_ROOT);               /* change back to root */
1014 }
1015
1016 /*
1017  * Close all open files (except std*) and turn off core dumps.
1018  */
1019 static void
1020 initial_setup()
1021 {
1022     int miss[3], devnull = -1;
1023 #if defined(__linux__) || (defined(RLIMIT_CORE) && !defined(SUDO_DEVEL))
1024     struct rlimit rl;
1025 #endif
1026
1027 #if defined(__linux__)
1028     /*
1029      * Unlimit the number of processes since Linux's setuid() will
1030      * apply resource limits when changing uid and return EAGAIN if
1031      * nproc would be violated by the uid switch.
1032      */
1033     rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
1034     if (setrlimit(RLIMIT_NPROC, &rl)) {
1035         if (getrlimit(RLIMIT_NPROC, &rl) == 0) {
1036             rl.rlim_cur = rl.rlim_max;
1037             (void)setrlimit(RLIMIT_NPROC, &rl);
1038         }
1039     }
1040 #endif /* __linux__ */
1041 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
1042     /*
1043      * Turn off core dumps.
1044      */
1045     (void) getrlimit(RLIMIT_CORE, &corelimit);
1046     memcpy(&rl, &corelimit, sizeof(struct rlimit));
1047     rl.rlim_cur = 0;
1048     (void) setrlimit(RLIMIT_CORE, &rl);
1049 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1050
1051     /*
1052      * stdin, stdout and stderr must be open; set them to /dev/null
1053      * if they are closed and close all other fds.
1054      */
1055     miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1056     miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1057     miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1058     if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1059         if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
1060             if (miss[STDIN_FILENO])
1061                 (void) dup2(devnull, STDIN_FILENO);
1062             if (miss[STDOUT_FILENO])
1063                 (void) dup2(devnull, STDOUT_FILENO);
1064             if (miss[STDERR_FILENO])
1065                 (void) dup2(devnull, STDERR_FILENO);
1066         }
1067     }
1068     closefrom(STDERR_FILENO + 1);
1069 }
1070
1071 #ifdef HAVE_LOGIN_CAP_H
1072 static void
1073 set_loginclass(pw)
1074     struct passwd *pw;
1075 {
1076     int errflags;
1077
1078     /*
1079      * Don't make it a fatal error if the user didn't specify the login
1080      * class themselves.  We do this because if login.conf gets
1081      * corrupted we want the admin to be able to use sudo to fix it.
1082      */
1083     if (login_class)
1084         errflags = NO_MAIL|MSG_ONLY;
1085     else
1086         errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1087
1088     if (login_class && strcmp(login_class, "-") != 0) {
1089         if (strcmp(*user_runas, "root") != 0 && user_uid != 0)
1090             errx(1, "only root can use -c %s", login_class);
1091     } else {
1092         login_class = pw->pw_class;
1093         if (!login_class || !*login_class)
1094             login_class =
1095                 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1096     }
1097
1098     lc = login_getclass(login_class);
1099     if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1100         log_error(errflags, "unknown login class: %s", login_class);
1101         if (!lc)
1102             lc = login_getclass(NULL);  /* needed for login_getstyle() later */
1103     }
1104 }
1105 #else
1106 static void
1107 set_loginclass(pw)
1108     struct passwd *pw;
1109 {
1110 }
1111 #endif /* HAVE_LOGIN_CAP_H */
1112
1113 #ifdef HAVE_PROJECT_H
1114 static void
1115 set_project(pw)
1116     struct passwd *pw;
1117 {
1118     int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1119     int errval;
1120     struct project proj;
1121     struct project *resultp = '\0';
1122     char buf[1024];
1123
1124     /*
1125      * Collect the default project for the user and settaskid
1126      */
1127     setprojent();
1128     if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1129         errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1130         if (errval != 0) {
1131             switch(errval) {
1132             case SETPROJ_ERR_TASK:
1133                 if (errno == EAGAIN)
1134                     log_error(errflags, "resource control limit has been reached");
1135                 else if (errno == ESRCH)
1136                     log_error(errflags, "user \"%s\" is not a member of "
1137                         "project \"%s\"", pw->pw_name, resultp->pj_name);
1138                 else if (errno == EACCES)
1139                     log_error(errflags, "the invoking task is final");
1140                 else
1141                     log_error(errflags, "could not join project \"%s\"",
1142                         resultp->pj_name);
1143                 break;
1144             case SETPROJ_ERR_POOL:
1145                 if (errno == EACCES)
1146                     log_error(errflags, "no resource pool accepting "
1147                             "default bindings exists for project \"%s\"",
1148                             resultp->pj_name);
1149                 else if (errno == ESRCH)
1150                     log_error(errflags, "specified resource pool does "
1151                             "not exist for project \"%s\"", resultp->pj_name);
1152                 else
1153                     log_error(errflags, "could not bind to default "
1154                             "resource pool for project \"%s\"", resultp->pj_name);
1155                 break;
1156             default:
1157                 if (errval <= 0) {
1158                     log_error(errflags, "setproject failed for project \"%s\"",
1159                         resultp->pj_name);
1160                 } else {
1161                     log_error(errflags, "warning, resource control assignment "
1162                         "failed for project \"%s\"", resultp->pj_name);
1163                 }
1164             }
1165         }
1166     } else {
1167         log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1168     }
1169     endprojent();
1170 }
1171 #else
1172 static void
1173 set_project(pw)
1174     struct passwd *pw;
1175 {
1176 }
1177 #endif /* HAVE_PROJECT_H */
1178
1179 /*
1180  * Look up the fully qualified domain name and set user_host and user_shost.
1181  */
1182 void
1183 set_fqdn()
1184 {
1185 #ifdef HAVE_GETADDRINFO
1186     struct addrinfo *res0, hint;
1187 #else
1188     struct hostent *hp;
1189 #endif
1190     char *p;
1191
1192 #ifdef HAVE_GETADDRINFO
1193     memset(&hint, 0, sizeof(hint));
1194     hint.ai_family = PF_UNSPEC;
1195     hint.ai_flags = AI_CANONNAME;
1196     if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1197 #else
1198     if (!(hp = gethostbyname(user_host))) {
1199 #endif
1200         log_error(MSG_ONLY|NO_EXIT,
1201             "unable to resolve host %s", user_host);
1202     } else {
1203         if (user_shost != user_host)
1204             efree(user_shost);
1205         efree(user_host);
1206 #ifdef HAVE_GETADDRINFO
1207         user_host = estrdup(res0->ai_canonname);
1208         freeaddrinfo(res0);
1209 #else
1210         user_host = estrdup(hp->h_name);
1211 #endif
1212     }
1213     if ((p = strchr(user_host, '.'))) {
1214         *p = '\0';
1215         user_shost = estrdup(user_host);
1216         *p = '.';
1217     } else {
1218         user_shost = user_host;
1219     }
1220 }
1221
1222 /*
1223  * Get passwd entry for the user we are going to run commands as.
1224  * By default, this is "root".  Updates runas_pw as a side effect.
1225  */
1226 int
1227 set_runaspw(user)
1228     char *user;
1229 {
1230     if (runas_pw != NULL) {
1231         if (user_runas != &def_runas_default)
1232             return(TRUE);               /* don't override -u option */
1233         efree(runas_pw);
1234     }
1235     if (*user == '#') {
1236         runas_pw = sudo_getpwuid(atoi(user + 1));
1237         if (runas_pw == NULL) {
1238             runas_pw = emalloc(sizeof(struct passwd));
1239             (void) memset((VOID *)runas_pw, 0, sizeof(struct passwd));
1240             runas_pw->pw_uid = atoi(user + 1);
1241         }
1242     } else {
1243         runas_pw = sudo_getpwnam(user);
1244         if (runas_pw == NULL)
1245             log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %s!", user);
1246     }
1247     return(TRUE);
1248 }
1249
1250 /*
1251  * Get passwd entry for the user we are going to authenticate as.
1252  * By default, this is the user invoking sudo.  In the most common
1253  * case, this matches sudo_user.pw or runas_pw.
1254  */
1255 static struct passwd *
1256 get_authpw()
1257 {
1258     struct passwd *pw;
1259
1260     if (def_rootpw) {
1261         if (runas_pw->pw_uid == 0)
1262             pw = runas_pw;
1263         else if ((pw = sudo_getpwuid(0)) == NULL)
1264             log_error(0, "uid 0 does not exist in the passwd file!");
1265     } else if (def_runaspw) {
1266         if (strcmp(def_runas_default, *user_runas) == 0)
1267             pw = runas_pw;
1268         else if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1269             log_error(0, "user %s does not exist in the passwd file!",
1270                 def_runas_default);
1271     } else if (def_targetpw) {
1272         if (runas_pw->pw_name == NULL)
1273             log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %lu!",
1274                 (unsigned long) runas_pw->pw_uid);
1275         pw = runas_pw;
1276     } else
1277         pw = sudo_user.pw;
1278
1279     return(pw);
1280 }
1281
1282 /*
1283  * Tell which options are mutually exclusive and exit.
1284  */
1285 static void
1286 usage_excl(exit_val)
1287     int exit_val;
1288 {
1289     warnx("Only one of the -e, -h, i, -k, -K, -l, -s, -v or -V options may be used");
1290     usage(exit_val);
1291 }
1292
1293 /*
1294  * Give usage message and exit.
1295  */
1296 static void
1297 usage(exit_val)
1298     int exit_val;
1299 {
1300     char **p, **uvec[4];
1301     int i, linelen, linemax, ulen, plen;
1302     static char *uvec1[] = {
1303         " -h |",
1304         " -K |",
1305         " -k |",
1306         " -L |",
1307         " -l |",
1308         " -V |",
1309         " -v",
1310         NULL
1311     };
1312     static char *uvec2[] = {
1313         " [-bEHPS]",
1314 #ifdef HAVE_BSD_AUTH_H
1315         " [-a auth_type]",
1316 #endif
1317 #ifdef HAVE_LOGIN_CAP_H
1318         " [-c class|-]",
1319 #endif
1320 #ifdef HAVE_SELINUX
1321         " [-r role]",
1322 #endif
1323         " [-p prompt]",
1324 #ifdef HAVE_SELINUX
1325         " [-t type]",
1326 #endif
1327         " [-u username|#uid]",
1328         " [VAR=value]",
1329         " {-i | -s | <command>}",
1330         NULL
1331     };
1332     static char *uvec3[] = {
1333         " -e",
1334         " [-S]",
1335 #ifdef HAVE_BSD_AUTH_H
1336         " [-a auth_type]",
1337 #endif
1338 #ifdef HAVE_LOGIN_CAP_H
1339         " [-c class|-]",
1340 #endif
1341         " [-p prompt]",
1342         " [-u username|#uid]",
1343         " file ...",
1344         NULL
1345     };
1346
1347     /*
1348      * Use usage vectors appropriate to the progname.
1349      */
1350     if (strcmp(getprogname(), "sudoedit") == 0) {
1351         uvec[0] = uvec3 + 1;
1352         uvec[1] = NULL;
1353     } else {
1354         uvec[0] = uvec1;
1355         uvec[1] = uvec2;
1356         uvec[2] = uvec3;
1357         uvec[3] = NULL;
1358     }
1359
1360     /*
1361      * Print usage and wrap lines as needed.
1362      * Assumes an 80-character wide terminal, which is kind of bogus...
1363      */
1364     ulen = (int)strlen(getprogname()) + 7;
1365     linemax = 80;
1366     for (i = 0; uvec[i] != NULL; i++) {
1367         printf("usage: %s", getprogname());
1368         linelen = linemax - ulen;
1369         for (p = uvec[i]; *p != NULL; p++) {
1370             plen = (int)strlen(*p);
1371             if (linelen >= plen || linelen == linemax - ulen) {
1372                 fputs(*p, stdout);
1373                 linelen -= plen;
1374             } else {
1375                 p--;
1376                 linelen = linemax - ulen;
1377                 printf("\n%*s", ulen, "");
1378             }
1379         }
1380         putchar('\n');
1381     }
1382     exit(exit_val);
1383 }