usermod.c (2243B)
1 /* see LICENSE file for copyright and license details */ 2 #ifndef _DEFAULT_SOURCE 3 #define _DEFAULT_SOURCE 4 #endif 5 #include <errno.h> 6 #include <grp.h> 7 #include <stdlib.h> 8 #include <string.h> 9 #include <unistd.h> 10 11 #include "accounts.h" 12 #include "passwd.h" 13 #include "util.h" 14 15 static void 16 usage(void) 17 { 18 eprintf("usage: %s [-R root] [-p hash] [-a] [-G group,...] name\n", argv0); 19 } 20 21 /* whether group is one of list, a comma separated list */ 22 static int 23 listed(const char *list, const char *group) 24 { 25 size_t n = strlen(group); 26 27 for (const char *p = list; p && *p; p = strchr(p, ',') ? strchr(p, ',') + 1 : NULL) 28 if (!strncmp(p, group, n) && (p[n] == ',' || p[n] == '\0')) 29 return 1; 30 return 0; 31 } 32 33 // ?man usermod: change a person 34 // ?man arguments: [-R root] [-p hash] [-a] [-G group,...] name 35 // ?man changes a person's password and the groups they are in 36 int 37 main(int argc, char *argv[]) 38 { 39 char *root = NULL, *hash = NULL, *groups = NULL, *g, *save; 40 struct group *gr; 41 int append = 0; 42 43 ARGBEGIN 44 { 45 // ?man -R:str: work in another root 46 case 'R': 47 root = EARGF(usage()); 48 break; 49 // ?man -p:str: the password as crypt(3) gives it 50 case 'p': 51 hash = EARGF(usage()); 52 break; 53 // ?man -a: with -G, only put the person in the groups 54 case 'a': 55 append = 1; 56 break; 57 // ?man -G:str: the groups the person is in, apart by commas, and no other 58 case 'G': 59 groups = EARGF(usage()); 60 break; 61 default: 62 usage(); 63 } 64 ARGEND; 65 if (argc != 1 || (append && !groups)) 66 usage(); 67 if (root && (chroot(root) < 0 || chdir("/") < 0)) 68 eprintf("chroot %s:", root); 69 if (hash && pwdb_update(argv[0], hash) < 0) 70 eprintf("%s: the password could not be kept\n", argv[0]); 71 if (groups && !append) { 72 setgrent(); 73 while ((gr = getgrent())) 74 for (char **m = gr->gr_mem; m && *m; m++) 75 if (!strcmp(*m, argv[0]) && !listed(groups, gr->gr_name) 76 && acct_member(gr->gr_name, argv[0], 0) < 0) 77 weprintf("%s:", gr->gr_name); 78 endgrent(); 79 } 80 for (g = groups ? strtok_r(groups, ",", &save) : NULL; g; g = strtok_r(NULL, ",", &save)) 81 if (acct_member(g, argv[0], 1) < 0) 82 weprintf("%s:", g); 83 return 0; 84 }