]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - usr.sbin/pw/pw_user.c
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / usr.sbin / pw / pw_user.c
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
28 #ifndef lint
29 static const char rcsid[] =
30   "$FreeBSD$";
31 #endif /* not lint */
32
33 #include <ctype.h>
34 #include <err.h>
35 #include <fcntl.h>
36 #include <sys/param.h>
37 #include <dirent.h>
38 #include <paths.h>
39 #include <termios.h>
40 #include <sys/types.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <login_cap.h>
44 #include <pwd.h>
45 #include <grp.h>
46 #include <libutil.h>
47 #include "pw.h"
48 #include "bitmap.h"
49
50 #define LOGNAMESIZE (MAXLOGNAME-1)
51
52 static          char locked_str[] = "*LOCKED*";
53
54 static int      delete_user(struct userconf *cnf, struct passwd *pwd,
55                     char *name, int delete, int mode);
56 static int      print_user(struct passwd * pwd);
57 static uid_t    pw_uidpolicy(struct userconf * cnf, long id);
58 static uid_t    pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer);
59 static time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
60 static time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
61 static char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
62 static char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
63 static char    *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
64 static char    *shell_path(char const * path, char *shells[], char *sh);
65 static void     rmat(uid_t uid);
66 static void     rmopie(char const * name);
67
68 static void
69 create_and_populate_homedir(int mode, struct passwd *pwd)
70 {
71         char *homedir, *dotdir;
72         struct userconf *cnf = conf.userconf;
73
74         homedir = dotdir = NULL;
75
76         if (conf.rootdir[0] != '\0') {
77                 asprintf(&homedir, "%s/%s", conf.rootdir, pwd->pw_dir);
78                 if (homedir == NULL)
79                         errx(EX_OSERR, "out of memory");
80                 asprintf(&dotdir, "%s/%s", conf.rootdir, cnf->dotdir);
81         }
82
83         copymkdir(homedir ? homedir : pwd->pw_dir, dotdir ? dotdir: cnf->dotdir,
84             cnf->homemode, pwd->pw_uid, pwd->pw_gid);
85         pw_log(cnf, mode, W_USER, "%s(%u) home %s made", pwd->pw_name,
86             pwd->pw_uid, pwd->pw_dir);
87 }
88
89 /*-
90  * -C config      configuration file
91  * -q             quiet operation
92  * -n name        login name
93  * -u uid         user id
94  * -c comment     user name/comment
95  * -d directory   home directory
96  * -e date        account expiry date
97  * -p date        password expiry date
98  * -g grp         primary group
99  * -G grp1,grp2   additional groups
100  * -m [ -k dir ]  create and set up home
101  * -s shell       name of login shell
102  * -o             duplicate uid ok
103  * -L class       user class
104  * -l name        new login name
105  * -h fd          password filehandle
106  * -H fd          encrypted password filehandle
107  * -F             force print or add
108  *   Setting defaults:
109  * -D             set user defaults
110  * -b dir         default home root dir
111  * -e period      default expiry period
112  * -p period      default password change period
113  * -g group       default group
114  * -G             grp1,grp2.. default additional groups
115  * -L class       default login class
116  * -k dir         default home skeleton
117  * -s shell       default shell
118  * -w method      default password method
119  */
120
121 int
122 pw_user(int mode, char *name, long id, struct cargs * args)
123 {
124         int             rc, edited = 0;
125         char           *p = NULL;
126         char                                     *passtmp;
127         struct carg    *arg;
128         struct passwd  *pwd = NULL;
129         struct group   *grp;
130         struct stat     st;
131         struct userconf *cnf;
132         char            line[_PASSWORD_LEN+1];
133         char            path[MAXPATHLEN];
134         FILE           *fp;
135         char *dmode_c;
136         void *set = NULL;
137
138         static struct passwd fakeuser =
139         {
140                 NULL,
141                 "*",
142                 -1,
143                 -1,
144                 0,
145                 "",
146                 "User &",
147                 "/nonexistent",
148                 "/bin/sh",
149                 0
150 #if defined(__FreeBSD__)
151                 ,0
152 #endif
153         };
154
155         cnf = conf.userconf;
156
157         /*
158          * With M_NEXT, we only need to return the
159          * next uid to stdout
160          */
161         if (mode == M_NEXT)
162         {
163                 uid_t next = pw_uidpolicy(cnf, id);
164                 if (getarg(args, 'q'))
165                         return next;
166                 printf("%u:", next);
167                 pw_group(mode, name, -1, args);
168                 return EXIT_SUCCESS;
169         }
170
171         /*
172          * We can do all of the common legwork here
173          */
174
175         if ((arg = getarg(args, 'b')) != NULL) {
176                 cnf->home = arg->val;
177         }
178
179         if ((arg = getarg(args, 'M')) != NULL) {
180                 dmode_c = arg->val;
181                 if ((set = setmode(dmode_c)) == NULL)
182                         errx(EX_DATAERR, "invalid directory creation mode '%s'",
183                             dmode_c);
184                 cnf->homemode = getmode(set, _DEF_DIRMODE);
185                 free(set);
186         }
187
188         /*
189          * If we'll need to use it or we're updating it,
190          * then create the base home directory if necessary
191          */
192         if (arg != NULL || getarg(args, 'm') != NULL) {
193                 int     l = strlen(cnf->home);
194
195                 if (l > 1 && cnf->home[l-1] == '/')     /* Shave off any trailing path delimiter */
196                         cnf->home[--l] = '\0';
197
198                 if (l < 2 || *cnf->home != '/')         /* Check for absolute path name */
199                         errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
200
201                 if (stat(cnf->home, &st) == -1) {
202                         char    dbuf[MAXPATHLEN];
203
204                         /*
205                          * This is a kludge especially for Joerg :)
206                          * If the home directory would be created in the root partition, then
207                          * we really create it under /usr which is likely to have more space.
208                          * But we create a symlink from cnf->home -> "/usr" -> cnf->home
209                          */
210                         if (strchr(cnf->home+1, '/') == NULL) {
211                                 snprintf(dbuf, MAXPATHLEN, "/usr%s", cnf->home);
212                                 if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
213                                         chown(dbuf, 0, 0);
214                                         /*
215                                          * Skip first "/" and create symlink:
216                                          * /home -> usr/home
217                                          */
218                                         symlink(dbuf+1, cnf->home);
219                                 }
220                                 /* If this falls, fall back to old method */
221                         }
222                         strlcpy(dbuf, cnf->home, sizeof(dbuf));
223                         p = dbuf;
224                         if (stat(dbuf, &st) == -1) {
225                                 while ((p = strchr(p + 1, '/')) != NULL) {
226                                         *p = '\0';
227                                         if (stat(dbuf, &st) == -1) {
228                                                 if (mkdir(dbuf, _DEF_DIRMODE) == -1)
229                                                         goto direrr;
230                                                 chown(dbuf, 0, 0);
231                                         } else if (!S_ISDIR(st.st_mode))
232                                                 errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
233                                         *p = '/';
234                                 }
235                         }
236                         if (stat(dbuf, &st) == -1) {
237                                 if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
238                                 direrr: err(EX_OSFILE, "mkdir '%s'", dbuf);
239                                 }
240                                 chown(dbuf, 0, 0);
241                         }
242                 } else if (!S_ISDIR(st.st_mode))
243                         errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
244         }
245
246         if ((arg = getarg(args, 'e')) != NULL)
247                 cnf->expire_days = atoi(arg->val);
248
249         if ((arg = getarg(args, 'y')) != NULL)
250                 cnf->nispasswd = arg->val;
251
252         if ((arg = getarg(args, 'p')) != NULL && arg->val)
253                 cnf->password_days = atoi(arg->val);
254
255         if ((arg = getarg(args, 'g')) != NULL) {
256                 if (!*(p = arg->val))   /* Handle empty group list specially */
257                         cnf->default_group = "";
258                 else {
259                         if ((grp = GETGRNAM(p)) == NULL) {
260                                 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
261                                         errx(EX_NOUSER, "group `%s' does not exist", p);
262                         }
263                         cnf->default_group = newstr(grp->gr_name);
264                 }
265         }
266         if ((arg = getarg(args, 'L')) != NULL)
267                 cnf->default_class = pw_checkname(arg->val, 0);
268
269         if ((arg = getarg(args, 'G')) != NULL && arg->val) {
270                 int i = 0;
271
272                 for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
273                         if ((grp = GETGRNAM(p)) == NULL) {
274                                 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
275                                         errx(EX_NOUSER, "group `%s' does not exist", p);
276                         }
277                         if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
278                                 cnf->groups[i++] = newstr(grp->gr_name);
279                 }
280                 while (i < cnf->numgroups)
281                         cnf->groups[i++] = NULL;
282         }
283
284         if ((arg = getarg(args, 'k')) != NULL) {
285                 if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
286                         errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
287         }
288
289         if ((arg = getarg(args, 's')) != NULL)
290                 cnf->shell_default = arg->val;
291
292         if ((arg = getarg(args, 'w')) != NULL)
293                 cnf->default_password = boolean_val(arg->val, cnf->default_password);
294         if (mode == M_ADD && getarg(args, 'D')) {
295                 if (name != NULL)
296                         errx(EX_DATAERR, "can't combine `-D' with `-n name'");
297                 if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
298                         if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
299                                 cnf->min_uid = 1000;
300                         if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
301                                 cnf->max_uid = 32000;
302                 }
303                 if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
304                         if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
305                                 cnf->min_gid = 1000;
306                         if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
307                                 cnf->max_gid = 32000;
308                 }
309
310                 if (write_userconfig(conf.config))
311                         return (EXIT_SUCCESS);
312                 err(EX_IOERR, "config udpate");
313         }
314
315         if (mode == M_PRINT && getarg(args, 'a')) {
316                 SETPWENT();
317                 while ((pwd = GETPWENT()) != NULL)
318                         print_user(pwd);
319                 ENDPWENT();
320                 return EXIT_SUCCESS;
321         }
322
323         if (name != NULL)
324                 pwd = GETPWNAM(pw_checkname(name, 0));
325
326         if (id < 0 && name == NULL)
327                 errx(EX_DATAERR, "user name or id required");
328
329         /*
330          * Update, delete & print require that the user exists
331          */
332         if (mode == M_UPDATE || mode == M_DELETE ||
333             mode == M_PRINT  || mode == M_LOCK   || mode == M_UNLOCK) {
334
335                 if (name == NULL && pwd == NULL)        /* Try harder */
336                         pwd = GETPWUID(id);
337
338                 if (pwd == NULL) {
339                         if (mode == M_PRINT && getarg(args, 'F')) {
340                                 fakeuser.pw_name = name ? name : "nouser";
341                                 fakeuser.pw_uid = (uid_t) id;
342                                 return print_user(&fakeuser);
343                         }
344                         if (name == NULL)
345                                 errx(EX_NOUSER, "no such uid `%ld'", id);
346                         errx(EX_NOUSER, "no such user `%s'", name);
347                 }
348
349                 if (name == NULL)
350                         name = pwd->pw_name;
351
352                 /*
353                  * The M_LOCK and M_UNLOCK functions simply add or remove
354                  * a "*LOCKED*" prefix from in front of the password to
355                  * prevent it decoding correctly, and therefore prevents
356                  * access. Of course, this only prevents access via
357                  * password authentication (not ssh, kerberos or any
358                  * other method that does not use the UNIX password) but
359                  * that is a known limitation.
360                  */
361
362                 if (mode == M_LOCK) {
363                         if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
364                                 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
365                         asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
366                         if (passtmp == NULL)    /* disaster */
367                                 errx(EX_UNAVAILABLE, "out of memory");
368                         pwd->pw_passwd = passtmp;
369                         edited = 1;
370                 } else if (mode == M_UNLOCK) {
371                         if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
372                                 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
373                         pwd->pw_passwd += sizeof(locked_str)-1;
374                         edited = 1;
375                 } else if (mode == M_DELETE)
376                         return (delete_user(cnf, pwd, name,
377                                     getarg(args, 'r') != NULL, mode));
378                 else if (mode == M_PRINT)
379                         return print_user(pwd);
380
381                 /*
382                  * The rest is edit code
383                  */
384                 if (conf.newname != NULL) {
385                         if (strcmp(pwd->pw_name, "root") == 0)
386                                 errx(EX_DATAERR, "can't rename `root' account");
387                         pwd->pw_name = pw_checkname(conf.newname, 0);
388                         edited = 1;
389                 }
390
391                 if (id > 0 && isdigit((unsigned char)*arg->val)) {
392                         pwd->pw_uid = (uid_t)id;
393                         edited = 1;
394                         if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
395                                 errx(EX_DATAERR, "can't change uid of `root' account");
396                         if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
397                                 warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
398                 }
399
400                 if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {    /* Already checked this */
401                         gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
402                         if (newgid != pwd->pw_gid) {
403                                 edited = 1;
404                                 pwd->pw_gid = newgid;
405                         }
406                 }
407
408                 if ((arg = getarg(args, 'p')) != NULL) {
409                         if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
410                                 if (pwd->pw_change != 0) {
411                                         pwd->pw_change = 0;
412                                         edited = 1;
413                                 }
414                         }
415                         else {
416                                 time_t          now = time(NULL);
417                                 time_t          expire = parse_date(now, arg->val);
418
419                                 if (pwd->pw_change != expire) {
420                                         pwd->pw_change = expire;
421                                         edited = 1;
422                                 }
423                         }
424                 }
425
426                 if ((arg = getarg(args, 'e')) != NULL) {
427                         if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
428                                 if (pwd->pw_expire != 0) {
429                                         pwd->pw_expire = 0;
430                                         edited = 1;
431                                 }
432                         }
433                         else {
434                                 time_t          now = time(NULL);
435                                 time_t          expire = parse_date(now, arg->val);
436
437                                 if (pwd->pw_expire != expire) {
438                                         pwd->pw_expire = expire;
439                                         edited = 1;
440                                 }
441                         }
442                 }
443
444                 if ((arg = getarg(args, 's')) != NULL) {
445                         char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
446                         if (shell == NULL)
447                                 shell = "";
448                         if (strcmp(shell, pwd->pw_shell) != 0) {
449                                 pwd->pw_shell = shell;
450                                 edited = 1;
451                         }
452                 }
453
454                 if (getarg(args, 'L')) {
455                         if (cnf->default_class == NULL)
456                                 cnf->default_class = "";
457                         if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
458                                 pwd->pw_class = cnf->default_class;
459                                 edited = 1;
460                         }
461                 }
462
463                 if ((arg  = getarg(args, 'd')) != NULL) {
464                         if (strcmp(pwd->pw_dir, arg->val))
465                                 edited = 1;
466                         if (stat(pwd->pw_dir = arg->val, &st) == -1) {
467                                 if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
468                                   warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
469                         } else if (!S_ISDIR(st.st_mode))
470                                 warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
471                 }
472
473                 if ((arg = getarg(args, 'w')) != NULL &&
474                     getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
475                         login_cap_t *lc;
476
477                         lc = login_getpwclass(pwd);
478                         if (lc == NULL ||
479                             login_setcryptfmt(lc, "sha512", NULL) == NULL)
480                                 warn("setting crypt(3) format");
481                         login_close(lc);
482                         pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
483                         edited = 1;
484                 }
485
486         } else {
487                 login_cap_t *lc;
488
489                 /*
490                  * Add code
491                  */
492
493                 if (name == NULL)       /* Required */
494                         errx(EX_DATAERR, "login name required");
495                 else if ((pwd = GETPWNAM(name)) != NULL)        /* Exists */
496                         errx(EX_DATAERR, "login name `%s' already exists", name);
497
498                 /*
499                  * Now, set up defaults for a new user
500                  */
501                 pwd = &fakeuser;
502                 pwd->pw_name = name;
503                 pwd->pw_class = cnf->default_class ? cnf->default_class : "";
504                 pwd->pw_uid = pw_uidpolicy(cnf, id);
505                 pwd->pw_gid = pw_gidpolicy(args, pwd->pw_name, (gid_t) pwd->pw_uid);
506                 pwd->pw_change = pw_pwdpolicy(cnf, args);
507                 pwd->pw_expire = pw_exppolicy(cnf, args);
508                 pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
509                 pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
510                 lc = login_getpwclass(pwd);
511                 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
512                         warn("setting crypt(3) format");
513                 login_close(lc);
514                 pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
515                 edited = 1;
516
517                 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
518                         warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
519         }
520
521         /*
522          * Shared add/edit code
523          */
524         if ((arg = getarg(args, 'c')) != NULL) {
525                 char    *gecos = pw_checkname(arg->val, 1);
526                 if (strcmp(pwd->pw_gecos, gecos) != 0) {
527                         pwd->pw_gecos = gecos;
528                         edited = 1;
529                 }
530         }
531
532         if ((arg = getarg(args, 'h')) != NULL ||
533             (arg = getarg(args, 'H')) != NULL) {
534                 if (strcmp(arg->val, "-") == 0) {
535                         if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
536                                 pwd->pw_passwd = "*";   /* No access */
537                                 edited = 1;
538                         }
539                 } else {
540                         int             fd = atoi(arg->val);
541                         int             precrypt = (arg->ch == 'H');
542                         int             b;
543                         int             istty = isatty(fd);
544                         struct termios  t;
545                         login_cap_t     *lc;
546
547                         if (istty) {
548                                 if (tcgetattr(fd, &t) == -1)
549                                         istty = 0;
550                                 else {
551                                         struct termios  n = t;
552
553                                         /* Disable echo */
554                                         n.c_lflag &= ~(ECHO);
555                                         tcsetattr(fd, TCSANOW, &n);
556                                         printf("%s%spassword for user %s:",
557                                              (mode == M_UPDATE) ? "new " : "",
558                                              precrypt ? "encrypted " : "",
559                                              pwd->pw_name);
560                                         fflush(stdout);
561                                 }
562                         }
563                         b = read(fd, line, sizeof(line) - 1);
564                         if (istty) {    /* Restore state */
565                                 tcsetattr(fd, TCSANOW, &t);
566                                 fputc('\n', stdout);
567                                 fflush(stdout);
568                         }
569                         if (b < 0)
570                                 err(EX_IOERR, "-%c file descriptor",
571                                     precrypt ? 'H' : 'h');
572                         line[b] = '\0';
573                         if ((p = strpbrk(line, "\r\n")) != NULL)
574                                 *p = '\0';
575                         if (!*line)
576                                 errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
577                         if (precrypt) {
578                                 if (strchr(line, ':') != NULL)
579                                         return EX_DATAERR;
580                                 pwd->pw_passwd = line;
581                         } else {
582                                 lc = login_getpwclass(pwd);
583                                 if (lc == NULL ||
584                                     login_setcryptfmt(lc, "sha512", NULL) == NULL)
585                                         warn("setting crypt(3) format");
586                                 login_close(lc);
587                                 pwd->pw_passwd = pw_pwcrypt(line);
588                         }
589                         edited = 1;
590                 }
591         }
592
593         /*
594          * Special case: -N only displays & exits
595          */
596         if (conf.dryrun)
597                 return print_user(pwd);
598
599         if (mode == M_ADD) {
600                 edited = 1;     /* Always */
601                 rc = addpwent(pwd);
602                 if (rc == -1)
603                         errx(EX_IOERR, "user '%s' already exists",
604                             pwd->pw_name);
605                 else if (rc != 0)
606                         err(EX_IOERR, "passwd file update");
607                 if (cnf->nispasswd && *cnf->nispasswd=='/') {
608                         rc = addnispwent(cnf->nispasswd, pwd);
609                         if (rc == -1)
610                                 warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
611                         else
612                                 warn("NIS passwd update");
613                         /* NOTE: we treat NIS-only update errors as non-fatal */
614                 }
615         } else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
616                 if (edited) {   /* Only updated this if required */
617                         rc = chgpwent(name, pwd);
618                         if (rc == -1)
619                                 errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
620                         else if (rc != 0)
621                                 err(EX_IOERR, "passwd file update");
622                         if ( cnf->nispasswd && *cnf->nispasswd=='/') {
623                                 rc = chgnispwent(cnf->nispasswd, name, pwd);
624                                 if (rc == -1)
625                                         warn("User '%s' not found in NIS passwd", pwd->pw_name);
626                                 else
627                                         warn("NIS passwd update");
628                                 /* NOTE: NIS-only update errors are not fatal */
629                         }
630                 }
631         }
632
633         /*
634          * Ok, user is created or changed - now edit group file
635          */
636
637         if (mode == M_ADD || getarg(args, 'G') != NULL) {
638                 int i, j;
639                 /* First remove the user from all group */
640                 SETGRENT();
641                 while ((grp = GETGRENT()) != NULL) {
642                         char group[MAXLOGNAME];
643                         if (grp->gr_mem == NULL)
644                                 continue;
645                         for (i = 0; grp->gr_mem[i] != NULL; i++) {
646                                 if (strcmp(grp->gr_mem[i] , pwd->pw_name) != 0)
647                                         continue;
648                                 for (j = i; grp->gr_mem[j] != NULL ; j++)
649                                         grp->gr_mem[j] = grp->gr_mem[j+1];
650                                 strlcpy(group, grp->gr_name, MAXLOGNAME);
651                                 chggrent(group, grp);
652                         }
653                 }
654                 ENDGRENT();
655
656                 /* now add to group where needed */
657                 for (i = 0; cnf->groups[i] != NULL; i++) {
658                         grp = GETGRNAM(cnf->groups[i]);
659                         grp = gr_add(grp, pwd->pw_name);
660                         /*
661                          * grp can only be NULL in 2 cases:
662                          * - the new member is already a member
663                          * - a problem with memory occurs
664                          * in both cases we want to skip now.
665                          */
666                         if (grp == NULL)
667                                 continue;
668                         chggrent(cnf->groups[i], grp);
669                         free(grp);
670                 }
671         }
672
673
674         /* go get a current version of pwd */
675         pwd = GETPWNAM(name);
676         if (pwd == NULL) {
677                 /* This will fail when we rename, so special case that */
678                 if (mode == M_UPDATE && conf.newname != NULL) {
679                         name = conf.newname;            /* update new name */
680                         pwd = GETPWNAM(name);   /* refetch renamed rec */
681                 }
682         }
683         if (pwd == NULL)        /* can't go on without this */
684                 errx(EX_NOUSER, "user '%s' disappeared during update", name);
685
686         grp = GETGRGID(pwd->pw_gid);
687         pw_log(cnf, mode, W_USER, "%s(%u):%s(%u):%s:%s:%s",
688                pwd->pw_name, pwd->pw_uid,
689             grp ? grp->gr_name : "unknown", (grp ? grp->gr_gid : (uid_t)-1),
690                pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
691
692         /*
693          * If adding, let's touch and chown the user's mail file. This is not
694          * strictly necessary under BSD with a 0755 maildir but it also
695          * doesn't hurt anything to create the empty mailfile
696          */
697         if (mode == M_ADD) {
698                 if (PWALTDIR() != PWF_ALT) {
699                         arg = getarg(args, 'R');
700                         snprintf(path, sizeof(path), "%s%s/%s",
701                             arg ? arg->val : "", _PATH_MAILDIR, pwd->pw_name);
702                         close(open(path, O_RDWR | O_CREAT, 0600));      /* Preserve contents &
703                                                                          * mtime */
704                         chown(path, pwd->pw_uid, pwd->pw_gid);
705                 }
706         }
707
708         /*
709          * Let's create and populate the user's home directory. Note
710          * that this also `works' for editing users if -m is used, but
711          * existing files will *not* be overwritten.
712          */
713         if (PWALTDIR() != PWF_ALT && getarg(args, 'm') != NULL && pwd->pw_dir &&
714             *pwd->pw_dir == '/' && pwd->pw_dir[1])
715                 create_and_populate_homedir(mode, pwd);
716
717         /*
718          * Finally, send mail to the new user as well, if we are asked to
719          */
720         if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
721                 FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
722                 
723                 if (pfp == NULL)
724                         warn("sendmail");
725                 else {
726                         fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
727                         while (fgets(line, sizeof(line), fp) != NULL) {
728                                 /* Do substitutions? */
729                                 fputs(line, pfp);
730                         }
731                         pclose(pfp);
732                         pw_log(cnf, mode, W_USER, "%s(%u) new user mail sent",
733                             pwd->pw_name, pwd->pw_uid);
734                 }
735                 fclose(fp);
736         }
737
738         return EXIT_SUCCESS;
739 }
740
741
742 static          uid_t
743 pw_uidpolicy(struct userconf * cnf, long id)
744 {
745         struct passwd  *pwd;
746         uid_t           uid = (uid_t) - 1;
747
748         /*
749          * Check the given uid, if any
750          */
751         if (id >= 0) {
752                 uid = (uid_t) id;
753
754                 if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
755                         errx(EX_DATAERR, "uid `%u' has already been allocated", pwd->pw_uid);
756         } else {
757                 struct bitmap   bm;
758
759                 /*
760                  * We need to allocate the next available uid under one of
761                  * two policies a) Grab the first unused uid b) Grab the
762                  * highest possible unused uid
763                  */
764                 if (cnf->min_uid >= cnf->max_uid) {     /* Sanity
765                                                          * claus^H^H^H^Hheck */
766                         cnf->min_uid = 1000;
767                         cnf->max_uid = 32000;
768                 }
769                 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
770
771                 /*
772                  * Now, let's fill the bitmap from the password file
773                  */
774                 SETPWENT();
775                 while ((pwd = GETPWENT()) != NULL)
776                         if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
777                                 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
778                 ENDPWENT();
779
780                 /*
781                  * Then apply the policy, with fallback to reuse if necessary
782                  */
783                 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
784                         uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
785
786                 /*
787                  * Another sanity check
788                  */
789                 if (uid < cnf->min_uid || uid > cnf->max_uid)
790                         errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
791                 bm_dealloc(&bm);
792         }
793         return uid;
794 }
795
796
797 static          uid_t
798 pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer)
799 {
800         struct group   *grp;
801         gid_t           gid = (uid_t) - 1;
802         struct carg    *a_gid = getarg(args, 'g');
803         struct userconf *cnf = conf.userconf;
804
805         /*
806          * If no arg given, see if default can help out
807          */
808         if (a_gid == NULL && cnf->default_group && *cnf->default_group)
809                 a_gid = addarg(args, 'g', cnf->default_group);
810
811         /*
812          * Check the given gid, if any
813          */
814         SETGRENT();
815         if (a_gid != NULL) {
816                 if ((grp = GETGRNAM(a_gid->val)) == NULL) {
817                         gid = (gid_t) atol(a_gid->val);
818                         if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
819                                 errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
820                 }
821                 gid = grp->gr_gid;
822         } else if ((grp = GETGRNAM(nam)) != NULL &&
823             (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
824                 gid = grp->gr_gid;  /* Already created? Use it anyway... */
825         } else {
826                 struct cargs    grpargs;
827                 gid_t           grid = -1;
828
829                 LIST_INIT(&grpargs);
830
831                 /*
832                  * We need to auto-create a group with the user's name. We
833                  * can send all the appropriate output to our sister routine
834                  * bit first see if we can create a group with gid==uid so we
835                  * can keep the user and group ids in sync. We purposely do
836                  * NOT check the gid range if we can force the sync. If the
837                  * user's name dups an existing group, then the group add
838                  * function will happily handle that case for us and exit.
839                  */
840                 if (GETGRGID(prefer) == NULL)
841                         grid = prefer;
842                 if (conf.dryrun) {
843                         addarg(&grpargs, 'q', NULL);
844                         gid = pw_group(M_NEXT, nam, -1, &grpargs);
845                 }
846                 else
847                 {
848                         pw_group(M_ADD, nam, grid, &grpargs);
849                         if ((grp = GETGRNAM(nam)) != NULL)
850                                 gid = grp->gr_gid;
851                 }
852         }
853         ENDGRENT();
854         return gid;
855 }
856
857
858 static          time_t
859 pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
860 {
861         time_t          result = 0;
862         time_t          now = time(NULL);
863         struct carg    *arg = getarg(args, 'p');
864
865         if (arg != NULL) {
866                 if ((result = parse_date(now, arg->val)) == now)
867                         errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
868         } else if (cnf->password_days > 0)
869                 result = now + ((long) cnf->password_days * 86400L);
870         return result;
871 }
872
873
874 static          time_t
875 pw_exppolicy(struct userconf * cnf, struct cargs * args)
876 {
877         time_t          result = 0;
878         time_t          now = time(NULL);
879         struct carg    *arg = getarg(args, 'e');
880
881         if (arg != NULL) {
882                 if ((result = parse_date(now, arg->val)) == now)
883                         errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
884         } else if (cnf->expire_days > 0)
885                 result = now + ((long) cnf->expire_days * 86400L);
886         return result;
887 }
888
889
890 static char    *
891 pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
892 {
893         struct carg    *arg = getarg(args, 'd');
894         static char     home[128];
895
896         if (arg)
897                 return (arg->val);
898
899         if (cnf->home == NULL || *cnf->home == '\0')
900                 errx(EX_CONFIG, "no base home directory set");
901         snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
902
903         return (home);
904 }
905
906 static char    *
907 shell_path(char const * path, char *shells[], char *sh)
908 {
909         if (sh != NULL && (*sh == '/' || *sh == '\0'))
910                 return sh;      /* specified full path or forced none */
911         else {
912                 char           *p;
913                 char            paths[_UC_MAXLINE];
914
915                 /*
916                  * We need to search paths
917                  */
918                 strlcpy(paths, path, sizeof(paths));
919                 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
920                         int             i;
921                         static char     shellpath[256];
922
923                         if (sh != NULL) {
924                                 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
925                                 if (access(shellpath, X_OK) == 0)
926                                         return shellpath;
927                         } else
928                                 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
929                                         snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
930                                         if (access(shellpath, X_OK) == 0)
931                                                 return shellpath;
932                                 }
933                 }
934                 if (sh == NULL)
935                         errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
936                 errx(EX_CONFIG, "no default shell available or defined");
937                 return NULL;
938         }
939 }
940
941
942 static char    *
943 pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
944 {
945         char           *sh = newshell;
946         struct carg    *arg = getarg(args, 's');
947
948         if (newshell == NULL && arg != NULL)
949                 sh = arg->val;
950         return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
951 }
952
953 #define SALTSIZE        32
954
955 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
956
957 char           *
958 pw_pwcrypt(char *password)
959 {
960         int             i;
961         char            salt[SALTSIZE + 1];
962         char            *cryptpw;
963
964         static char     buf[256];
965
966         /*
967          * Calculate a salt value
968          */
969         for (i = 0; i < SALTSIZE; i++)
970                 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
971         salt[SALTSIZE] = '\0';
972
973         cryptpw = crypt(password, salt);
974         if (cryptpw == NULL)
975                 errx(EX_CONFIG, "crypt(3) failure");
976         return strcpy(buf, cryptpw);
977 }
978
979
980 static char    *
981 pw_password(struct userconf * cnf, struct cargs * args, char const * user)
982 {
983         int             i, l;
984         char            pwbuf[32];
985
986         switch (cnf->default_password) {
987         case -1:                /* Random password */
988                 l = (arc4random() % 8 + 8);     /* 8 - 16 chars */
989                 for (i = 0; i < l; i++)
990                         pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
991                 pwbuf[i] = '\0';
992
993                 /*
994                  * We give this information back to the user
995                  */
996                 if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
997                     !conf.dryrun) {
998                         if (isatty(STDOUT_FILENO))
999                                 printf("Password for '%s' is: ", user);
1000                         printf("%s\n", pwbuf);
1001                         fflush(stdout);
1002                 }
1003                 break;
1004
1005         case -2:                /* No password at all! */
1006                 return "";
1007
1008         case 0:         /* No login - default */
1009         default:
1010                 return "*";
1011
1012         case 1:         /* user's name */
1013                 strlcpy(pwbuf, user, sizeof(pwbuf));
1014                 break;
1015         }
1016         return pw_pwcrypt(pwbuf);
1017 }
1018
1019 static int
1020 delete_user(struct userconf *cnf, struct passwd *pwd, char *name,
1021     int delete, int mode)
1022 {
1023         char             file[MAXPATHLEN];
1024         char             home[MAXPATHLEN];
1025         uid_t            uid = pwd->pw_uid;
1026         struct group    *gr, *grp;
1027         char             grname[LOGNAMESIZE];
1028         int              rc;
1029         struct stat      st;
1030
1031         if (strcmp(pwd->pw_name, "root") == 0)
1032                 errx(EX_DATAERR, "cannot remove user 'root'");
1033
1034         if (!PWALTDIR()) {
1035                 /*
1036                  * Remove opie record from /etc/opiekeys
1037                 */
1038
1039                 rmopie(pwd->pw_name);
1040
1041                 /*
1042                  * Remove crontabs
1043                  */
1044                 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
1045                 if (access(file, F_OK) == 0) {
1046                         snprintf(file, sizeof(file), "crontab -u %s -r", pwd->pw_name);
1047                         system(file);
1048                 }
1049         }
1050         /*
1051          * Save these for later, since contents of pwd may be
1052          * invalidated by deletion
1053          */
1054         snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
1055         strlcpy(home, pwd->pw_dir, sizeof(home));
1056         gr = GETGRGID(pwd->pw_gid);
1057         if (gr != NULL)
1058                 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
1059         else
1060                 grname[0] = '\0';
1061
1062         rc = delpwent(pwd);
1063         if (rc == -1)
1064                 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
1065         else if (rc != 0)
1066                 err(EX_IOERR, "passwd update");
1067
1068         if (cnf->nispasswd && *cnf->nispasswd=='/') {
1069                 rc = delnispwent(cnf->nispasswd, name);
1070                 if (rc == -1)
1071                         warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
1072                 else if (rc != 0)
1073                         warn("WARNING: NIS passwd update");
1074                 /* non-fatal */
1075         }
1076
1077         grp = GETGRNAM(name);
1078         if (grp != NULL &&
1079             (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
1080             strcmp(name, grname) == 0)
1081                 delgrent(GETGRNAM(name));
1082         SETGRENT();
1083         while ((grp = GETGRENT()) != NULL) {
1084                 int i, j;
1085                 char group[MAXLOGNAME];
1086                 if (grp->gr_mem == NULL)
1087                         continue;
1088
1089                 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1090                         if (strcmp(grp->gr_mem[i], name) != 0)
1091                                 continue;
1092
1093                         for (j = i; grp->gr_mem[j] != NULL; j++)
1094                                 grp->gr_mem[j] = grp->gr_mem[j+1];
1095                         strlcpy(group, grp->gr_name, MAXLOGNAME);
1096                         chggrent(group, grp);
1097                 }
1098         }
1099         ENDGRENT();
1100
1101         pw_log(cnf, mode, W_USER, "%s(%u) account removed", name, uid);
1102
1103         if (!PWALTDIR()) {
1104                 /*
1105                  * Remove mail file
1106                  */
1107                 remove(file);
1108
1109                 /*
1110                  * Remove at jobs
1111                  */
1112                 if (getpwuid(uid) == NULL)
1113                         rmat(uid);
1114
1115                 /*
1116                  * Remove home directory and contents
1117                  */
1118                 if (delete && *home == '/' && getpwuid(uid) == NULL &&
1119                     stat(home, &st) != -1) {
1120                         rm_r(home, uid);
1121                         pw_log(cnf, mode, W_USER, "%s(%u) home '%s' %sremoved",
1122                                name, uid, home,
1123                                stat(home, &st) == -1 ? "" : "not completely ");
1124                 }
1125         }
1126
1127         return (EXIT_SUCCESS);
1128 }
1129
1130 static int
1131 print_user(struct passwd * pwd)
1132 {
1133         if (!conf.pretty) {
1134                 char            *buf;
1135
1136                 buf = conf.v7 ? pw_make_v7(pwd) : pw_make(pwd);
1137                 printf("%s\n", buf);
1138                 free(buf);
1139         } else {
1140                 int             j;
1141                 char           *p;
1142                 struct group   *grp = GETGRGID(pwd->pw_gid);
1143                 char            uname[60] = "User &", office[60] = "[None]",
1144                                 wphone[60] = "[None]", hphone[60] = "[None]";
1145                 char            acexpire[32] = "[None]", pwexpire[32] = "[None]";
1146                 struct tm *    tptr;
1147
1148                 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1149                         strlcpy(uname, p, sizeof(uname));
1150                         if ((p = strtok(NULL, ",")) != NULL) {
1151                                 strlcpy(office, p, sizeof(office));
1152                                 if ((p = strtok(NULL, ",")) != NULL) {
1153                                         strlcpy(wphone, p, sizeof(wphone));
1154                                         if ((p = strtok(NULL, "")) != NULL) {
1155                                                 strlcpy(hphone, p,
1156                                                     sizeof(hphone));
1157                                         }
1158                                 }
1159                         }
1160                 }
1161                 /*
1162                  * Handle '&' in gecos field
1163                  */
1164                 if ((p = strchr(uname, '&')) != NULL) {
1165                         int             l = strlen(pwd->pw_name);
1166                         int             m = strlen(p);
1167
1168                         memmove(p + l, p + 1, m);
1169                         memmove(p, pwd->pw_name, l);
1170                         *p = (char) toupper((unsigned char)*p);
1171                 }
1172                 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1173                         strftime(acexpire, sizeof acexpire, "%c", tptr);
1174                 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1175                         strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1176                 printf("Login Name: %-15s   #%-12u Group: %-15s   #%u\n"
1177                        " Full Name: %s\n"
1178                        "      Home: %-26.26s      Class: %s\n"
1179                        "     Shell: %-26.26s     Office: %s\n"
1180                        "Work Phone: %-26.26s Home Phone: %s\n"
1181                        "Acc Expire: %-26.26s Pwd Expire: %s\n",
1182                        pwd->pw_name, pwd->pw_uid,
1183                        grp ? grp->gr_name : "(invalid)", pwd->pw_gid,
1184                        uname, pwd->pw_dir, pwd->pw_class,
1185                        pwd->pw_shell, office, wphone, hphone,
1186                        acexpire, pwexpire);
1187                 SETGRENT();
1188                 j = 0;
1189                 while ((grp=GETGRENT()) != NULL)
1190                 {
1191                         int     i = 0;
1192                         if (grp->gr_mem != NULL) {
1193                                 while (grp->gr_mem[i] != NULL)
1194                                 {
1195                                         if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1196                                         {
1197                                                 printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
1198                                                 break;
1199                                         }
1200                                         ++i;
1201                                 }
1202                         }
1203                 }
1204                 ENDGRENT();
1205                 printf("%s", j ? "\n" : "");
1206         }
1207         return EXIT_SUCCESS;
1208 }
1209
1210 char *
1211 pw_checkname(char *name, int gecos)
1212 {
1213         char showch[8];
1214         const char *badchars, *ch, *showtype;
1215         int reject;
1216
1217         ch = name;
1218         reject = 0;
1219         if (gecos) {
1220                 /* See if the name is valid as a gecos (comment) field. */
1221                 badchars = ":!@";
1222                 showtype = "gecos field";
1223         } else {
1224                 /* See if the name is valid as a userid or group. */
1225                 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1226                 showtype = "userid/group name";
1227                 /* Userids and groups can not have a leading '-'. */
1228                 if (*ch == '-')
1229                         reject = 1;
1230         }
1231         if (!reject) {
1232                 while (*ch) {
1233                         if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1234                             *ch == 127) {
1235                                 reject = 1;
1236                                 break;
1237                         }
1238                         /* 8-bit characters are only allowed in GECOS fields */
1239                         if (!gecos && (*ch & 0x80)) {
1240                                 reject = 1;
1241                                 break;
1242                         }
1243                         ch++;
1244                 }
1245         }
1246         /*
1247          * A `$' is allowed as the final character for userids and groups,
1248          * mainly for the benefit of samba.
1249          */
1250         if (reject && !gecos) {
1251                 if (*ch == '$' && *(ch + 1) == '\0') {
1252                         reject = 0;
1253                         ch++;
1254                 }
1255         }
1256         if (reject) {
1257                 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1258                     ? "`%c'" : "0x%02x", *ch);
1259                 errx(EX_DATAERR, "invalid character %s at position %td in %s",
1260                     showch, (ch - name), showtype);
1261         }
1262         if (!gecos && (ch - name) > LOGNAMESIZE)
1263                 errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1264                     LOGNAMESIZE);
1265
1266         return (name);
1267 }
1268
1269
1270 static void
1271 rmat(uid_t uid)
1272 {
1273         DIR            *d = opendir("/var/at/jobs");
1274
1275         if (d != NULL) {
1276                 struct dirent  *e;
1277
1278                 while ((e = readdir(d)) != NULL) {
1279                         struct stat     st;
1280
1281                         if (strncmp(e->d_name, ".lock", 5) != 0 &&
1282                             stat(e->d_name, &st) == 0 &&
1283                             !S_ISDIR(st.st_mode) &&
1284                             st.st_uid == uid) {
1285                                 char            tmp[MAXPATHLEN];
1286
1287                                 snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s", e->d_name);
1288                                 system(tmp);
1289                         }
1290                 }
1291                 closedir(d);
1292         }
1293 }
1294
1295 static void
1296 rmopie(char const * name)
1297 {
1298         static const char etcopie[] = "/etc/opiekeys";
1299         FILE   *fp = fopen(etcopie, "r+");
1300
1301         if (fp != NULL) {
1302                 char    tmp[1024];
1303                 off_t   atofs = 0;
1304                 int     length = strlen(name);
1305
1306                 while (fgets(tmp, sizeof tmp, fp) != NULL) {
1307                         if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
1308                                 if (fseek(fp, atofs, SEEK_SET) == 0) {
1309                                         fwrite("#", 1, 1, fp);  /* Comment username out */
1310                                 }
1311                                 break;
1312                         }
1313                         atofs = ftell(fp);
1314                 }
1315                 /*
1316                  * If we got an error of any sort, don't update!
1317                  */
1318                 fclose(fp);
1319         }
1320 }
1321