daemon: Split out checksum type to program name mapping into function.
[libguestfs.git] / daemon / checksum.c
index 2423265..4ee6231 100644 (file)
 #include "daemon.h"
 #include "actions.h"
 
-char *
-do_checksum (const char *csumtype, const char *path)
+static const char *
+program_of_csum (const char *csumtype)
 {
-  const char *program;
-  char *buf;
-  char *out, *err;
-  int r;
-  int len;
-
-  if (strcasecmp (csumtype, "crc") == 0)
-    program = "cksum";
-  else if (strcasecmp (csumtype, "md5") == 0)
-    program = "md5sum";
-  else if (strcasecmp (csumtype, "sha1") == 0)
-    program = "sha1sum";
-  else if (strcasecmp (csumtype, "sha224") == 0)
-    program = "sha224sum";
-  else if (strcasecmp (csumtype, "sha256") == 0)
-    program = "sha256sum";
-  else if (strcasecmp (csumtype, "sha384") == 0)
-    program = "sha384sum";
-  else if (strcasecmp (csumtype, "sha512") == 0)
-    program = "sha512sum";
+  if (STRCASEEQ (csumtype, "crc"))
+    return "cksum";
+  else if (STRCASEEQ (csumtype, "md5"))
+    return "md5sum";
+  else if (STRCASEEQ (csumtype, "sha1"))
+    return "sha1sum";
+  else if (STRCASEEQ (csumtype, "sha224"))
+    return "sha224sum";
+  else if (STRCASEEQ (csumtype, "sha256"))
+    return "sha256sum";
+  else if (STRCASEEQ (csumtype, "sha384"))
+    return "sha384sum";
+  else if (STRCASEEQ (csumtype, "sha512"))
+    return "sha512sum";
   else {
     reply_with_error ("unknown checksum type, expecting crc|md5|sha1|sha224|sha256|sha384|sha512");
     return NULL;
   }
+}
 
-  /* Make the path relative to /sysroot. */
-  buf = sysroot_path (path);
-  if (!buf) {
-    reply_with_perror ("malloc");
+static char *
+checksum (const char *csumtype, const char *path)
+{
+  const char *program;
+  char *out, *err;
+  int r;
+  int len;
+
+  program = program_of_csum (csumtype);
+  if (program == NULL)
     return NULL;
-  }
 
-  r = command (&out, &err, program, buf, NULL);
-  free (buf);
+  r = command (&out, &err, program, path, NULL);
   if (r == -1) {
     reply_with_error ("%s: %s", program, err);
     free (out);
@@ -79,3 +78,24 @@ do_checksum (const char *csumtype, const char *path)
 
   return out;                  /* Caller frees. */
 }
+
+char *
+do_checksum (const char *csumtype, const char *path)
+{
+  /* Make the path relative to /sysroot. */
+  char *buf = sysroot_path (path);
+  if (!buf) {
+    reply_with_perror ("malloc");
+    return NULL;
+  }
+
+  char *r = checksum (csumtype, buf);
+  free (buf);
+  return r;
+}
+
+char *
+do_checksum_device (const char *csumtype, const char *device)
+{
+  return checksum (csumtype, device);
+}