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