[Libguestfs] [PATCH 1/3] daemon: Rearrange code in 'file' command.

Richard W.M. Jones rjones at redhat.com
Fri Jun 4 14:34:17 UTC 2010


-- 
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
virt-top is 'top' for virtual machines.  Tiny program with many
powerful monitoring features, net stats, disk stats, logging, etc.
http://et.redhat.com/~rjones/virt-top
-------------- next part --------------
>From e3befe5a2e85179dcc5a52aa7d74b9cc5f3430ec Mon Sep 17 00:00:00 2001
From: Richard Jones <rjones at redhat.com>
Date: Fri, 4 Jun 2010 11:23:01 +0100
Subject: [PATCH 1/3] daemon: Rearrange code in 'file' command.

  path = path to access file (/sysroot/.. or /dev/..)
  display_path = original path, saved so we can display it
  buf = optional buffer which is freed along return codepaths

There should be no change to the semantics of the code.
---
 daemon/file.c |   31 +++++++++++++++----------------
 1 files changed, 15 insertions(+), 16 deletions(-)

diff --git a/daemon/file.c b/daemon/file.c
index 7600064..2594207 100644
--- a/daemon/file.c
+++ b/daemon/file.c
@@ -512,20 +512,18 @@ do_pwrite (const char *path, const char *content, size_t size, int64_t offset)
 char *
 do_file (const char *path)
 {
-  char *out, *err;
-  int r, freeit = 0;
-  char *buf;
-  int len;
+  char *buf = NULL;
+  const char *display_path = path;
 
-  if (STREQLEN (path, "/dev/", 5))
-    buf = (char *) path;
-  else {
+  int is_dev = STRPREFIX (path, "/dev/");
+
+  if (!is_dev) {
     buf = sysroot_path (path);
     if (!buf) {
       reply_with_perror ("malloc");
       return NULL;
     }
-    freeit = 1;
+    path = buf;
   }
 
   /* file(1) manpage claims "file returns 0 on success, and non-zero on
@@ -533,26 +531,27 @@ do_file (const char *path)
    * every scenario I can think up.  So check the target is readable
    * first.
    */
-  if (access (buf, R_OK) == -1) {
-    if (freeit) free (buf);
-    reply_with_perror ("access: %s", path);
+  if (access (path, R_OK) == -1) {
+    reply_with_perror ("access: %s", display_path);
+    free (buf);
     return NULL;
   }
 
-  r = command (&out, &err, "file", "-zbsL", buf, NULL);
-  if (freeit) free (buf);
+  char *out, *err;
+  int r = command (&out, &err, "file", "-zbsL", path, NULL);
+  free (buf);
 
   if (r == -1) {
     free (out);
-    reply_with_error ("%s: %s", path, err);
+    reply_with_error ("%s: %s", display_path, err);
     free (err);
     return NULL;
   }
   free (err);
 
   /* We need to remove the trailing \n from output of file(1). */
-  len = strlen (out);
-  if (out[len-1] == '\n')
+  size_t len = strlen (out);
+  if (len > 0 && out[len-1] == '\n')
     out[len-1] = '\0';
 
   return out;			/* caller frees */
-- 
1.6.6.1



More information about the Libguestfs mailing list