deluser: size reduction by 60 bytes.
[platform/upstream/busybox.git] / loginutils / deluser.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * deluser (remove lusers from the system ;) for TinyLogin
4  *
5  * Copyright (C) 1999 by Lineo, inc. and John Beppu
6  * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
7  * Unified with delgroup by Tito Ragusa <farmatito@tiscali.it>
8  *
9  * Licensed under GPL version 2, see file LICENSE in this tarball for details.
10  *
11  */
12
13 #include "busybox.h"
14
15 static void del_line_matching(const char *login, const char *filename)
16 {
17         char *line;
18         FILE *passwd;
19         int len = strlen(login);
20         int found = 0;
21         llist_t *plist = NULL;
22         
23         passwd = fopen_or_warn(filename, "r");
24         if (!passwd) return;
25
26         while ((line = xmalloc_fgets(passwd))) {
27                 if (!strncmp(line, login, len)
28                  && line[len] == ':'
29                 ) {
30                         found++;
31                         free(line);
32                 } else {
33                         llist_add_to_end(&plist, line);
34                 }
35         }
36
37         if (!found) {
38                 bb_error_msg("can't find '%s' in '%s'", login, filename);
39                 if (!ENABLE_FEATURE_CLEAN_UP) return;
40                 goto clean_up;
41         }
42
43         if (ENABLE_FEATURE_CLEAN_UP)
44                 fclose(passwd);
45
46         passwd = fopen_or_warn(filename, "w");
47         if (passwd) {
48                 if (ENABLE_FEATURE_CLEAN_UP) {
49  clean_up:
50                         while ((line = llist_pop(&plist))) {
51                                 if (found) fputs(line, passwd);
52                                 free(line);
53                         }
54                         fclose(passwd);
55                 } else {
56                         /* found != 0 here, no need to check */
57                         while ((line = llist_pop(&plist)))
58                                 fputs(line, passwd);
59                 }
60         }
61 }
62
63 int deluser_main(int argc, char **argv)
64 {
65         if (argc != 2)
66                 bb_show_usage();
67
68         if (ENABLE_DELUSER
69          && (!ENABLE_DELGROUP || applet_name[3] == 'u')
70         ) {
71                 del_line_matching(argv[1], bb_path_passwd_file);
72                 if (ENABLE_FEATURE_SHADOWPASSWDS)
73                         del_line_matching(argv[1], bb_path_shadow_file);
74         }
75         del_line_matching(argv[1], bb_path_group_file);
76         if (ENABLE_FEATURE_SHADOWPASSWDS)
77                 del_line_matching(argv[1], bb_path_gshadow_file);
78
79         return EXIT_SUCCESS;
80 }
81
82 /* $Id: deluser.c,v 1.4 2003/07/14 20:20:45 andersen Exp $ */