[Toybox] [PATCH 5/5] Add new toy - chown.

Georgi Chorbadzhiyski gf at unixsol.org
Wed Mar 7 00:16:00 PST 2012


---
 toys/chown.c |  103 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 103 insertions(+), 0 deletions(-)
 create mode 100644 toys/chown.c

diff --git a/toys/chown.c b/toys/chown.c
new file mode 100644
index 0000000..e71ee9d
--- /dev/null
+++ b/toys/chown.c
@@ -0,0 +1,103 @@
+/* vi: set sw=4 ts=4:
+ *
+ * chown.c - Change ownership
+ *
+ * Copyright 2012 Georgi Chorbadzhiyski <georgi at unixsol.org>
+ *
+ * See http://pubs.opengroup.org/onlinepubs/009695399/utilities/chown.html
+ *
+ * TODO: Add support for -h
+ * TODO: Add support for -H
+ * TODO: Add support for -L
+ * TODO: Add support for -P
+
+USE_CHOWN(NEWTOY(chown, "<2Rfv", TOYFLAG_BIN))
+
+config CHOWN
+	bool "chown"
+	default y
+	help
+	  usage: chown [-R] [-f] [-v] group file...
+	  Change ownership of one or more files.
+
+	  -R	recurse into subdirectories.
+	  -f	suppress most error messages.
+	  -v	verbose output.
+*/
+
+#include "toys.h"
+
+#define FLAG_R 4
+#define FLAG_f 2
+#define FLAG_v 1
+
+DEFINE_GLOBALS(
+	uid_t owner;
+	gid_t group;
+	char *owner_name;
+	char *group_name;
+)
+
+#define TT this.chown
+
+static int do_chown(char *path) {
+	int ret = chown(path, TT.owner, TT.group);
+	if (toys.optflags & FLAG_v)
+		xprintf("chown(%s:%s, %s)\n", TT.owner_name, TT.group_name, path);
+	if (ret == -1 && !(toys.optflags & FLAG_f))
+		perror_msg("changing owner of '%s' to '%s:%s'", path,
+			TT.owner_name, TT.group_name);
+	toys.exitval |= ret;
+	return ret;
+}
+
+void chown_main(void)
+{
+	char **s;
+	char *owner = NULL, *group;
+	char *param1 = *toys.optargs;
+
+	TT.owner = -1;
+	TT.group = -1;
+	TT.owner_name = "";
+	TT.group_name = "";
+
+	group = strchr(param1, ':');
+	if (!group)
+		group = strchr(param1, '.');
+
+	if (group) {
+		group++;
+		struct group *g = getgrnam(group);
+		if (!g) {
+			error_msg("invalid group '%s'", group);
+			toys.exitval = 1;
+			return;
+		}
+		TT.group = g->gr_gid;
+		TT.group_name = group;
+		owner = param1;
+		owner[group - owner - 1] = '\0';
+	} else {
+		owner = param1;
+	}
+
+	if (owner && owner[0]) {
+		struct passwd *p = getpwnam(owner);
+		if (!p) {
+			error_msg("invalid owner '%s'", owner);
+			toys.exitval = 1;
+			return;
+		}
+		TT.owner = p->pw_uid;
+		TT.owner_name = owner;
+	}
+
+	for (s=toys.optargs + 1; *s; s++) {
+		if (toys.optflags & FLAG_R) {
+			dirtree_for_each(*s, do_chown);
+		} else {
+			do_chown(*s);
+		}
+	}
+}
-- 
1.7.5.1


 1331108160.0


More information about the Toybox mailing list