]> git.ipfire.org Git - thirdparty/libvirt.git/commitdiff
util: Implement virFileChownFiles()
authorStefan Berger <stefanb@linux.vnet.ibm.com>
Tue, 4 Apr 2017 16:22:31 +0000 (12:22 -0400)
committerStefan Berger <stefanb@linux.vnet.ibm.com>
Wed, 6 Jun 2018 14:48:41 +0000 (10:48 -0400)
Implement virFileChownFiles() which changes file ownership of all
files in a given directory.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
Reviewed-by: John Ferlan <jferlan@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
src/libvirt_private.syms
src/util/virfile.c
src/util/virfile.h

index 5540391fe894cb0d8cc3c042b56b61515956f5d3..e2ca00df857bf1a4b47aa12f1a006d3eec5866c7 100644 (file)
@@ -1768,6 +1768,7 @@ virFileActivateDirOverride;
 virFileBindMountDevice;
 virFileBuildPath;
 virFileCanonicalizePath;
+virFileChownFiles;
 virFileClose;
 virFileComparePaths;
 virFileCopyACLs;
index a2c4cebb5676c4294ff3ba031bafbff97656e589..e41881f6c91b32cb9cf01d3507d54e656dc519fe 100644 (file)
@@ -2980,6 +2980,61 @@ void virDirClose(DIR **dirp)
     *dirp = NULL;
 }
 
+
+/*
+ * virFileChownFiles:
+ * @name: name of the directory
+ * @uid: uid
+ * @gid: gid
+ *
+ * Change ownership of all regular files in a directory.
+ *
+ * Returns -1 on error, with error already reported, 0 on success.
+ */
+int virFileChownFiles(const char *name,
+                      uid_t uid,
+                      gid_t gid)
+{
+    struct dirent *ent;
+    int ret = -1;
+    int direrr;
+    DIR *dir;
+    char *path = NULL;
+
+    if (virDirOpen(&dir, name) < 0)
+        return -1;
+
+    while ((direrr = virDirRead(dir, &ent, name)) > 0) {
+        if (ent->d_type != DT_REG)
+            continue;
+
+        if (virAsprintf(&path, "%s/%s", name, ent->d_name) < 0)
+            goto cleanup;
+
+        if (chown(path, uid, gid) < 0) {
+            virReportSystemError(errno,
+                                 _("cannot chown '%s' to (%u, %u)"),
+                                 ent->d_name, (unsigned int) uid,
+                                 (unsigned int) gid);
+            goto cleanup;
+        }
+        VIR_FREE(path);
+    }
+
+    if (direrr < 0)
+        goto cleanup;
+
+    ret = 0;
+
+ cleanup:
+    VIR_FREE(path);
+
+    virDirClose(&dir);
+
+    return ret;
+}
+
+
 static int
 virFileMakePathHelper(char *path, mode_t mode)
 {
index 6b0cbad4d1cabc2c38680d4a984fd39737465d36..c7a32c30a829bebda0d7e87bad286a7ee784f8a6 100644 (file)
@@ -238,6 +238,9 @@ int virFileOpenAs(const char *path, int openflags, mode_t mode,
     ATTRIBUTE_NONNULL(1) ATTRIBUTE_RETURN_CHECK;
 int virFileRemove(const char *path, uid_t uid, gid_t gid);
 
+int virFileChownFiles(const char *name, uid_t uid, gid_t gid)
+    ATTRIBUTE_NONNULL(1) ATTRIBUTE_RETURN_CHECK;
+
 enum {
     VIR_DIR_CREATE_NONE        = 0,
     VIR_DIR_CREATE_AS_UID      = (1 << 0),