xref: /freebsd/usr.sbin/pw/pw.c (revision 4cf49a43559ed9fdad601bdcccd2c55963008675)
1 /*-
2  * Copyright (C) 1996
3  *	David L. Nugent.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #ifndef lint
28 static const char rcsid[] =
29   "$FreeBSD$";
30 #endif /* not lint */
31 
32 #include <err.h>
33 #include <fcntl.h>
34 #include <paths.h>
35 #include <sys/wait.h>
36 #include "pw.h"
37 
38 const char     *Modes[] = {"add", "del", "mod", "show", "next", NULL};
39 const char     *Which[] = {"user", "group", NULL};
40 static const char *Combo1[] = {
41   "useradd", "userdel", "usermod", "usershow", "usernext",
42   "groupadd", "groupdel", "groupmod", "groupshow", "groupnext",
43   NULL};
44 static const char *Combo2[] = {
45   "adduser", "deluser", "moduser", "showuser", "nextuser",
46   "addgroup", "delgroup", "modgroup", "showgroup", "nextgroup",
47 NULL};
48 
49 struct pwf PWF =
50 {
51 	0,
52 	setpwent,
53 	endpwent,
54 	getpwent,
55 	getpwuid,
56 	getpwnam,
57 	pwdb,
58 	setgrent,
59 	endgrent,
60 	getgrent,
61 	getgrgid,
62 	getgrnam,
63 	grdb
64 
65 };
66 struct pwf VPWF =
67 {
68 	1,
69 	vsetpwent,
70 	vendpwent,
71 	vgetpwent,
72 	vgetpwuid,
73 	vgetpwnam,
74 	vpwdb,
75 	vsetgrent,
76 	vendgrent,
77 	vgetgrent,
78 	vgetgrgid,
79 	vgetgrnam,
80 	vgrdb
81 };
82 
83 static struct cargs arglist;
84 
85 static int      getindex(const char *words[], const char *word);
86 static void     cmdhelp(int mode, int which);
87 
88 
89 int
90 main(int argc, char *argv[])
91 {
92 	int             ch;
93 	int             mode = -1;
94 	int             which = -1;
95 	char		*config = NULL;
96 	struct userconf *cnf;
97 
98 	static const char *opts[W_NUM][M_NUM] =
99 	{
100 		{ /* user */
101 			"V:C:qn:u:c:d:e:p:g:G:mk:s:oL:i:w:h:Db:NPy:Y",
102 			"V:C:qn:u:rY",
103 			"V:C:qn:u:c:d:e:p:g:G:ml:k:s:w:L:h:FNPY",
104 			"V:C:qn:u:FPa7",
105 			"V:C:q"
106 		},
107 		{ /* grp  */
108 			"V:C:qn:g:h:M:pNPY",
109 			"V:C:qn:g:Y",
110 			"V:C:qn:g:l:h:FM:m:NPY",
111 			"V:C:qn:g:FPa",
112 			"V:C:q"
113 		 }
114 	};
115 
116 	static int      (*funcs[W_NUM]) (struct userconf * _cnf, int _mode, struct cargs * _args) =
117 	{			/* Request handlers */
118 		pw_user,
119 		pw_group
120 	};
121 
122 	umask(0);		/* We wish to handle this manually */
123 	LIST_INIT(&arglist);
124 
125 	/*
126 	 * Break off the first couple of words to determine what exactly
127 	 * we're being asked to do
128 	 */
129 	while (argc > 1) {
130 		int             tmp;
131 
132 		if (*argv[1] == '-') {
133 			/*
134 			 * Special case, allow pw -V<dir> <operation> [args] for scripts etc.
135 			 */
136 			if (argv[1][1] == 'V') {
137 				optarg = &argv[1][2];
138 				if (*optarg == '\0') {
139 					optarg = argv[2];
140 					++argv;
141 					--argc;
142 				}
143 				addarg(&arglist, 'V', optarg);
144 			} else
145 				break;
146 		}
147 		else if ((tmp = getindex(Modes, argv[1])) != -1)
148 			mode = tmp;
149 		else if ((tmp = getindex(Which, argv[1])) != -1)
150 			which = tmp;
151 		else if ((tmp = getindex(Combo1, argv[1])) != -1 || (tmp = getindex(Combo2, argv[1])) != -1) {
152 			which = tmp / M_NUM;
153 			mode = tmp % M_NUM;
154 		} else if (strcmp(argv[1], "help") == 0)
155 			cmdhelp(mode, which);
156 		else if (which != -1 && mode != -1)
157 			addarg(&arglist, 'n', argv[1]);
158 		else
159 			errx(EX_USAGE, "unknown keyword `%s'", argv[1]);
160 		++argv;
161 		--argc;
162 	}
163 
164 	/*
165 	 * Bail out unless the user is specific!
166 	 */
167 	if (mode == -1 || which == -1)
168 		cmdhelp(mode, which);
169 
170 	/*
171 	 * We know which mode we're in and what we're about to do, so now
172 	 * let's dispatch the remaining command line args in a genric way.
173 	 */
174 	optarg = NULL;
175 
176 	while ((ch = getopt(argc, argv, opts[which][mode])) != -1) {
177 		if (ch == '?')
178 			errx(EX_USAGE, NULL);
179 		else
180 			addarg(&arglist, ch, optarg);
181 		optarg = NULL;
182 	}
183 
184 	/*
185 	 * Must be root to attempt an update
186 	 */
187 	if (geteuid() != 0 && mode != M_PRINT && mode != M_NEXT && getarg(&arglist, 'N')==NULL)
188 		errx(EX_NOPERM, "you must be root to run this program");
189 
190 	/*
191 	 * We should immediately look for the -q 'quiet' switch so that we
192 	 * don't bother with extraneous errors
193 	 */
194 	if (getarg(&arglist, 'q') != NULL)
195 		freopen("/dev/null", "w", stderr);
196 
197 	/*
198 	 * Set our base working path if not overridden
199 	 */
200 
201 	config = getarg(&arglist, 'C') ? getarg(&arglist, 'C')->val : NULL;
202 
203 	if (getarg(&arglist, 'V') != NULL) {
204 		char * etcpath = getarg(&arglist, 'V')->val;
205 		if (*etcpath) {
206 			if (config == NULL) {	/* Only override config location if -C not specified */
207 				config = malloc(MAXPATHLEN);
208 				snprintf(config, MAXPATHLEN, "%s/pw.conf", etcpath);
209 			}
210 			memcpy(&PWF, &VPWF, sizeof PWF);
211 			setpwdir(etcpath);
212 			setgrdir(etcpath);
213 		}
214 	}
215 
216 	/*
217 	 * Now, let's do the common initialisation
218 	 */
219 	cnf = read_userconfig(config);
220 
221 	ch = funcs[which] (cnf, mode, &arglist);
222 
223 	/*
224 	 * If everything went ok, and we've been asked to update
225 	 * the NIS maps, then do it now
226 	 */
227 	if (ch == EXIT_SUCCESS && getarg(&arglist, 'Y') != NULL) {
228 		pid_t	pid;
229 
230 		fflush(NULL);
231 		if (chdir(_PATH_YP) == -1)
232 			warn("chdir(" _PATH_YP ")");
233 		else if ((pid = fork()) == -1)
234 			warn("fork()");
235 		else if (pid == 0) {
236 			/* Is make anywhere else? */
237 			execlp("/usr/bin/make", "make", NULL);
238 			_exit(1);
239 		} else {
240 			int   i;
241 			waitpid(pid, &i, 0);
242 			if ((i = WEXITSTATUS(i)) != 0)
243 				errx(ch, "make exited with status %d", i);
244 			else
245 				pw_log(cnf, mode, which, "NIS maps updated");
246 		}
247 	}
248 	return ch;
249 }
250 
251 
252 static int
253 getindex(const char *words[], const char *word)
254 {
255 	int             i = 0;
256 
257 	while (words[i]) {
258 		if (strcmp(words[i], word) == 0)
259 			return i;
260 		i++;
261 	}
262 	return -1;
263 }
264 
265 
266 /*
267  * This is probably an overkill for a cmdline help system, but it reflects
268  * the complexity of the command line.
269  */
270 
271 static void
272 cmdhelp(int mode, int which)
273 {
274 	if (which == -1)
275 		fprintf(stderr, "usage: pw [user|group] [add|del|mod|show|next] [ help | switches/values ]\n");
276 	else if (mode == -1)
277 		fprintf(stderr, "usage: pw %s [add|del|mod|show|next] [ help | switches/values ]\n", Which[which]);
278 	else {
279 
280 		/*
281 		 * We need to give mode specific help
282 		 */
283 		static const char *help[W_NUM][M_NUM] =
284 		{
285 			{
286 				"usage: pw useradd [name] [switches]\n"
287 				"\t-V etcdir      alternate /etc location\n"
288 				"\t-C config      configuration file\n"
289 				"\t-q             quiet operation\n"
290 				"  Adding users:\n"
291 				"\t-n name        login name\n"
292 				"\t-u uid         user id\n"
293 				"\t-c comment     user name/comment\n"
294 				"\t-d directory   home directory\n"
295 				"\t-e date        account expiry date\n"
296 				"\t-p date        password expiry date\n"
297 				"\t-g grp         initial group\n"
298 				"\t-G grp1,grp2   additional groups\n"
299 				"\t-m [ -k dir ]  create and set up home\n"
300 				"\t-s shell       name of login shell\n"
301 				"\t-o             duplicate uid ok\n"
302 				"\t-L class       user class\n"
303 				"\t-h fd          read password on fd\n"
304 				"\t-Y             update NIS maps\n"
305 				"\t-N             no update\n"
306 				"  Setting defaults:\n"
307 				"\t-V etcdir      alternate /etc location\n"
308 			        "\t-D             set user defaults\n"
309 				"\t-b dir         default home root dir\n"
310 				"\t-e period      default expiry period\n"
311 				"\t-p period      default password change period\n"
312 				"\t-g group       default group\n"
313 				"\t-G grp1,grp2   additional groups\n"
314 				"\t-L class       default user class\n"
315 				"\t-k dir         default home skeleton\n"
316 				"\t-u min,max     set min,max uids\n"
317 				"\t-i min,max     set min,max gids\n"
318 				"\t-w method      set default password method\n"
319 				"\t-s shell       default shell\n"
320 				"\t-y path        set NIS passwd file path\n",
321 				"usage: pw userdel [uid|name] [switches]\n"
322 				"\t-V etcdir      alternate /etc location\n"
323 				"\t-n name        login name\n"
324 				"\t-u uid         user id\n"
325 				"\t-Y             update NIS maps\n"
326 				"\t-r             remove home & contents\n",
327 				"usage: pw usermod [uid|name] [switches]\n"
328 				"\t-V etcdir      alternate /etc location\n"
329 				"\t-C config      configuration file\n"
330 				"\t-q             quiet operation\n"
331 				"\t-F             force add if no user\n"
332 				"\t-n name        login name\n"
333 				"\t-u uid         user id\n"
334 				"\t-c comment     user name/comment\n"
335 				"\t-d directory   home directory\n"
336 				"\t-e date        account expiry date\n"
337 				"\t-p date        password expiry date\n"
338 				"\t-g grp         initial group\n"
339 				"\t-G grp1,grp2   additional groups\n"
340 				"\t-l name        new login name\n"
341 				"\t-L class       user class\n"
342 				"\t-m [ -k dir ]  create and set up home\n"
343 				"\t-s shell       name of login shell\n"
344 				"\t-w method      set new password using method\n"
345 				"\t-h fd          read password on fd\n"
346 				"\t-Y             update NIS maps\n"
347 				"\t-N             no update\n",
348 				"usage: pw usershow [uid|name] [switches]\n"
349 				"\t-V etcdir      alternate /etc location\n"
350 				"\t-n name        login name\n"
351 				"\t-u uid         user id\n"
352 				"\t-F             force print\n"
353 				"\t-P             prettier format\n"
354 				"\t-a             print all users\n"
355 				"\t-7             print in v7 format\n",
356 				"usage: pw usernext [switches]\n"
357 				"\t-V etcdir      alternate /etc location\n"
358 				"\t-C config      configuration file\n"
359 			},
360 			{
361 				"usage: pw groupadd [group|gid] [switches]\n"
362 				"\t-V etcdir      alternate /etc location\n"
363 				"\t-C config      configuration file\n"
364 				"\t-q             quiet operation\n"
365 				"\t-n group       group name\n"
366 				"\t-g gid         group id\n"
367 				"\t-M usr1,usr2   add users as group members\n"
368 				"\t-o             duplicate gid ok\n"
369 				"\t-Y             update NIS maps\n"
370 				"\t-N             no update\n",
371 				"usage: pw groupdel [group|gid] [switches]\n"
372 				"\t-V etcdir      alternate /etc location\n"
373 				"\t-n name        group name\n"
374 				"\t-g gid         group id\n"
375 				"\t-Y             update NIS maps\n",
376 				"usage: pw groupmod [group|gid] [switches]\n"
377 				"\t-V etcdir      alternate /etc location\n"
378 				"\t-C config      configuration file\n"
379 				"\t-q             quiet operation\n"
380 				"\t-F             force add if not exists\n"
381 				"\t-n name        group name\n"
382 				"\t-g gid         group id\n"
383 				"\t-M usr1,usr2   replaces users as group members\n"
384 				"\t-m usr1,usr2   add users as group members\n"
385 				"\t-l name        new group name\n"
386 				"\t-Y             update NIS maps\n"
387 				"\t-N             no update\n",
388 				"usage: pw groupshow [group|gid] [switches]\n"
389 				"\t-V etcdir      alternate /etc location\n"
390 				"\t-n name        group name\n"
391 				"\t-g gid         group id\n"
392 				"\t-F             force print\n"
393 				"\t-P             prettier format\n"
394 				"\t-a             print all accounting groups\n",
395 				"usage: pw groupnext [switches]\n"
396 				"\t-V etcdir      alternate /etc location\n"
397 				"\t-C config      configuration file\n"
398 			}
399 		};
400 
401 		fprintf(stderr, help[which][mode]);
402 	}
403 	exit(EXIT_FAILURE);
404 }
405 
406 struct carg    *
407 getarg(struct cargs * _args, int ch)
408 {
409 	struct carg    *c = _args->lh_first;
410 
411 	while (c != NULL && c->ch != ch)
412 		c = c->list.le_next;
413 	return c;
414 }
415 
416 struct carg    *
417 addarg(struct cargs * _args, int ch, char *argstr)
418 {
419 	struct carg    *ca = malloc(sizeof(struct carg));
420 
421 	if (ca == NULL)
422 		errx(EX_OSERR, "out of memory");
423 	ca->ch = ch;
424 	ca->val = argstr;
425 	LIST_INSERT_HEAD(_args, ca, list);
426 	return ca;
427 }
428