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