changeset 1730:90a7ed7ec30e

Factor out xgetgrnamid() and xgetpwnamid() into xwrap.c.
author Rob Landley <rob@landley.net>
date Thu, 12 Mar 2015 11:11:08 -0500
parents 801eba977271
children 5a00bc5e1c0f
files lib/lib.h lib/xwrap.c toys/posix/chgrp.c
diffstat 3 files changed, 37 insertions(+), 16 deletions(-) [+]
line wrap: on
line diff
--- a/lib/lib.h	Wed Mar 11 23:05:54 2015 -0500
+++ b/lib/lib.h	Thu Mar 12 11:11:08 2015 -0500
@@ -123,6 +123,8 @@
 struct group *xgetgrgid(gid_t gid);
 struct passwd *xgetpwnam(char *name);
 struct group *xgetgrnam(char *name);
+struct passwd *xgetpwnamid(char *user);
+struct group *xgetgrnamid(char *group);
 void xsetuser(struct passwd *pwd);
 char *xreadlink(char *name);
 long xparsetime(char *arg, long units, long *fraction);
--- a/lib/xwrap.c	Wed Mar 11 23:05:54 2015 -0500
+++ b/lib/xwrap.c	Thu Mar 12 11:11:08 2015 -0500
@@ -477,6 +477,38 @@
   return group;
 }
 
+struct passwd *xgetpwnamid(char *user)
+{
+  struct passwd *up = getpwnam(user);
+  uid_t uid;
+
+  if (!up) {
+    char *s = 0;
+
+    uid = estrtol(user, &s, 10);
+    if (!errno && s && !*s) up = getpwuid(uid);
+  }
+  if (!up) perror_exit("user '%s'", user);
+
+  return up;
+}
+
+struct group *xgetgrnamid(char *group)
+{
+  struct group *gr = getgrnam(group);
+  gid_t gid;
+
+  if (!gr) {
+    char *s = 0;
+
+    gid = estrtol(group, &s, 10);
+    if (!errno && s && !*s) gr = getgrgid(gid);
+  }
+  if (!gr) perror_exit("group '%s'", group);
+
+  return gr;
+}
+
 struct passwd *xgetpwnam(char *name)
 {
   struct passwd *up = getpwnam(name);
--- a/toys/posix/chgrp.c	Wed Mar 11 23:05:54 2015 -0500
+++ b/toys/posix/chgrp.c	Thu Mar 12 11:11:08 2015 -0500
@@ -82,30 +82,17 @@
   // Distinguish chown from chgrp
   if (ischown) {
     char *grp;
-    struct passwd *p;
 
     own = xstrdup(*toys.optargs);
     if ((grp = strchr(own, ':')) || (grp = strchr(own, '.'))) {
       *(grp++) = 0;
       TT.group_name = grp;
     }
-    if (*own) {
-      TT.owner_name = own;
-      p = getpwnam(own);
-      // TODO: trailing garbage?
-      if (!p && isdigit(*own)) p=getpwuid(atoi(own));
-      if (!p) error_exit("no user '%s'", own);
-      TT.owner = p->pw_uid;
-    }
+    if (*own) TT.owner = xgetpwnamid(TT.owner_name = own)->pw_uid;
   } else TT.group_name = *toys.optargs;
 
-  if (TT.group_name && *TT.group_name) {
-    struct group *g;
-    g = getgrnam(TT.group_name);
-    if (!g) g=getgrgid(atoi(TT.group_name));
-    if (!g) error_exit("no group '%s'", TT.group_name);
-    TT.group = g->gr_gid;
-  }
+  if (TT.group_name && *TT.group_name)
+    TT.group = xgetgrnamid(TT.group_name)->gr_gid;
 
   for (s=toys.optargs+1; *s; s++) {
     struct dirtree *new = dirtree_add_node(0, *s, hl);