1 /* setuidgid - run a command with the UID and GID of a specified user
2 Copyright (C) 2003 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Jim Meyering */
22 #include <sys/types.h>
29 #include "long-options.h"
32 #define PROGRAM_NAME "setuidgid"
34 /* I wrote this program from scratch, based on the description of
35 D.J. Bernstein's program: http://cr.yp.to/daemontools/setuidgid.html. */
36 #define WRITTEN_BY _("Written by Jim Meyering.")
38 #define FAIL_STATUS 111
46 fprintf (stderr, _("Try `%s --help' for more information.\n"),
51 Usage: %s USERNAME COMMAND [ARGUMENT]...\n\
54 program_name, program_name);
57 Drop any supplemental groups, assume the user-ID and group-ID of\n\
58 the specified USERNAME, and run COMMAND with any specified ARGUMENTs.\n\
59 Exit with status 111 if unable to assume the required UID and GID.\n\
60 Otherwise, exit with the exit status of COMMAND.\n\
61 This program is useful only when run by root (UID=0).\n\
64 fputs (HELP_OPTION_DESCRIPTION, stdout);
65 fputs (VERSION_OPTION_DESCRIPTION, stdout);
66 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
72 main (int argc, char **argv)
77 initialize_main (&argc, &argv);
78 program_name = argv[0];
79 setlocale (LC_ALL, "");
80 bindtextdomain (PACKAGE, LOCALEDIR);
83 atexit (close_stdout);
85 parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
88 /* The above handles --help and --version.
89 Since there is no other invocation of getopt, handle `--' here. */
90 if (argc > 1 && STREQ (argv[1], "--"))
98 error (0, 0, _("too few arguments"));
103 pwd = getpwnam (user_id);
106 error (0, errno, _("unknown user-ID: %s"), quote (user_id));
110 if (setgroups (1, &pwd->pw_gid))
112 error (0, errno, _("cannot set supplemental group"));
116 if (setgid (pwd->pw_gid))
118 error (0, errno, _("cannot set group-ID to %ld"), (long) pwd->pw_gid);
122 if (setuid (pwd->pw_uid))
124 error (0, errno, _("cannot set user-ID to %ld"), (long) pwd->pw_uid);
129 char **cmd = argv + 2;
132 error (0, errno, _("cannot run command %s"), quote (*cmd));