Fix bug 603: "chown :root thingy" should work now.
[oweals/busybox.git] / coreutils / chown.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini chown implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 /* BB_AUDIT SUSv3 defects - unsupported options -h, -H, -L, and -P. */
11 /* BB_AUDIT GNU defects - unsupported options -h, -c, -f, -v, and long options. */
12 /* BB_AUDIT Note: gnu chown does not support -H, -L, or -P. */
13 /* http://www.opengroup.org/onlinepubs/007904975/utilities/chown.html */
14
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include "busybox.h"
19
20 static uid_t uid = -1;
21 static gid_t gid = -1;
22
23 static int (*chown_func)(const char *, uid_t, gid_t) = chown;
24
25 static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
26 {
27         if (!chown_func(fileName,
28                                 (uid == -1) ? statbuf->st_uid : uid,
29                                 (gid == -1) ? statbuf->st_gid : gid)) {
30                 return TRUE;
31         }
32         bb_perror_msg("%s", fileName);  /* A filename could have % in it... */
33         return FALSE;
34 }
35
36 #define FLAG_R 1
37 #define FLAG_h 2
38
39 int chown_main(int argc, char **argv)
40 {
41         int flags;
42         int retval = EXIT_SUCCESS;
43         char *groupName;
44
45         flags = bb_getopt_ulflags(argc, argv, "Rh");
46
47         if (flags & FLAG_h) chown_func = lchown;
48
49         if (argc - optind < 2) {
50                 bb_show_usage();
51         }
52
53         argv += optind;
54
55         /* First, check if there is a group name here */
56         if ((groupName = strchr(*argv, '.')) == NULL) {
57                 groupName = strchr(*argv, ':');
58         }
59
60         /* Check for the username and groupname */
61         if (groupName) {
62                 *groupName++ = '\0';
63                 gid = get_ug_id(groupName, bb_xgetgrnam);
64         }
65         if (--groupName != *argv) uid = get_ug_id(*argv, bb_xgetpwnam);
66         ++argv;
67
68         /* Ok, ready to do the deed now */
69         do {
70                 if (! recursive_action (*argv, (flags & FLAG_R), FALSE, FALSE,
71                                                                 fileAction, fileAction, NULL)) {
72                         retval = EXIT_FAILURE;
73                 }
74         } while (*++argv);
75
76         return retval;
77 }
78
79 /*
80 Local Variables:
81 c-file-style: "linux"
82 c-basic-offset: 4
83 tab-width: 4
84 End:
85 */