adduser: prefer to call addgroup --gid, not non-std addgroup -g
[oweals/busybox.git] / loginutils / adduser.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * adduser - add users to /etc/passwd and /etc/shadow
4  *
5  * Copyright (C) 1999 by Lineo, inc. and John Beppu
6  * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  */
10
11 //usage:#define adduser_trivial_usage
12 //usage:       "[OPTIONS] USER"
13 //usage:#define adduser_full_usage "\n\n"
14 //usage:       "Add a user\n"
15 //usage:     "\nOptions:"
16 //usage:     "\n        -h DIR          Home directory"
17 //usage:     "\n        -g GECOS        GECOS field"
18 //usage:     "\n        -s SHELL        Login shell"
19 //usage:     "\n        -G GRP          Add user to existing group"
20 //usage:     "\n        -S              Create a system user"
21 //usage:     "\n        -D              Don't assign a password"
22 //usage:     "\n        -H              Don't create home directory"
23 //usage:     "\n        -u UID          User id"
24
25 #include "libbb.h"
26
27 #if CONFIG_LAST_SYSTEM_ID < CONFIG_FIRST_SYSTEM_ID
28 #error Bad LAST_SYSTEM_ID or FIRST_SYSTEM_ID in .config
29 #endif
30
31 /* #define OPT_HOME           (1 << 0) */ /* unused */
32 /* #define OPT_GECOS          (1 << 1) */ /* unused */
33 #define OPT_SHELL          (1 << 2)
34 #define OPT_GID            (1 << 3)
35 #define OPT_DONT_SET_PASS  (1 << 4)
36 #define OPT_SYSTEM_ACCOUNT (1 << 5)
37 #define OPT_DONT_MAKE_HOME (1 << 6)
38 #define OPT_UID            (1 << 7)
39
40 /* We assume UID_T_MAX == INT_MAX */
41 /* remix */
42 /* recoded such that the uid may be passed in *p */
43 static void passwd_study(struct passwd *p)
44 {
45         int max = UINT_MAX;
46
47         if (getpwnam(p->pw_name)) {
48                 bb_error_msg_and_die("%s '%s' in use", "user", p->pw_name);
49                 /* this format string is reused in adduser and addgroup */
50         }
51
52         if (!(option_mask32 & OPT_UID)) {
53                 if (option_mask32 & OPT_SYSTEM_ACCOUNT) {
54                         p->pw_uid = CONFIG_FIRST_SYSTEM_ID;
55                         max = CONFIG_LAST_SYSTEM_ID;
56                 } else {
57                         p->pw_uid = CONFIG_LAST_SYSTEM_ID + 1;
58                         max = 64999;
59                 }
60         }
61         /* check for a free uid (and maybe gid) */
62         while (getpwuid(p->pw_uid) || (p->pw_gid == (gid_t)-1 && getgrgid(p->pw_uid))) {
63                 if (option_mask32 & OPT_UID) {
64                         /* -u N, cannot pick uid other than N: error */
65                         bb_error_msg_and_die("%s '%s' in use", "uid", itoa(p->pw_uid));
66                         /* this format string is reused in adduser and addgroup */
67                 }
68                 if (p->pw_uid == max) {
69                         bb_error_msg_and_die("no %cids left", 'u');
70                         /* this format string is reused in adduser and addgroup */
71                 }
72                 p->pw_uid++;
73         }
74
75         if (p->pw_gid == (gid_t)-1) {
76                 p->pw_gid = p->pw_uid; /* new gid = uid */
77                 if (getgrnam(p->pw_name)) {
78                         bb_error_msg_and_die("%s '%s' in use", "group", p->pw_name);
79                         /* this format string is reused in adduser and addgroup */
80                 }
81         }
82 }
83
84 static void addgroup_wrapper(struct passwd *p, const char *group_name)
85 {
86         char *argv[6];
87
88         argv[0] = (char*)"addgroup";
89         if (group_name) {
90                 /* Add user to existing group */
91                 argv[1] = (char*)"--";
92                 argv[2] = p->pw_name;
93                 argv[3] = (char*)group_name;
94                 argv[4] = NULL;
95         } else {
96                 /* Add user to his own group with the first free gid
97                  * found in passwd_study.
98                  * We try to use --gid, not -g, because "standard" addgroup
99                  * has no such short option, it has only long --gid.
100                  */
101 #if ENABLE_FEATURE_ADDGROUP_LONG_OPTIONS
102                 argv[1] = (char*)"--gid";
103 #else
104                 argv[1] = (char*)"-g";
105 #endif
106                 argv[2] = utoa(p->pw_gid);
107                 argv[3] = (char*)"--";
108                 argv[4] = p->pw_name;
109                 argv[5] = NULL;
110         }
111
112         spawn_and_wait(argv);
113 }
114
115 static void passwd_wrapper(const char *login_name) NORETURN;
116
117 static void passwd_wrapper(const char *login_name)
118 {
119         BB_EXECLP("passwd", "passwd", "--", login_name, NULL);
120         bb_error_msg_and_die("can't execute passwd, you must set password manually");
121 }
122
123 #if ENABLE_FEATURE_ADDUSER_LONG_OPTIONS
124 static const char adduser_longopts[] ALIGN1 =
125                 "home\0"                Required_argument "h"
126                 "gecos\0"               Required_argument "g"
127                 "shell\0"               Required_argument "s"
128                 "ingroup\0"             Required_argument "G"
129                 "disabled-password\0"   No_argument       "D"
130                 "empty-password\0"      No_argument       "D"
131                 "system\0"              No_argument       "S"
132                 "no-create-home\0"      No_argument       "H"
133                 "uid\0"                 Required_argument "u"
134                 ;
135 #endif
136
137 /*
138  * adduser will take a login_name as its first parameter.
139  * home, shell, gecos:
140  * can be customized via command-line parameters.
141  */
142 int adduser_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
143 int adduser_main(int argc UNUSED_PARAM, char **argv)
144 {
145         struct passwd pw;
146         const char *usegroup = NULL;
147         char *p;
148         unsigned opts;
149
150 #if ENABLE_FEATURE_ADDUSER_LONG_OPTIONS
151         applet_long_options = adduser_longopts;
152 #endif
153
154         /* got root? */
155         if (geteuid()) {
156                 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
157         }
158
159         pw.pw_gecos = (char *)"Linux User,,,";
160         /* We assume that newly created users "inherit" root's shell setting */
161         pw.pw_shell = (char *)get_shell_name();
162         pw.pw_dir = NULL;
163
164         /* exactly one non-option arg */
165         /* disable interactive passwd for system accounts */
166         opt_complementary = "=1:SD:u+";
167         if (sizeof(pw.pw_uid) == sizeof(int)) {
168                 opts = getopt32(argv, "h:g:s:G:DSHu:", &pw.pw_dir, &pw.pw_gecos, &pw.pw_shell, &usegroup, &pw.pw_uid);
169         } else {
170                 unsigned uid;
171                 opts = getopt32(argv, "h:g:s:G:DSHu:", &pw.pw_dir, &pw.pw_gecos, &pw.pw_shell, &usegroup, &uid);
172                 if (opts & OPT_UID) {
173                         pw.pw_uid = uid;
174                 }
175         }
176         argv += optind;
177
178         /* fill in the passwd struct */
179         pw.pw_name = argv[0];
180         die_if_bad_username(pw.pw_name);
181         if (!pw.pw_dir) {
182                 /* create string for $HOME if not specified already */
183                 pw.pw_dir = xasprintf("/home/%s", argv[0]);
184         }
185         pw.pw_passwd = (char *)"x";
186         if (opts & OPT_SYSTEM_ACCOUNT) {
187                 if (!usegroup) {
188                         usegroup = "nogroup";
189                 }
190                 if (!(opts & OPT_SHELL)) {
191                         pw.pw_shell = (char *) "/bin/false";
192                 }
193         }
194         pw.pw_gid = usegroup ? xgroup2gid(usegroup) : -1; /* exits on failure */
195
196         /* make sure everything is kosher and setup uid && maybe gid */
197         passwd_study(&pw);
198
199         p = xasprintf("x:%u:%u:%s:%s:%s",
200                         (unsigned) pw.pw_uid, (unsigned) pw.pw_gid,
201                         pw.pw_gecos, pw.pw_dir, pw.pw_shell);
202         if (update_passwd(bb_path_passwd_file, pw.pw_name, p, NULL) < 0) {
203                 return EXIT_FAILURE;
204         }
205         if (ENABLE_FEATURE_CLEAN_UP)
206                 free(p);
207
208 #if ENABLE_FEATURE_SHADOWPASSWDS
209         /* /etc/shadow fields:
210          * 1. username
211          * 2. encrypted password
212          * 3. last password change (unix date (unix time/24*60*60))
213          * 4. minimum days required between password changes
214          * 5. maximum days password is valid
215          * 6. days before password is to expire that user is warned
216          * 7. days after password expires that account is disabled
217          * 8. unix date when login expires (i.e. when it may no longer be used)
218          */
219         /* fields:     2 3  4 5     6 78 */
220         p = xasprintf("!:%u:0:99999:7:::", (unsigned)(time(NULL)) / (24*60*60));
221         /* ignore errors: if file is missing we suppose admin doesn't want it */
222         update_passwd(bb_path_shadow_file, pw.pw_name, p, NULL);
223         if (ENABLE_FEATURE_CLEAN_UP)
224                 free(p);
225 #endif
226
227         /* add to group */
228         addgroup_wrapper(&pw, usegroup);
229
230         /* clear the umask for this process so it doesn't
231          * screw up the permissions on the mkdir and chown. */
232         umask(0);
233         if (!(opts & OPT_DONT_MAKE_HOME)) {
234                 /* set the owner and group so it is owned by the new user,
235                  * then fix up the permissions to 2755. Can't do it before
236                  * since chown will clear the setgid bit */
237                 int mkdir_err = mkdir(pw.pw_dir, 0755);
238                 if (mkdir_err == 0) {
239                         /* New home. Copy /etc/skel to it */
240                         const char *args[] = {
241                                 "chown",
242                                 "-R",
243                                 xasprintf("%u:%u", (int)pw.pw_uid, (int)pw.pw_gid),
244                                 pw.pw_dir,
245                                 NULL
246                         };
247                         /* Be silent on any errors (like: no /etc/skel) */
248                         logmode = LOGMODE_NONE;
249                         copy_file("/etc/skel", pw.pw_dir, FILEUTILS_RECUR);
250                         logmode = LOGMODE_STDIO;
251                         chown_main(4, (char**)args);
252                 }
253                 if ((mkdir_err != 0 && errno != EEXIST)
254                  || chown(pw.pw_dir, pw.pw_uid, pw.pw_gid) != 0
255                  || chmod(pw.pw_dir, 02755) != 0 /* set setgid bit on homedir */
256                 ) {
257                         bb_simple_perror_msg(pw.pw_dir);
258                 }
259         }
260
261         if (!(opts & OPT_DONT_SET_PASS)) {
262                 /* interactively set passwd */
263                 passwd_wrapper(pw.pw_name);
264         }
265
266         return EXIT_SUCCESS;
267 }